我编写了这段代码,但是在stackoverflow上的人们指出这些函数将被弃用。所以我用mysqli函数更新它。新的不会返回我想显示的图片网址。
这是旧的工作代码:
<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>
最佳答案
您实际上尚未通过$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