简体   繁体   中英

Turning a result from a query into a PHP variable

The query below is on a page where there is only one value for $submissionid . Thus, the field points has only one value.

How can I turn the points from the query below into a regular PHP variable?

  $sqlStra = "SELECT points, submissionid
               FROM submission 
              WHERE submissionid = '$submissionid'";

EDIT: This is pulling from a MySQL database.

EDIT II: I want to points to equal a variable on the entire page, not just inside of a while loop.

In this way you can read all the points returned by your query.

while ($row = mysql_fetch_array($sqlStra, MYSQL_ASSOC)) {
    $points = $row["points"]);
}

I would use an ORM library (I use the one that comes bundled with Kohana ) to eliminate the possibility of SQL injections. However, assuming a database connection is already established, this code will do what you are looking for.

$resource = mysql_query("SELECT points, submissionid FROM submission WHERE submissionid = '$submissionid'");
$result = mysql_fetch_assoc($resource);
echo $result["points"];

If you don't have a MySQL database connection established, check out mysql_connect .

Well, you'll want to get a resource from that query and then give it to mysql_fetch_assoc, like so:

$res = mysql_query($sqlStra);

// If you **Know for sure** you'll only have one row:
$row = mysql_fetch_assoc($res);
$points = $row['points'];

//Otherwise, you're going to need to loop.
$array_of_all_points = array();

while ($row = mysql_fetch_assoc($res)) {
    // $row['points'] now has what you want. You can assign it normally, or can use
    // extract($row) to turn it into $points, which I would advise against personally.
    $points = $row['points'];
    $array_of_all_points[$row['submissionid']] = $row['points'];
}

echo $points; // This will be the last $row['points'] that was executed.
echo $array_of_all_points['thatsubmissionid']; // Will output the points for the given session id. 

Also, that query isn't safe (if $submissionid comes from user input, it is vulnerable to SQL injection), you should use an ORM library as iloveitaly mentions. (I use Zend DB , though it's not technically ORM by itself)

Edit:

As the comments point out, this depends on if you're actually using Mysql. If you're not, you can use the PDO library to do your querying.

$sqlStra = "SELECT points FROM submission WHERE submissionid = ?"; 

$statement = $connection->prepare($sqlStra);
$statement->bind_param('i', $submissionid);
$statement->bind_result($points);
$statement->execute();
$statement->fetch(); // this will create / populate $points

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