-1

我已将我的问题缩小到这段代码:

<?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 很陌生。

4

2 回答 2

3

您正在尝试将 mysql_* 函数与mysqli一起使用。这是两个非常不同的事情。看看mysqli_connect函数。

开始这一切的错误是:

警告:mysqli_query() 期望参数 1 是 mysqli,给定资源

这意味着 mysqli_query 函数期望 mysqli 链接作为其第一个参数。相反,它收到了一个资源,因为 mysql_connect 将返回一个 MySQL 链接标识符资源变量。手册中的 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();
?>
于 2013-10-26T18:00:57.020 回答
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;
?>
于 2013-10-26T18:04:44.427 回答