I have a seen a mysql code that looks like this
select * from customer
where name = :name;
In Mysql using colons in front of the value is not permitted, my assumption is the query is provided with a colon to bind it with PHP functions.
What I am looking for is which function is used to bind the queries with colons?
So far I have checked mysqli_stmt_bind_param but mechanism used to replace parameter with value is question mark and not colon.
You're correct with the binding, but there are two ways;
? - a simple placeholder, which you would bind with numerical indexes. For example;
$sql = "INSERT INTO `foo` (`bar`,`baz`) VALUES (?, ?)";
$smt = $pdo->prepare($sql);
$smt->bindParam(1, $bar);
$smt->bindParam(2, $baz);
// ...
:foo - a simple placeholder, which you would bind with a string index. For example;
$sql = "INSERT INTO `foo` (`bar`,`baz`) VALUES (:bar, :baz)";
$smt = $pdo->prepare($sql);
$smt->bindParam(':bar', $bar);
$smt->bindParam(':baz', $baz);
// ...
There are two database APIs available that involve binding;
PDO
MySQLi
You can see this article by "Use the Index, Luke" to see how binding is actually done.
Here is an example taken from php.net:
<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>
You should try searching on Google before asking here as this is simple function call.
For more details, please check: http://php.net/manual/en/pdostatement.bindparam.php
Related
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.
[ Status: Learner ]
I always use mysql, but this time i wanted to learn something new(prepared statements). I found this code in an other question, but I saw similar codes to this, and I found, that I can't imagine what is the "sss" in the 3rd row means.
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $val1, $val2, $val3);
$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';
/* Execute the statement */
$stmt->execute();
Here's another code with the same problem in the 2nd row: 'dd'
$stmt = $conn->prepare ( 'SELECT author, title FROM books where price < ? and weight > ?' );
$stmt->bind_param('dd',$price,$weight);
$price=15.; //RON
$weight=300.; //g
if (!$stmt->execute()) die ("Unsuccessfull query.");
$stmt->bind_result($author, $title);
echo "Big weight (>$weight g) and cheap books (< $price RON) <br>";
Could you explain it please for me please?
It's a specification character indicating what type of data type it can expect. In your case, it's 3 string variables.
Char Description
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
See the documentation
I am new to PDO objects and cannot find a single piece of documentation that will help me. Say I got a simple code to delete a row:
$count = $dbh->exec("DELETE FROM fruit WHERE colour = 'red'");
That will return affected rows, but how would I use prepared statements with that? Can use use $dbh->prepare AND $dbh->exec or query !?
It should be the same as any other statement:
$stmt = $dbh->prepare("DELETE FROM fruit WHERE colour = ?");
$stmt->execute(array('red'));
$count = $stmt->rowCount();
The PDO Statement rowCount() should be what you are looking to do.
EDIT
Fixed by adding the ->rowCount() which will return the row count. ->execute in a statement will return a bool, true or false whether the query errored out or not. Of course all of this information is readily available at the PDO Statement Manual
$dbh->prepare returns a PDOStatement object. You then call $stmt->execute to get the result.
More info in the PDO manual
Here's an example from the manual:
<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$stmt = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$stmt->execute(array($calories, $colour));
?>
I´m trying to do the following query in PHP
$sqlstr = mysql_query("SELECT * FROM sales where passport = $row['passport']");
if (mysql_numrows($sqlstr) != 0) {
while ($row = mysql_fetch_array($sqlstr)) {
echo $row['firstname'];
}}
How can I incorporate the value of $row['passport'] into my query?
First of all you forgot the single-quotes. sAc corrected this already in his answer. But I would consider to also use an escaping function due to security-issues:
$sqlstr = mysql_query("
SELECT
*
FROM
sales
WHERE
passport = '" . mysql_real_escape_string($row['passport']) . "'");
You are missing quotes:
$sqlstr = mysql_query("SELECT * FROM sales where passport = '{$row['passport']}'");
I would avoid manually escaping/sanitizing your variables and just use prepared statements. This was something I didn't learn until much later in my web development career, and I wish I'd known about it sooner. It will save you a lot of trouble and is just safer all around.
You can use the mysqli_stmt class to perform MySQL queries using prepared statements, or you could use the PHP Data Objects (PDO) extension, which works with MySQL, PostgreSQL and other RDBMSes.
Just to show you what it looks like, here's the first example from the PDOStatement->bindParam doc page:
<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>
I've gotten a little confused with the PDO::prepare functions.
I have something like this
array('user_email'=>'hello#net.com','user_pass'=>'password')
and i'd like to translate it into something like this
INSERT INTO user_info (user_email, user_pass) VALUES (hello#net.com, password)
using parameterized queries with PDO (or mysqli, I'm open to suggestions).
Another idea -
array('uid'=>'10', 'first_name'=>'robert', 'last_name'=>'jones')
array("email", "number")
into
SELECT email, number FROM t1 WHERE uid=10 AND first_name=robert AND last_name=jones
I know the answer lies somewhere with PDO::prepare and call_user_func_array, but I've gotten really confused on how the latter function works, and would appreciate an explanation.
I'm confused, and maybe you are too. Here is a simple example:
$sth = $dbh->prepare('SELECT * FROM table WHERE id = ? AND date = ?');
$sth->execute(array(150, '2009-04-04'));
$data = $sth->fetchAll();
Or:
$sth = $dbh->prepare("INSERT table VALUES(:foo, :bar)");
$sth->bindParam(":foo", $foo);
$sth->bindParam(":bar", $bar);
Or:
$sth = $dbh->prepare("INSERT INTO user_info (user_email, user_pass) VALUES (:email, :pass)");
$sth->execute(array(':email' => 'foo#example.org', ':pass' => '1234'));
Hope this helps!
PDOStatement::execute() works with parameters markers, so you have to construct query before calling PDO::prepare().
You don't have to use call_user_func_array(). PDOStatement::execute() takes associative arrays by default.
$stmt = $pdo->prepare("SELECT fld FROM tbl WHERE fld=:parameter1 AND fld2=:parameter2");
$stmt->execute(array(":parameter1" => "value1", ":parameter2" => "value2"));
...
http://se.php.net/manual/en/pdo.prepare.php