Friday, 8 December 2017

mysql - PHP/PDO function return value from database varriabele parameters

style="font-weight: bold;">

Answer



I am trying to write this basic function to get a value
from a table.



            

function getvalue($value, $from, $id){
//Returns the
value of a table

require('includes/connect.php');
$db =
new PDO('mysql:host=localhost;dbname='.$database, $username, $password);

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


$sql = "SELECT :value AS value
FROM :from
WHERE id =
:id

LIMIT 1";

$stmt = $db->prepare($sql);

$stmt->bindParam(':value', $value, PDO::PARAM_STR);

$stmt->bindParam(':from', $from, PDO::PARAM_STR);

$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

$data = $stmt->fetch();
$return =
$data['value'];


return $return;

}//function
?>


It
gives this Fatal error:





Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error
or access violation: 1064 You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near ''project'
WHERE id = '1'' at line 2' in /functions/getvalue.php:26 Stack trace: #0
/functions/getvalue.php(26): PDOStatement->execute() #1 /
test.php(24):
getvalue('tarief', 'project', '1') #2 {main} thrown in /functions/getvalue.php on line
26


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...