So using prepared statements im trying to query with a '
i have a string called $awayteam wich holds : SSS'18 VR1
When i try to query the DB with above string it wont work....
$conn = new PDO($link, $pdo_username, $pdo_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM clublogo WHERE naam = :name");
//$stmt->bindParam(':name', $awayteam);
$stmt->bindParam(':name', $awayteam, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row){
$awayclublogo = sprintf($row[pad]);
}
$conn = null;
$awayclublogo will be NULL
However when i do it with just TEXT it does work.
$conn = new PDO($link, $pdo_username, $pdo_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM clublogo WHERE naam = :name");
$stmt->bindValue(':name', "SSS'18 VR1");
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row){
$awayclublogo = sprintf($row[pad]);
}
$conn = null;
OK So #Devon pointed out that the problem was due to HTML encoding.
Told me to look at the source, and sure he was right.
SSS'18 VR
im getting the variable from the DB like :
$conn = new PDO($link, $pdo_username, $pdo_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM vrip_uitslag WHERE GameID = :name");
$stmt->bindParam(':name', $gameid);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row) {
$hometeam = sprintf($row[Thuis]);
$awayteam = sprintf($row[Uit]);
}
var_dump($awayteam) will result : string(15) "SSS'18 VR1"
i then use $awayteam so i have no clue where the HTML encoding is happening....
I think it's been established that this is solved using prepared statements since you're using PHP. This would handle this automatically.
In SQL in general, you can escape it in a couple ways:
Use another apostrophe (single quote) before it:
'SSS''18 VR1'
Use the backslash before it:
'SSS\'18 VR1'
Double up on single quotes. Add an extra single quote to escape it.
SELECT * FROM clublogo WHERE name = 'SSS''18 VR1'
Use prepared statements if you are using PDO.
$dbh = new PDO("...");
$stmt = $dbh->prepare("SELECT * FROM clublogo WHERE name = :name");
$stmt->bindValue(':name', "SSS'18 VR1");
$stmt->execute();
$result = $stmt->fetchAll();
You have to use bindParam if you are using a variable.
$dbh = new PDO("...");
$stmt = $dbh->prepare("SELECT * FROM clublogo WHERE name = :name");
$stmt->bindParam(':name', $awayteam, PDO::PARAM_STR);
$awayteam = "SSS'18 VR1";
$stmt->execute();
$result = $stmt->fetchAll();
PDO: Prepared statements
Related
First, according to another SO post, I tried combining the two statements into one.
<?php
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
$sql = "UPDATE users SET pass = :password WHERE usrn = :id;
SELECT prim FROM users WHERE usrn = :id;";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->bindParam(":password", password_hash($_POST["password"], PASSWORD_DEFAULT));
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC); //// line 71
?>
However, this kept throwing the error: Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error on line 71.
I couldn't find any relevant solutions to this issue, so I decided to simply split up the two statements.
<?php
$sql = "UPDATE users SET pass = :password WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->bindParam(":password", password_hash($_POST["password"], PASSWORD_DEFAULT));
$stmt->execute();
$sql = "SELECT prim FROM users WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["session"] = $result["prim"];
?>
But a var_dump($result) is returning Bool(false), so obviously something is not working right with fetching the result and storing it as a variable, it seems, in both cases.
I'm new to PHP and MySQL, so I'm at a loss right now.
Change this,
$sql = "SELECT prim FROM users WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["session"] = $result["prim"];
To this,
$sql = "SELECT prim FROM users WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->execute(); // Your problem
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["session"] = $result["prim"];
You are missing the execution of the query.
I was wondering if it possible to use multiple query this way? that will make my work easy or any other way to do this? just moved on to mysqli prepared statement so no idea. thanks you
$mysqli = new mysqli('localhost', 'root', '', 'demo');
$stmt = $mysqli -> prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt = $stmt->get_result();
while ($row = $stmt->fetch_assoc()) {
//do something with row
}
$stmt->bind_param('i', $id2);
$stmt->execute();
$stmt = $stmt->get_result();
while ($row = $stmt->fetch_assoc()) {
//do something with row
}
$stmt = $stmt->get_result()
returns mysqli_result and it isn't prepared statement anymore, and as such you cannot do multiple queries.
You cannot use "multiple query" with prepared statements. However, you can execute the same query with different set of parameters - that's exactly what prepared statements are for. Judging by your code, you need the second option (so I corrected the question title). All you need is to supply another value for the already bound variable.
here you go:
$mysqli = new mysqli('localhost', 'root', '', 'demo');
$stmt = $mysqli -> prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
//do something with row
}
$id = $id2; // you need to use the same variable you bound
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
//do something with row
}
oh and yes, there was also a silly typo in your code, now fixed. You shouldn't overwrite the statement variable.
Ok, this is the problem:
This works:
$STH = $DBH->prepare("SELECT * FROM juegos WHERE id = 1");
$STH->execute();
This doesn't:
$STH = $DBH->prepare("SELECT * FROM juegos WHERE id = :id");
$STH->bindParam(':id', '1', PDO::PARAM_STR);
$STH->execute();
What in the world am I doing wrong? It doesn't even throw an exception
Thank you everyone!
Also, this is the whole code
<?php
try {
$DBH = new PDO("everything is", "ok", "here");
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $DBH->prepare("SELECT * FROM juegos WHERE id = :id");
$STH->bindParam(':id', '1', PDO::PARAM_STR);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
echo $row['nombre']."<br/>";
}
$DBH = null;
echo "Todo saliĆ³ bien";
} catch (PDOException $e) {
echo "Error";
}
?>
Using bindParam() the variable is bound as a reference.
A string can't be passed by reference.
The following things can be passed by reference:
Variables, i.e. foo($a)
New statements, i.e. foo(new foobar())
References returned from functions
Try using bindValue()
$STH->bindValue(':id', '1', PDO::PARAM_STR);
PHP bindParam() binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement.
The correct way to use bindParam is:
$id = 1;
$sth = $DBH->prepare("SELECT * FROM juegos WHERE id = :id");
$sth->bindParam(':id', $id, PDO::PARAM_INT);// use bindParam to bind the variable
// ^ PDO::PARAM_INT - the value of the variable $id should be an int
// ^ $id - the variable being represented by ':id',
// ^ :id - represents the variable
// $id - the variable being represented by ':id',
PHP bindValue() binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement.
$id=10;
$name=roadkill;
$sth = $dbh->prepare('SELECT *
FROM juegos
WHERE id < :id AND name = :name');
$sth->bindValue(':id', $id, PDO::PARAM_INT);// use bindValue to bind the variable's value
$sth->bindValue(':name', $name, PDO::PARAM_STR);// use bindValue to bind the variable's value
The key difference between these two methods is that unlike PDOStatement::bindValue(), with bindParam() the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.
The value for the :tabla parameter will be automatically quoted and escaped by PDO. The query executed would become:
SELECT * FROM 'juegos'
which is not valid SQL.
do not pass the value directly to BindParam.
try {
// $DBH = new PDO("everything is", "ok", "here");
$DBH = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $DBH->prepare("SELECT * FROM statstracker WHERE SrNo = :id");
$id = 1; // here you should keep it as variable and pass it to param
$STH->bindParam(':id', $id, PDO::PARAM_STR);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
echo $row['SrNo']."<br/>";
}
$DBH = null;
echo "Todo saliĆ³ bien";
} catch (PDOException $e) {
echo "Error";
}
For me replacing the double quote by single quote fixed the issue.
Previous:
$STH = $DBH->prepare("SELECT * FROM statstracker WHERE SrNo = :id");
Solution:
$STH = $DBH->prepare('SELECT * FROM statstracker WHERE SrNo = :id');
And it works, though not sure why.
Hope it helps!
I have two stored procedures in my database Postgres, both have the same name but the difference are the parameters.
procedure1(::string, ::integer, ::string, ::integer)
procedure1(::string, ::integer, ::integer)
In PDO doing bindParam correct, is coming STR, INT, INT but the prepere always performs procedure1.
How do I get him to understand what I call the procedure2?
Some information for more help? I clear? thanks
EDIT ===
...
$bounds = null; // forced for debug
if(!is_null($bounds)){
$query = "SELECT procedure1(:name, :domain, :geo, :userid)";
$stmt = $db->prepare($query);
$stmt->bindParam('name', $name, PDO::PARAM_STR);
$stmt->bindParam('domain', $idDomain, PDO::PARAM_INT);
$stmt->bindParam('geo', $geoString, PDO::PARAM_STR);
$stmt->bindParam('userid', $userId, PDO::PARAM_INT);
}else{
$query = "SELECT procedure1(:name, :domain, :userid)";
$stmt = $db->prepare($query);
$stmt->bindParam('name', $name, PDO::PARAM_STR);
$stmt->bindParam('domain', $idDomain, PDO::PARAM_INT);
$stmt->bindParam('userid', $userId, PDO::PARAM_INT);
}
$result = $stmt->execute();
...
The error it gives is that he is running a procedure that requires four parameters
Try changing your $query statements to explicitly tell PDO the types, and to avoid extra code switch to bindValue (PDO uses the PARAM flags to format SQL, not to cast data types):
$bounds = null; // forced for debug
if(!is_null($bounds)){
$query = "SELECT procedure1(:name::VARCHAR, :domain::INTEGER, :geo::VARCHAR, :userid::INTEGER)";
$stmt = $db->prepare($query);
$stmt->bindValue('name', $name);
$stmt->bindValue('domain', $idDomain);
$stmt->bindValue('geo', $geoString);
$stmt->bindValue('userid', $userId);
}else{
$query = "SELECT procedure1(:name::VARCHAR, :domain::INTEGER, :userid::INTEGER)";
$stmt = $db->prepare($query);
$stmt->bindValue('name', $name);
$stmt->bindValue('domain', $idDomain);
$stmt->bindValue('userid', $userId);
}
$result = $stmt->execute();
I've tried following the PHP.net instructions for doing SELECT queries but I am not sure the best way to go about doing this.
I would like to use a parameterized SELECT query, if possible, to return the ID in a table where the name field matches the parameter. This should return one ID because it will be unique.
I would then like to use that ID for an INSERT into another table, so I will need to determine if it was successful or not.
I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.
$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();
You can use the bindParam or bindValue methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
A litle bit complete answer is here with all ready for use:
$sql = "SELECT `username` FROM `users` WHERE `id` = :id";
$q = $dbh->prepare($sql);
$q->execute(array(':id' => "4"));
$done= $q->fetch();
echo $done[0];
Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();
I hope this help someone, Enjoy!
Method 1:USE PDO query method
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Getting Row Count
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Method 2: Statements With Parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Method 3:Bind parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Want to know more look at this link
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}