Jonhz Jonhz - 3 months ago 6
PHP Question

Store MySQLi query result in a PHP variable

All i want to do is to store the name of the guest that is on the A1 seat in a PHP variable named "resulted".

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'test';
$con=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if ($con->connect_error) {
die("Connection failed: " . $conn->connect_error);
}


$resulted = mysqli_query("SELECT name FROM guests WHERE seat='A1');

echo $resulted;
?>


I know this is totally wrong but I don't know how i shoud do it....

Answer

There is some issue in your code. I have fetched associative array amd print gust name.

    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = 'root';
    $dbname = 'test';
    $con=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
    if ($con->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }


    $resulted = mysqli_query($conn, "SELECT name FROM guest WHERE seat='A1'");
    if(mysqli_num_rows($resulted) > 0) {
     $row = mysqli_fetch_assoc($resulted);
      print_r($row['name']);
    }


    // Free result set
    mysqli_free_result($resulted);

    mysqli_close($con);

    ?>
Comments