mysql - PHP/PDO function return value from database varriabele parameters -
i trying write basic function value table.
<?php function getvalue($value, $from, $id){ //returns value of 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 value :from 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 fatal error:
uncaught exception 'pdoexception' message 'sqlstate[42000]: syntax error or access violation: 1064 have error in sql syntax; check manual corresponds mysql server version right syntax use near ''project' id = '1'' @ 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
although idea of having such function excellent, implementation terrible. essential drawbacks are:
- you connecting database every time function called
- this code prone sql injection
- yet awfully inflexible, letting run no query different silly
select ... id
. learn other queries , find function unusable.
it should function accepts sql query , array parameters bind:
<?php //returns value of query function getvalue($sql, $params = array()) { global $pdo; $stmt = $db->prepare($sql); $stmt->execute($params); return $stmt->fetchcolumn(); } require('includes/connect.php'); $name = getvalue("select name users id =?",array($_get['id']))
simple, robust , usable.
while connection string better moved includes/connect.php
$dsn = "mysql:host=localhost;dbname=$database;charset=utf8"; $opt = array( pdo::attr_errmode => pdo::errmode_exception, pdo::attr_default_fetch_mode => pdo::fetch_assoc ); $pdo = new pdo($dsn, $username, $password, $opt);
Comments
Post a Comment