0

我写了这段代码,但是 stackoverflow 上的人指出这些函数将被弃用。所以我用 mysqli 函数更新它。新的不会返回我想显示的图像 url。

这是旧的工作代码:

<html>
<head>

<title>My first PHP script</title>
</head>
<body> 

<?php

$dbhost = 'access.website';
$dbname = 'my_db';
$dbuser = 'usr_nam';
$dbpass = 'passwrd';

$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
    or die("Error Connecting To Database Server");

mysql_select_db($dbname, $mysql_handle)
    or die("Error selecting database: $dbname");

$query = sprintf("SELECT image_url, Type FROM Pokemon 
    c WHERE c.name='%s'", 
    mysql_real_escape_string($_GET["fname"]));

$result = mysql_fetch_assoc(mysql_query($query));   

echo '<img height="450" width="330" src="'.$result['image_url'].'" />';

mysql_close($mysql_handle);

?>

</body>
</html>

这是我的新代码:

<html>
<head>

  <title>My first PHP script</title>
</head>
<body> 

<?php

$dbhost = 'access.website';
$dbname = 'my_db';
$dbuser = 'usr_nam';
$dbpass = 'passwrd';

$link = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);

mysqli_select_db($link,$dbname);

$query = sprintf("SELECT image_url, Type FROM Pokemon 
    c WHERE c.name='%s'", 
    mysqli_real_escape_string($link,$_GET["fname"]));

$result = mysqli_query($link,$query);   

echo '<img height="450" width="330" src="'.$result['image_url'].'" />';

mysqli_close($link);

?>

</body>
</html>
4

1 回答 1

3

您实际上并没有通过或类似方式从$result资源中获取结果:mysqli_fetch_assoc()

$result = mysqli_query($link,$query);   
$row = mysqli_fetch_assoc($result);

echo '<img height="450" width="330" src="'.$row['image_url'].'" />';

另一个建议:虽然您已切换到 MySQLi,但您并没有通过准备好的语句获得其主要的安全优势。使用准备好的语句和占位符会更好地完成此操作:

// MySQLi object-oriented version with a prepared statement
$mysqli = new mysqli('host','user','pass','dbname');
// Prepare the query and placeholder
$stmt = $mysqli->prepare("SELECT image_url, Type FROM Pokemon c WHERE c.name=?");
// Bind input var & execute
$stmt->bind_param('s', $_GET['fname']);
$stmt->execute();
$stmt->bind_result($img_url)
$stmt->fetch();

echo '<img height="450" width="330" src="'.$img_url.'" />';

或非 OO 版本:

// $link is already defined
$stmt = mysqli_prepare($link, "SELECT image_url, Type FROM Pokemon c WHERE c.name=?");
mysqli_stmt_bind_param($stmt, 's', $_GET['fname']);
mysqli_stmt_execute($stmt);
// Bind output var & fetch
mysqli_stmt_bind_result($stmt, $img_url);
mysqli_stmt_fetch($stmt);
// $img_url now holds the value
于 2012-11-08T03:19:10.323 回答