这是我简单的PHP代码:
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "********"; //hiding my password
$dbname = "course";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM tutors";
$result = $conn->query($sql);
if( $result === true ) {
echo "good";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
while($row = $result->fetch_assoc()) {
echo $row["name"];
}
?>
</body>
</html>
在我的名为&#34; course&#34;的数据库中,我有一个名为&#34; tutors&#34;它有一个名为&#34; name&#34;的列。我在该表中有两个条目,名称为#34;深思熟虑&#34;和#34;比利牛斯&#34;分别
但是,当此代码运行时,唯一打印出来的是:
错误:SELECT name FROM tutors
应该简单地打印出我之前提到的两个名字。
有谁知道为什么会这样?我知道我的桌子上有两个条目!
答案 0 :(得分:2)
我认为“name”这个词是MySQL reserved word。将查询变量包装在一个波浪号反引号中,如下所示:
$sql = "SELECT `name` FROM `tutors`";
这有助于从MySQL中逃避这些值,以为您正在尝试引用内置变量。
答案 1 :(得分:-1)
为什么不像这样使用mysqli:
function getFollowers($link, $userid)
{
$sql = "SELECT users.id, username, profileImg FROM following INNER JOIN users ON users.id = following.userid WHERE followid = " . $userid;
$result = mysqli_query($link,$sql);
$resultsArray = [];
while($row = mysqli_fetch_assoc($result)) {
$resultsArray[] = $row;
}
mysqli_free_result($result);
return $resultsArray;
}
这只是一个干净的例子,我相信你明白了。
以下是$ link
function connection()
{
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_NAME', 'databaseTable');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
return $link;
}
或没有方法:
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_NAME', 'databaseTable');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT name FROM tutors";
$result = mysqli_query($link,$sql);
$resultsArray = [];
while($row = mysqli_fetch_assoc($result)) {
echo $row["name"];
}
mysqli_free_result($result);
要检查查询是否成功,您可以执行以下操作:
if (mysqli_num_rows($result) > 0)
{
//has rows, so whatever you want with them.
}
在定义$ result后放置条件。