gpt4 book ai didi

php - 第一个参数必须是字符串

转载 作者:行者123 更新时间:2023-11-29 11:53:15 26 4
gpt4 key购买 nike

下面这段代码有什么问题-:

            <?php

if($_SERVER["REQUEST_METHOD"]=="POST")
{
require 'connection.php';
create_user();
}

function create_user(){
global $connect;

$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$age = $_POST["age"];

$query = "Insert into usertable(name, username, password, age) values ('$name','$username','$password','$age');";

mysqli_connect($connect, $query) or die (mysqli_error($connect));
mysqli_close($connect);
}

?>

它给出以下错误,我给出的第一个参数仅是字符串-:

        <br />
<b>Warning</b>: mysqli_connect() expects parameter 1 to be string, object given in
<b>C:\xampp\htdocs\webservice\insertuser.php</b> on line
<b>19</b>
<br />
can't connect

第 19 行是 mysqli_connect($connect, $query) 或 die (mysqli_error($connect));

最佳答案

准备好的语句与绑定(bind)一起使用。没有sql注入(inject)。打开错误报告。

这是端到端的。

更改连接参数。

你的变量自然会来自$_POST[],而我对它们进行了硬编码。你明白了。我希望如此。

切勿在未按照您的方式进行绑定(bind)的情况下使用用户提供的数据。即使在插入语句中也是如此。除非你想要二级sql注入(inject)攻击。

架构

create table data
( id int auto_increment primary key,
`name` varchar(100) not null,
email varchar(100) not null,
phone varchar(100) not null,
facebook varchar(100) not null,
linkedin varchar(100) not null,
twitter varchar(100) not null,
yourstory varchar(100) not null
);

PHP

<?php
//mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
mysqli_report(MYSQLI_REPORT_ALL);
error_reporting(E_ALL); // report all PHP errors
ini_set("display_errors", 1);
echo "start<br/>";
$name='a';
$email='b';
$phone='c';
$facebook='d';
$linkedin='e';
$twitter='f';
$yourstory='g';

try {
$mysqli= new mysqli('host', 'dbuser', 'password', 'databaseName');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
echo "I am connected and feel happy.<br/>";
$query = "INSERT INTO `data`(`name`, email, phone, facebook, linkedin, twitter, yourstory)";
$query .= " VALUES (?,?,?,?,?,?,?)";
echo "1<br/>";
$stmt = $mysqli->prepare($query);
echo "2<br/>";
// note the 7 s's below, s is for string
$stmt->bind_param("sssssss", $name, $email, $phone,$facebook,$linkedin,$twitter,$yourstory);
echo "3<br/>";
$stmt->execute();
echo "4<br/>";
$stmt->close();
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
?>

结果

select * from data;
+----+------+-------+-------+----------+----------+---------+-----------+
| id | name | email | phone | facebook | linkedin | twitter | yourstory |
+----+------+-------+-------+----------+----------+---------+-----------+
| 1 | a | b | c | d | e | f | g |
+----+------+-------+-------+----------+----------+---------+-----------+

关于php - 第一个参数必须是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33644361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com