使用PHP脚本获取数据
下面的程序是一个简单的示例,它将显示如何从tutorials_tbl表中获取/显示记录。
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysqli_error($conn));
}
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl';
mysqli_select_db($conn,'mydb');
$retval = mysqli_query( $conn, $sql );
if(! $retval ) {
die('Could not get data: ' . mysqli_error($conn));
}
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
echo "Tutorial ID :{$row['tutorial_id']} <br> ".
"Title: {$row['tutorial_title']} <br> ".
"Author: {$row['tutorial_author']} <br> ".
"Submission Date : {$row['submission_date']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysqli_close($conn);
尝试一下
将行的内容分配给变量$row,然后打印该行中的值。
注意 -当您想将数组值(PHP变量)直接插入字符串中时,请始终记住使用大括号。
在上面的示例中,常量
MYSQLI_ASSOC用作PHP函数
mysqli_fetch_array()的第二个参数,因此它将行作为关联数组返回。使用关联数组,您可以使用字段名称而不是使用索引来访问该字段。PHP提供了另一个名为
mysqli_fetch_assoc()的函数,该函数还将行作为关联数组返回。
例:下面的示例使用mysqli_fetch_assoc()函数显示tutorial_tbl表中的所有记录。
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysqli_error($conn));
}
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date
FROM tutorials_tbl';
mysqli_select_db($conn,'mydb');
$retval = mysqli_query( $conn, $sql );
if(! $retval ) {
die('Could not get data: ' . mysqli_error($conn));
}
while($row = mysqli_fetch_assoc($retval)) {
echo "Tutorial ID :{$row['tutorial_id']} <br> ".
"Title: {$row['tutorial_title']} <br> ".
"Author: {$row['tutorial_author']} <br> ".
"Submission Date : {$row['submission_date']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysqli_close($conn);
尝试一下
您还可以将常量MYSQLI_NUM用作PHP函数mysqli_fetch_array()的第二个参数。这将导致函数返回带有数字索引的数组。
例: 尝试以下示例使用MYSQL_NUM参数显示tutorials_tbl表中的所有记录。
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysqli_error($conn));
}
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date
FROM tutorials_tbl';
mysqli_select_db($conn,'mydb');
$retval = mysqli_query( $conn,$sql );
if(! $retval ) {
die('Could not get data: ' . mysqli_error($conn));
}
while($row = mysqli_fetch_array($retval, MYSQLI_NUM)) {
echo "Tutorial ID :{$row[0]} <br> ".
"Title: {$row[1]} <br> ".
"Author: {$row[2]} <br> ".
"Submission Date : {$row[3]} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysqli_close($conn);
?>
尝试一下
以上三个示例都将产生相同的结果。