简体   繁体   中英

Using mysql query output as variable in php

I am trying to use the output of an SQL query (in this case the output will be something like 26 "http://www.google.com"

I want to use the id and address in a process in php but cant seem to do anything with the output of the query other than echo it.

ultimately if i could end up with $id and $pos as variables that i could use that would be great.

<?php
$con = mysql_connect("localhost","root","root");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("movieCol", $con);
$query = "SELECT * FROM `movie_collection` ORDER BY `id` DESC LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['id']. " ". $row['poster'];
mysql_close($con);
?>

If you want them as separate variables then:

$query = "SELECT id, poster FROM `movie_collection` ORDER BY `id` DESC LIMIT 1";

...

list($id, $pos) = mysql_fetch_row($result);

echo $id. " ". $pos;

Although functionally this won't be any more or less beneficial than using the array elements that you already had.

You could also use extract() which populates individual variables with the array elements:

$row = mysql_fetch_array($result) or die(mysql_error());
extract($row);
echo $id. " ". $pos . " " . $director; // access all variables

Extracting is not recommended though, there really is no benefit over using the array elements.

Just assign the values to variables as: $id=$row['id']; and $pos=$row['poster'];

Now you can use the variables $id and $pos wherever you want.

I hope this is what you wanted.

Are you looking to something like this?

<?php
$con = mysql_connect("localhost","root","root");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("movieCol", $con);
$query = "SELECT * FROM `movie_collection` ORDER BY `id` DESC LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());

$whatYouWant = $row['id']. " ". $row['poster'];

mysql_close($con);
?><html>
<head><title><?=$whatYouWant?></title></head>
<body><h1><?=$whatYouWant?></h1></body></html>

All the warning about mysql_* being deprecated remain valid, of course. They become risky if your SQL contains anything that comes from outside the PHP script, like this:

NEVER DO THIS:

$value=$_REQUEST['item_id'];
$query = "SELECT * FROM `movie_collection` WHERE `id`=$value DESC LIMIT 1";

Consider PDO or mysqli, etc.. as others have suggested (or at least remember to filter $value correctly every time).

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