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!
Related
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
This is my first run with PDO, not sure how much better it is than using mysqli but its part of a project I have to create.
Here is the code that is causing the message, all I am trying to do is update pieces of data within my db table.
<?php
//PHP Data Objects
try{
//Connect
$dbh = new PDO('mysql:host=localhost; dbname = company; charset=utf-8','root', 'bachi619');
} catch(PDOException $e){
echo $e->getMessage();
}
$id = 4;
$name = "logan";
$department = "Design";
$sth = $dbh->query("UPDATE employees SET department=:department,last_name=:lastname WHERE id=:id");
//bind
$sth->bindParam(':id',$id);
$sth->bindParam(':lastname',$name);
$sth->bindParam(':department',$department);
$sth->execute();
?>
you have to use
$dbh -> prepare("UPDATE employees SET department=:department,last_name=:lastname WHERE id=:id");
Use prepare for PDO, check this http://in3.php.net/manual/en/pdostatement.bindparam.php
$sth = $dbh->prepare('UPDATE employees SET department=:department,last_name=:lastname WHERE id=:id' );
The dsn should be non spaced
$dbh = new PDO('mysql:host=localhost;dbname=company','root', 'bachi619');
You need to prepare the SQL statement like this
$sth = $dbh->prepare( 'UPDATE employees SET department=:department,last_name=:lastname WHERE id=:id' );
Then bind the parameters
$sth->bindParam(':id',$id);
$sth->bindParam(':lastname',$name);
$sth->bindParam(':department',$department);
and finally execute the query
$sth->execute();
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();
The current error when running this from the command line is "Call to a member function bindParam() on a non-object" which I've worked out to being a problem with the variable $orderPO. Something does not like non-numeric characters which led me to the bindParam PARAM_STR business which does not work either. The database fields are both varchar 50.
My search skills are failing me. I know this must be posted somewhere about a million times but I can't seem to find it. I am completely open to doing this another way if someone has a better idea.
Current attempt code:
try
{
$orderNum = '123456';
$orderPO = '123456-A';
$dbh = new PDO("mysql:host=localhost;dbname=dbname", 'someuser', 'somepass');
$stm = $dbh->prepare("insert into some_table (order_number, order_po)");
$stm->bindParam(':order_number', $orderNum, PDO::PARAM_STR);
$stm->bindParam(':order_po', $orderPO, PDO::PARAM_STR);
$stm->execute();
print_r($stm);
print_r($dbh);
$arr = $stm->errorInfo();
print_r($arr);
$stm->closeCursor();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
In order to bind parameters using PDO, you will need to use placeholders, like this:
$stm = $dbh->prepare("
INSERT INTO `some_table` SET
`order_number` = :order_number,
`order_po` = :order_po
");
$stm->bindParam(':order_number', $orderNum, PDO::PARAM_STR);
$stm->bindParam(':order_po', $orderPO, PDO::PARAM_STR);
Notice the inclusion of the : character before the named placeholder. I also added column names to your query.
Read further and see examples: PDO bindParam
The correct syntax is
$stm = $dbh->prepare("insert into some_table (order_number, order_po) VALUES (?, ?)");
$stm->bindParam(1,$orderNum);
$stm->bindParam(2,$orderPO);
include the questions marks, the numbers in the bindParam call refer to which question mark you're binding the parameter to
You are trying to use bindparam, but bind param matches ? not cursors :. You have not included any parameters or values.
Also, you are missing your VALUES statement within the query, which is causing the query to fail. This is why you get the "Call to a member function bindParam() on a non-object"
To use the :value syntax, use bindValue, not bindParam. to use bindParam, switch the :value to ? in your query and number them in order is your execute array.
try
{
$orderNum = '123456';
$orderPO = '123456-A';
$dbh = new PDO("mysql:host=localhost;dbname=dbname", 'someuser', 'somepass');
$stm = $dbh->prepare("insert into some_table (order_number, order_po) VALUES (:order_number, :order_po)");
$stm->bindvalue(':order_number', $orderNum, PDO::PARAM_STR);
$stm->bindvalue(':order_po', $orderPO, PDO::PARAM_STR);
$stm->execute();
print_r($stm);
print_r($dbh);
$arr = $stm->errorInfo();
print_r($arr);
$stm->closeCursor();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
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 />";
}