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.
The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.
Mysql also supports the concept of User-defined variables, which allows passing of a value from one statement to another. A user-defined variable in Mysql is written as @var_name where, var_name is the name of the variable and can consist of alphanumeric characters, ., _, and $.
Of course there is. Check out mysql_query
, and mysql_fetch_row
if you use MySQL.
Example from PHP manual:
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
There are a couple of mysql functions you need to look into.
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!";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With