我正在使用变量记录有关网站用户的信息,以观察他们在我网站上的行为。我的代码如下所示:
<?php
$pages_visited = "www.example.com, www.example.com/example.php, www.example.com/demo.php";
$con = mysqli_connect("localhost", "user", "password", "pages_visited");
if (mysqli_connect_errno()) {
echo "An error occurred when connecting to the database. Sorry.";
}
mysqli_query($con, "INSERT INTO visit_data ('Pages')
VALUES ('$pages_visited')");
mysqli_close($con);
但是,当我访问我的网站时,没有任何反应,并且表visit_data中没有添加新行。为什么会这样?
答案 0 :(得分:1)
尝试mysqli预处理语句(错误与不使用预处理语句无关,但我认为最好使用,因为不推荐使用mysql函数)
$db = new mysqli('localhost', 'root', '', 'database');
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
$pages_visited = "www.example.com, www.example.com/example.php, www.example.com/demo.php";
$stmt = $db->prepare("insert into `visit_data` (Pages) values(?)");
$stmt->bind_param('s', $pages_visited);
$stmt->execute();
答案 1 :(得分:1)
您需要更新您的查询:
INSERT INTO visit_data (`Pages`) VALUES('".$pages_visited."')
实际上你正在使用单引号(&#39; Pages&#39;), 检查波纹管代码。 我已在本地验证此代码正在运行
<?php
$pages_visited = "www.example.com, www.example.com/example.php, www.example.com/demo.php";
$con = mysqli_connect("localhost", "user", "password", "pages_visited");
if (mysqli_connect_errno()) {
echo "An error occurred when connecting to the database. Sorry.";
}
$try = mysqli_query($con, "INSERT INTO visit_data (`Pages`) VALUES('".$pages_visited."')");
if($try === false){
echo 'error - ';
echo mysqli_error($con);
} else{
echo 'all good';
}
mysqli_close($con);
答案 2 :(得分:-1)
使用字符串时,你必须使用'。$。text_var。“'。确保您使用的表列是正确的,并且除非您在创建表时使用默认值,否则不要遗漏任何不接受空值的列。
这应该有效
<?php
$pages_visited = "www.example.com, www.example.com/example.php, www.example.com/demo.php";
$con = mysqli_connect("localhost", "user", "password", "pages_visited");
if ( mysqli_connect_errno() )
{
echo "An error occurred when connecting to the database. Sorry.";
}
mysqli_query( $con, "INSERT INTO visit_data ( Pages ) VALUES ( '" . $pages_visited . "' )" );
mysqli_close($con);