[php] mysql query result in php variable

Is there any way to store mysql result in php variable? thanks

$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);

then I want to print selected userid from query.

This question is related to php mysql

The answer is


I personally use prepared statements.

Why is it important?

Well it's important because of security. It's very easy to do an SQL injection on someone who use variables in the query.

Instead of using this code:

$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);

You should use this

$stmt = $this->db->query("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password); //You need the variables to do something as well.
$stmt->execute();

Learn more about prepared statements on:

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php MySQLI

http://php.net/manual/en/pdo.prepared-statements.php PDO


$query="SELECT * FROM contacts";
$result=mysql_query($query);

There are a couple of mysql functions you need to look into.

  • mysql_query("query string here") : returns a resource
  • mysql_fetch_array(resource obtained above) : fetches a row and return as an array with numerical and associative(with column name as key) indices. Typically, you need to iterate through the results till expression evaluates to false value. Like the below:

    while ($row = mysql_fetch_array($query)){
        print_r $row;
    }

    Consult the manual, the links to which are provided below, they have more options to specify the format in which the array is requested. Like, you could use mysql_fetch_assoc(..) to get the row in an associative array.

Links:

In your case,

$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=mysql_query($query);
if (!$result){
    die("BAD!");
}
if (mysql_num_rows($result)==1){
    $row = mysql_fetch_array($result);
    echo "user Id: " . $row['userid'];
}
else{
    echo "not found!";
}

$query    =    "SELECT username, userid FROM user WHERE username = 'admin' ";
$result    =    $conn->query($query);

if (!$result) {
  echo 'Could not run query: ' . mysql_error();
  exit;
}

$arrayResult    =    mysql_fetch_array($result);

//Now you can access $arrayResult like this

$arrayResult['userid'];    // output will be userid which will be in database
$arrayResult['username'];  // output will be admin

//Note- userid and username will be column name of user table.