In PHP, querying the database is a very common operation. The query results are often returned in the form of an array. For this reason, we need to assign the query results to an array variable for subsequent operations. This article explains how to query data in PHP and assign the results to an array.
Before performing any database operations, we need to connect to the database first. The following is a simple example of connecting to a MySQL database:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = mysqli_connect($servername, $username, $password, $dbname); // 检测连接 if (!$conn) { die("连接失败: " . mysqli_connect_error()); } echo "连接成功"; ?>
In the above code, we first define some parameters required to connect to the MySQL database, including server name, user name, password, database name, etc. Then use the mysqli_connect()
function to create a connection object $conn
. This function needs to pass in $servername
, $username
, ## Parameters such as #$password and
$dbname. Finally, we determine if the connection was successful by checking if
$conn is
false.
<?php $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { // 输出每行数据 while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; } } else { echo "0 结果"; } mysqli_close($conn); ?>
$sql variable to save the query statement. Then use the
mysqli_query() function to execute the
$sql statement. This function needs to pass in the connection object
$conn and the query statement
$sql parameters.
mysqli_query() function will return a result set
$result, which contains all the queried data. We can get each row of data in a way similar to array subscripting.
mysqli_fetch_assoc() The function can fetch a row of data from the result set
$result and return it to the variable
$row as an associative array.
mysqli_num_rows() Function is used to get the number of rows in the result set.
mysqli_close() function to close the connection.
<?php $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = mysqli_query($conn, $sql); $myArray = array(); // 定义一个空数组 if (mysqli_num_rows($result) > 0) { // 输出每行数据 while($row = mysqli_fetch_assoc($result)) { $myArray[] = $row; // 将关联数组 $row 添加到数组 $myArray 中 } } else { echo "0 结果"; } mysqli_close($conn); print_r($myArray); // 输出数组 ?>
$myArray. Then in the loop, each time the
$row associative array is added to the
$myArray array, i.e.
$myArray[] = $row;. Finally, we can use the
print_r() function to output the array
$myArray to the page.
The above is the detailed content of How to query data assignment array in php. For more information, please follow other related articles on the PHP Chinese website!