我正在尝试创建一个网站,其中php与后端sql连接。有1行的用户名='user1'。
但是,这个简单的PHP代码可以获取“ user1”的详细信息-
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with password 'root') */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_NAME', 'startup');
/* Attempt to connect to MySQL database */
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
echo '<p>Connected successfully</p>';
$sql = "SELECT id, username, password FROM users WHERE username = ?";
$stmt = mysqli_prepare($link, $sql);
$param_username = "user1";
mysqli_stmt_bind_param($stmt, "s", $param_username);
mysqli_stmt_execute($stmt);
// mysqli_stmt_store_result($stmt);
echo '<p>done</p>';
$val = mysqli_stmt_num_rows($stmt);
printf("%%d = '%d'\n", $val); // standard integer representation
?>
以上代码返回此输出-
当明显有1行的用户名='user1'时,$ val的值为0。请提供帮助,我需要在我的PHP脚本中获取“ user1”的详细信息。
答案 0 :(得分:0)
您需要在任何地方正确使用连接变量名。(在这种情况下,它是$conn
,但您使用的是$link
)
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with password 'root') */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_NAME', 'startup');
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
/* check connection */
if (!$conn) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$param_username = "user1";
$stmt = mysqli_prepare($conn, "SELECT id, username, password FROM users WHERE `username` = ?");
mysqli_stmt_bind_param($stmt, "s", $param_username);
/* execute prepared statement */
mysqli_stmt_execute($stmt);
printf("%d Row inserted.\n", mysqli_num_rows($stmt));
/* close statement and connection */
mysqli_stmt_close($stmt);
/* close connection */
mysqli_close($conn);
?>
答案 1 :(得分:-1)
您做错了什么,请对此进行更新并尝试
$sql = "SELECT id, username, password FROM users WHERE username = ?";
$stmt = mysqli_prepare($link, $sql);
$param_username = "user1";
mysqli_stmt_bind_param($stmt, "s", $param_username);
mysqli_stmt_execute($stmt);