如何在MySQLi语句中插入变量? [英] How to insert a variable in MySQLi statement?
本文介绍了如何在MySQLi语句中插入变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用MYSQLi在数据库中插入数据.如果我使用以下查询,则会插入数据;
I am trying to insert data in a database using MYSQLi. If I use the following query, data is inserted;
INSERT INTO table (Name, Phone, Location) VALUES ('test', 'test', 'test')
我需要插入变量的值,而不是值"test".但是,以下方法不起作用.
Instead of the value 'test', I need the value of a variable inserted. However the following does not work.
$test = 'xxx';
if ($stmt = $mysqli->prepare("INSERT INTO table (Name, Phone, Location) VALUES (".$test.", 'aaa', 'bbb')")) {
$stmt->execute();
$stmt->close();
}
我尝试了bind_param
命令,但是没有用.
I have tried the bind_param
command, but it didn't work.
$stmt->bind_param("ss", $name, $phone, $location);
如何直接插入变量?
推荐答案
在您的情况下,代码应如下所示:
In your case the code should be like this:
$test = 'xxx';
$stmt = $mysqli->prepare("INSERT INTO table (Name, Phone, Location) VALUES (?, 'aaa', 'bbb')");
$stmt->bind_param("s", $test);
$stmt->execute();
$stmt->close();
如果您希望此查询包含3个变量:
If you want to have 3 variables for this query:
$name = "My name";
$phone = "My phone number";
$location = "My location";
$stmt = $mysqli->prepare("INSERT INTO table (Name, Phone, Location) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $phone, $location);
$stmt->execute();
$stmt->close();
这篇关于如何在MySQLi语句中插入变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文