简体   繁体   中英

mysql_result to PDO

Below is the code, I have, it is written in mysql. My goal is to convert this to PDO.

$query = "SELECT name, age FROM table WHERE condition=$condtion";
$mysql_query = mysql_query($query);

echo $name = mysql_result($mysql_query, 0, 'name');
echo $age = mysql_result($mysql_query, 0, 'age');

I have tried doing the following code below, but it is giving me an empty result.

$query = $PDO -> prepare("SELECT name, age FROM table");
$query -> execute();

echo $name = $query->fetch(PDO::FETCH_ASSOC)['name'];
echo $age = $query->fetch(PDO::FETCH_ASSOC)['age'];

Try:

$query = $PDO->prepare("SELECT name, age FROM table WHERE condition = :param");
$query->bindParam(':param', $param); // define this somewhere
$query->execute();
$result = $query->fetch();

echo $name = $result['name'];
echo $age = $result['age'];

From PHP.net, fetch works as follows: Fetches a row from a result set associated with a PDOStatement object. The fetch_style parameter determines how PDO returns the row.

When you execute a prepared statement, you need to perform a fetch or a fetchAll to pull the data. fetch gets you the first row, and in your case with a condition = X, I am guessing you only want one row.

Updated with links for reference:

execute: http://php.net/manual/en/pdostatement.execute.php

fetch: http://php.net/manual/en/pdostatement.fetch.php

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