I have a database with the following columns: id, name, zone.
I need the function to return the name of the record that contains the zone that arrives as a parameter
static public function mdlShowName($table, $zone){
$stmt = Conection::conect()->prepare("SELECT name FROM $table WHERE zone = :$zone");
$stmt -> bindParam(":name", name, PDO::PARAM_STR);
$stmt -> execute();
return $stmt -> fetch();
$stmt-> close();
$stmt = null;
}
The parameter placeholder is not a variable. Don't use $zone, just give it a label.
$stmt = Conection::conect()->prepare("SELECT name FROM $table WHERE zone = :zone");
The name by which you bind the parameter must be the same as the label you used as a placeholder in the query. Then bind it to the PHP variable that has the value.
Don't bother with PDO::PARAM_STR or other param types. The MySQL PDO driver ignores these anyway. They might be more important if you use some other brand of RDBMS (Oracle, Microsoft, etc.).
You don't need the : in the parameter name here.
$stmt -> bindParam("zone", $zone);
An alternative is to just pass an array to execute(). If you do this, then skip the bindParam() calls.
$stmt -> execute( ["zone" => $zone] );
Tip: This is all explained in the documentation!
Related
I am confused with the way lastInsertId() function is written. Say for example I have the following queries with lastInsertId() function.
$myinsert = $pdo->prepare("INSERT INTO some_table(something)VALUE(:something");
$myinsert -> bindValue(':something', $something);
$myinsert -> execute();
$insert = $pdo->prepare("INSERT INTO table(something)VALUE(:something");
$insert-> bindValue(':something', $something);
$insert-> execute();
$lastId = $pdo->lastInsertId();
$stmt = $pdo->prepare("INSERT INTO another_table(something)VALUE(:something");
$stmt -> bindValue(':something', $something);
$stmt -> execute();
Now the confusion is that as everyone knows and can see here that in the satement $lastId = $pdo->lastInsertId(); there is no where mentioned whether to fetch the last inserted ID from $myinsert query or $insert query or from $stmt query. So how does it know where to fetch the ID from? Since, lastInsertId() function is placed above the $stmt query, it definitely will not fetch last inserted id from $stmt query as when the $lastid was declared $stmt query was not yet executed. But how does it know it has to fetch from $insert query and not from $myinsert query as in whole statement $lastId = $pdo->lastInsertId(); there is nothing defined like to fetch from so and so particular query? Please help me understand the way it works.
It will just give you the insert ID from the last insert prior to making the call which generates an auto-increment value. It could be that each insert will generate one, but it will only be the last one executed prior to this call.
I am preparing mysql configuration settings using class. I am confused about it. I always use bindParam. It also possible to insert using array. I mean, what are the differences between array and bindparam.
eg array
$query = $db->prepare("INSERT INTO users SET
username = :uname,
password = :upass,
email = :umail");
$insert = $query->execute(array(
"upass" => "123456",
"umail" => "user#user.com",
"uname" => "username",
));
if ( $insert ){
$last_id = $db->lastInsertId();
}
eg
$stmt = $this -> db_conn -> prepare("INSERT into users(username, password) VALUES(:uname, :upass)");
$stmt -> bindParam(':uname', $username);
$stmt -> bindParam(':upass', $password);
$stmt -> execute();
Desconsidering the fact that with execute you can't choose the data type (it's always PDO::PARAM_STR) There's only a main difference between both (which is from core). PDOStatement::bindParam is by reference while PDOStatement::execute isn't. PDOStatement::execute do internnaly the same thing as PDOStatement::bindValue, but twice.
Internally (in C), bindValue calls the same method which execute calls. The method name which is called is really_register_bound_param.
On the other hand, bindParam calls other method called register_bound_param.
It means that bindValue calls the same method called by execute more than one time while bindParam calls a method to bind as a reference and only "really register" the param when execute is called.
Thinking about bind by reference, it's only possible using bindParam:
//fictional code
$stmt= $pdo->prepare("INSERT INTO table (column) VALUES (:value)");
$stmt->bindParam(":value", $randomValue);
for($i = 0 ; $i < 1000; $i))
{ $randomValue = rand(1000,1000000);
$stmt->execute();
}
Is it worthy? Perhaps while a while with a complex insert with multiples parameters could reduce the overhead with rebinding a new parameter or a big amount of them.
I know of two ways to use PDO in PHP to update a MySQL database record. Please could someone explain which one I should use for better security and the difference and I am a little confused.
Method One:
$user = "root";
$pass = "";
$dbh = new PDO('mysql:host=somehost;dbname=somedb', $user, $pass);
$sql = "UPDATE coupons SET
coupon_code = :coupon_code,
valid_from = :valid_from,
valid_to = :valid_to,
discount_percentage = :discount_percentage,
discount_amount = :discount_amount,
calculationType = :calculationType,
limit = :limit
WHERE coupon_code = :coupon";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':coupon_code', $_POST['coupon_code'], PDO::PARAM_STR);
$stmt->bindParam(':valid_from', $_POST['$valid_from'], PDO::PARAM_STR);
$stmt->bindParam(':valid_to', $_POST['valid_to'], PDO::PARAM_STR);
$stmt->bindParam(':discount_percentage', $_POST['discount_percentage'], PDO::PARAM_STR);
$stmt->bindParam(':discount_amount', $_POST['discount_amount'], PDO::PARAM_STR);
$stmt->bindParam(':calculationType', $_POST['calculationType'], PDO::PARAM_STR);
$stmt->bindParam(':limit', $_POST['limit'], PDO::PARAM_STR);
$stmt->bindParam(':coupon', $_POST['coupon_code'], PDO::PARAM_STR);
$stmt->execute();
Method Two:
$dbtype="somedbtype";
$dbhost="somehost";
$dbname="somedb";
$dbuser="someuser";
$dbpass= "somepass";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$title = 'PHP Pattern';
$author = 'Imanda';
$id = 3;
$sql = "UPDATE books
SET title=?, author=?
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($title,$author,$id));
From what I can see, method two does not bind the data, rather insert it directly into the query as an array type. Does this make the script more susceptible to SQL injection or other security risks?
The only difference between the two is that if you pass the array in to the execute function rather than calling bindParam yourself, it treats all parameters as PDO::PARAM_STR automatically, whereas in calling bindParam yourself you could bind them as integers, etc.
From the docs:
input_parameters
An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as PDO::PARAM_STR.
You can also see from the examples there that you can use named parameters (e.g. :limit) when passing the array into the execute function. You don't have to just put ?. In that case you give the array a key:
$sth->execute(array(':calories' => $calories, ':colour' => $colour));
It's mostly a matter of preference. Both protect you from injection.
Though I think it's much easier to force data type with bind(), where as using execute(array()) will be using strings.
My script containing that error is this:
$stmt = $this->db->prepare('SELECT libelle,activite,adresse,tel,lat,lng FROM etablissements where type IN ('.$in_list.')');
$stmt->execute();
$stmt->bind_result($libelle,$activite,$adresse,$tel,$lat,$lng);
The php version running on the server (not localhost) is 5.2.17
$stmt is supposed to be an object with the method execute().
Seems like $this->db->prepare() is not returning the good result.
If $this->db is a mysqli() object you should bind the parameters like that:
if ($stmt = $this->db->prepare('SELECT libelle,activite,adresse,tel,lat,lng FROM etablissements where type IN (?)')) {
$stmt->bind_param("s", $in_list);
$stmt->execute();
// ...
}
Check the sql you executed,
$this->db->prepare('SELECT libelle,activite,adresse,tel,lat,lng FROM etablissements where type IN ('.$in_list.')');
does not return a valid statement object.
Swap the statement bind and execute and replace result with param, It will work fine
$stmt = $this->db->prepare('SELECT libelle,activite,adresse,tel,lat,lng FROM etablissements
where type IN ('.$in_list.')');
$stmt->bind_param($libelle,$activite,$adresse,$tel,$lat,$lng);
$stmt->execute();
Your db object is null. Check if you close the connection too early or somehow you override it to null.
I have a variable called $description that has a paragraph of information in it. Some of these descriptions are a sentence or 2, some are long, so im using blobs to save this instead of var char. This statement executes without a problem, but nothing actually gets saved. No errors reported.
$query = "UPDATE event SET description=? WHERE id=? LIMIT 1";
if($stmt = $db -> prepare($query))
{
$null = NULL;
$stmt -> bind_param("bi", $null, $id);
$stmt -> send_long_data(0, $description);
$stmt -> execute();
}
Is there something im missing?
Instead of binding b as blob, try to refer to s as string