我只想从数据库中选择和显示数据。我想我在网上关注所有教程等但是有些不对劲。我的代码:
<?php
$user = 'root';
$pass = 'root';
$db='test';
$host ='localhost';
$name = 'ryan';
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
else{
echo 'Checkpoint 1 <br>';
}
$sql = "SELECT * FROM user WHERE name LIKE ryan";
$result = $mysqli->query($sql);
$num_results = $result->num_rows;
echo'checkpoint 2';
$row = $result->fetch_assoc();
echo'checkpoint 3';
?>
我可以到达检查站2&#39;但由于某种原因,fetch_assoc()函数不执行任何操作。我正在使用Netbeans,而fetch_assoc()甚至没有像num_rows函数那样变为绿色。如果我在末尾删除两个括号,fetch_assoc会变为绿色。
答案 0 :(得分:1)
您的mysql查询语法错误
LIKE
采用一种模式,通过不将其括在引号中,您基本上提供了一个列名
像这样更改您的查询
SELECT * FROM `user` WHERE `name` LIKE 'ryan';
还为查询添加一些错误处理
$result = $mysqli->query($sql) or die(mysqli->error);
答案 1 :(得分:0)
尝试此查询:
$sql = "SELECT * FROM user WHERE name LIKE 'ryan'";
答案 2 :(得分:0)
您必须将您的like语句绑定为
$param = "%ryan%";
$result = $mysqli->prepare("SELECT * FROM user WHERE name LIKE ?");
$result->bind_param("s", $param);
$result->execute();
$num_results = $result->num_rows;
$row = $result->fetch_assoc();
答案 3 :(得分:0)
<?php
$user = 'root';
$pass = 'root';
$db='test';
$host ='localhost';
$name = 'ryan';
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
else{
echo 'Checkpoint 1 <br>';
}
$sql = "SELECT * FROM user WHERE name LIKE 'ryan'";
$result = $mysqli->query($sql);
$num_results = $result->num_rows;
print_r($num_results);exit;
echo'checkpoint 2';
$row = $result->fetch_assoc();
echo'checkpoint 3';
?>
答案 4 :(得分:0)
您可以使用LIKE
和quotes
符号将字符串输入与%
语句结合使用。
修改后的代码:
$sql = "SELECT * FROM user WHERE name LIKE '%ryan%'";
$result = $mysqli->query($sql);
$num_results = $result->num_rows;
$row = $result->fetch_assoc();
我改变了什么?