简体   繁体   中英

Print the Result of a mysqli SELECT Query

I am trying to search my database for a result, and display all the columns relating to that result. My connection to the database works fine, but I don't know how to print the result of my query.

I tried accessing it as an array, but it did not work. What I want is to be able to search the database for the username 'TEST', and to return the password, email and username (to check the username exists).

My current code is this

$user = mysqli_query($con,"SELECT * FROM user_list where username = '$username'");
print_r($user); 

$username is the username. It returns this

(
    [current_field] => 0
    [field_count] => 4
    [lengths] => 
    [num_rows] => 2
    [type] => 0
)

Use Fetch to display the result

     $result = mysqli_query($con,"SELECT * FROM user_list where username = '" . mysqli_real_escape_string($con, $username) . "'"); 
    while($row = mysqli_fetch_array($result))
     {
        print_r($row);
     } 

You need to fetch the result first with mysqli_fetch_assoc

$userResult = mysqli_query($con,"SELECT * FROM user_list where username = '" . mysqli_real_escape_string($con, $username) . "'"); 
$user = mysqli_fetch_assoc($userResult);
print_r($user);
  • Avoid sql injections by escaping your strings.

To get the result of the mysqli_query() you need to use one of the functions, which return the rows. For examplefetch_all() to get all the rows or fetch_array() to get a single row.

You can also loop on the object directly.

$result = mysqli_query($con, 'SELECT ...');
foreach($result as $row) {
    print_r($row);
    // do something with each row
}

However, in your case you should not be using mysqli_query() at all! This leaves you vulnerable to SQL injection. You must use parameter binding, which is available with prepared statements.

For example your fixed query would look like this:

$stmt = $con->prepare('SELECT * FROM user_list where username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
foreach ($result as $row) {
    print_r($row);
}

The difference is that my variable is not separate from the SQL, so there is no risk of injection. You should never allow any variable input directly in SQL query. Doing this properly is really not that difficult.

You have to fetch your result:

$user = mysqli_query($con,"SELECT * FROM user_list where username = '$username'");

while ($row = $user->fetch_row()) {
        print_r($row);
    }
while($row = mysql_fetch_array($user, MYSQL_ASSOC))
{
    echo "MATE :{$row['MATE']}  <br> ".
         "TEST : {$row['TEST']} <br> ".
         "--------------------------------<br>";
}
it's may work your you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM