我已将问题缩小到这段代码:
<?php
$mysql_host = "mysqlXX.000webhost.com";
$mysql_user = "a4935911_******";
$mysql_password = "******";
$con = mysql_connect($mysql_host, $mysql_user, $mysql_password) or die(mysql_error());
$db = mysql_select_db('a4935911_******', $con) or die(mysql_error());
$getuname = mysqli_fetch_assoc(mysqli_query($con, "SELECT username FROM users WHERE id = 4"));
$username = $getuname ['username'];
echo "Username = " .$username;
?>
我在两页上有这个。 第一个工作正常,输出'admin'按预期输出,而第二个给我两个错误:
警告:mysqli_query()要求参数1为mysqli,第11行/home/a4935911/public_html/requestUser.php中给出的资源
警告:mysqli_fetch_assoc()期望参数1为mysqli_result,在第11行的/home/a4935911/public_html/requestUser.php中给出为null
这怎么只会导致其中一个页面出现问题?有什么帮助吗?
更新
<?php
$con=mysqli_connect("mysqlXX.000webhost.com","a4935911_XXX","XXXX","a4935911_XXX");
$id = $_SESSION['uid'];
$getuname = mysqli_fetch_assoc(mysqli_query($con, "SELECT username FROM users WHERE id = $id"));
$username = $getuname ['username'];
echo "Username = " .$username;
?>
错误:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in /home/a4935911/public_html/requestUser.php on line 4
PHP是无情的。这次我错过了什么?你可以看到我对PHP很新。
答案 0 :(得分:3)
您正尝试将mysqli用于mysql_ *函数。这是两件截然不同的事情。看看mysqli_connect功能。
启动它的错误是:
警告:mysqli_query()要求参数1为mysqli,resource 给定
这意味着mysqli_query函数期望将mysqli链接作为其第一个参数。相反,它收到一个资源,因为mysql_connect将返回一个MySQL链接标识符资源变量。来自manual:
的mysqli示例<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/*
* Use this instead of $connect_error if you need to ensure
* compatibility with PHP versions prior to 5.2.9 and 5.3.0.
*/
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();
?>
答案 1 :(得分:0)
试试这个:
$mysql_host = "mysqlXX.000webhost.com";
$mysql_user = "a4935911_******";
$mysql_password = "******";
$con = new mysqli($mysql_host, $mysql_user, $mysql_password,'database_name');
if (mysqli_connect_errno()) die('Could not connect: ' . mysqli_connect_error());
$getuname = mysqli_fetch_assoc(mysqli_query($con, "SELECT username FROM users WHERE id = 4"));
$username = $getuname ['username'];
echo "Username = " .$username;
?>
<强>更新强>
<?php
$con=mysqli_connect("mysqlXX.000webhost.com","a4935911_XXX","XXXX","a4935911_XXX");
$id = $_SESSION['uid'];
$result=$con->query("SELECT username FROM users WHERE id = $id");
$getuname = mysqli_fetch_array($result);
$username = $getuname ['username'];
echo "Username = " .$username;
?>