PHP PDO using try - php

For best practices should I be putting the fetch command portion inside of the try statement or is the prepare and execute sufficient?
$sql = "SELECT * FROM links WHERE device = 'mobile' AND category = ? ORDER BY category asc, link_id asc";
try{
$sth = $dbh->prepare($sql);
$sth->bindValue(1, $cat, PDO::PARAM_STR);
$sth->execute();
}
catch(\PDOException $ex){
print($ex->getMessage());
}
if($sth->rowCount()) {
print("<a data-rel=\"dialog\" data-transition=\"pop\" href=\"index.php?action=addnew&cat=$cat\">Add New Menu Item</a><br/><br/>");
print("<ul data-role=\"listview\" data-filter=\"true\">");
while($row = $sth->fetch(PDO::FETCH_BOTH)) {
print("<li>");
print("<a data-transition='fade' href='$row[$COL_HREF]'>$row[$COL_LINK_NAME]<br/></a>");
print("</li>\n");
}
print("</ul>");
}

Inside the try with the rest of the code.
If the code in your try produces an Exception, you're printing out the exception message but are then continuing to check the rowCount(), which is dependent on $sth being successfully set and executed.

Related

get results of query using prepared statements mysqli

I would like to get the results of a query using prepared statements but I don't get anything.
The problem is I'm not able to fetch my results. Can some one show an example how to get results of query using prepared statements?
Here is my code:
$sql = "SELECT `username` FROM `usrs` WHERE `username` = ? ";
$statement = $this->conn->prepare($sql);
if (!statement)
{
throw new Exception($statement->error);
}
$statement->bind_param("s",$username);
$statement->execute();
$statement->bind_result($user);
while ($statement->fetch())
{
printf("%s", $user);
}
Looks pretty close. I added two lines. One line stores the result and the other is a check to make sure you had a response from the query. Run it and see if it helps.
$sql = "SELECT `username` FROM `usrs` WHERE `username` = ? ";
$statement = $this->conn->prepare($sql);
if (!statement)
{
throw new Exception($statement->error);
}
$statement->bind_param("s",$username);
$statement->execute();
$statement->store_result(); //<-- Added this.
if($statement->num_rows === 0) exit('No rows');//<--Test to see if you have a result.
$statement->bind_result($user);
while ($statement->fetch())
{
printf("%s", $user);
}

Delete function not working within a transaction pdo php mysql

I am having similar problems as this colleague: similar problem
I am surprised that a Delete function within a transaction with pdo does not behave properly. If I use the delete function alone in a pdo it works perfectly but when I combine the delete function with an update function in a transaction it stops working (only first query works). I have tried all the answer and tips from the old thread but nothing seems to work. Can someone help me here?
The code that I am working with:
function denyactionevent(){
try {
$$this->setAttribute(PDO::ATTR_AUTOCOMMIT, true);
$$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->conn->beginTransaction();
// product update query
$query = "UPDATE
" . $this->table_name . "
SET
accepted = :accepted
WHERE
id = :id";
// prepare query statement
$stmt = $this->conn->prepare($query);
// bind variable values
$stmt->bindParam(':accepted', $this->accepted);
$stmt->bindParam(':id', $this->id);
// execute the query
$stmt->execute();
$query2 = "DELETE
FROM event_case
WHERE reference = :id
";
// prepare query statement
$stmt = $this->conn->prepare($query2);
// bind values
$stmt->bindParam(':id', $this->id);
// execute the query
$stmt->execute();
$this->conn->commit();
return true;
} catch (Exception $e) {
$stmt->rollBack();
return false;
}
}

First run with PDO getting a Call to a member function bindParam() on a non-object error

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();

WHERE statement inside if condition in SQL

Can I do a WHERE clause inside an IF statement?
Like I want something like this:
$SQL = mysql_query("SELECT * FROM `table` ORDER BY `row` DESC");
$rows = mysql_fetch_array($SQL);
$email = $_SESSION['email_of_user'];
if($rows["row"] == "1" WHERE `row`='$email' : ?> (Pulls the logged in user's email)
Edit Server
<?php else : ?>
Add Server
<?php endif; ?>
Do I need (" where the WHERE statement is? Because I tried that and it didn't seem to work...
Or can I do it with an if condition inside of a where clause? Not sure of all these terms yet so correct me if I'm wrong...
You cannot mix up a query statement with PHP's statement. Instead write a query extracting desired results and check if there are any rows from that query.
I will show you an example:
$query = "SELECT * FROM `TABLE_NAME` WHERE `field` = '1' && `email`='$email'"; //Create similar query
$result = mysqli_query($query, $link); //Query the server
if(mysqli_num_rows($result)) { //Check if there are rows
$authenticated = true; //if there is, set a boolean variable to denote the authentication
}
//Then do what you want
if($authenticated) {
echo "Edit Server";
} else {
echo "Add Server";
}
Since Aaron has shown such a effort to encourage safe code in my example. Here is how you can do this securely. PDO Library provides options to bind params to the query statement in the safe way. So, here is how to do it.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); //Create the connection
//Create the Query Statemetn
$sth = $dbh->prepare('SELECT * FROM `TABLE_NAME` WHERE field = :field AND email = :email');
//Binds Parameters in the safe way
$sth -> bindParam(':field', 1, PDO::PARAM_INT);
$sth -> bindParam(':email', $email, PDO::PARAM_STRING);
//Then Execute the statement
$sth->execute();
$result = $sth->fetchAll(); //This returns the result set as an associative array

Why am I receiving a PDO query error?

Apologies in advance because I'm really unsure how to ask this question so if you need to know anything then please comment rather than downvote and I will edit.
I have teaser links on my main page which when clicked open up a window with the full article. I'm currently converting my MySQL code over to PDO and have gotten a little stuck.
In MySQL I used to be doing the following (Here, $foo_query is the query from the first page):
$id = $_GET['id'];
$sql = "SELECT id, postdate, title, body FROM FooBarTable WHERE id = $id";
if ($foo_query = mysql_query($sql)) {
$r = mysql_fetch_assoc($foo_query);
$title = $r["title"];
$body = $r["body"];
}
Which is simple to understand to me. I've been trying to convert this using what I know, and it turns out I don't know very much. So far I have the following:
$id = $_GET['id'];
$sql = $DBH->prepare("SELECT id, postdate, title, body FROM FooBarTable WHERE id = :id OR id = $id");
$sql->bindParam(':id', $_REQUEST['id'], PDO::PARAM_INT);
if ($foo_query = $DBH->query($sql)) {
$r->setFetchMode(PDO::FETCH_ASSOC);
$r = $foo_query->fetch();
$title = $r["title"];
$body = $r["body"];
}
$sql->execute();
This brings up an error of 'PDO::query() expects parameter 1 to be string'. This is for the 'if' line.
Have I even written any of that PDO correctly? What would I need to do from here? A friend has recently taught me MySQL, but he doesn't know PDO at all which means I can't ask his advice (not all that helpful...)
This is the correct way, with comments:
try {
//Connect to the database, store the connection as a PDO object into $db.
$db = new PDO("mysql:host=localhost;dbname=database", "user", "password");
//PDO will throw PDOExceptions on errors, this means you don't need to explicitely check for errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//PDO will not emulate prepared statements. This solves some edge cases, and relives work from the PDO object.
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//Prepare the statement.
$statement = $db->prepare("SELECT id, postdate, title, body FROM FooBarTable WHERE id = :id");
//Bind the Value, binding parameters should be used when the same query is run repeatedly with different parameters.
$statement->bindValue(":id", $_GET['id'], PDO::PARAM_INT);
//Execute the query
$statement->execute();
//Fetch all of the results.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
//$result now contains the entire resultset from the query.
}
//In the case an error occurs, a PDOException will be thrown. We catch it here.
catch (PDOException $e) {
echo "An error has occurred: " . $e->getMessage();
}
You need to use PDOStatement::execute instead of PDO::query:
$foo_query = $sql->execute();
You may also bind all your params at once when calling execute:
$foo_query = $sql->execute(array(
':id' => $id
));
You should change it to:
$sql->execute();
if($r = $sql->fetch()) {
$title = $r["title"];
$body = $r["body"];
Try this:
$sql = $DBH->prepare("SELECT id, postdate, title, body
FROM FooBarTable WHERE id = :id OR id = $id");
$sql->bindParam (':id', $_REQUEST['id'],PDO::PARAM_INT);
$sql->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$title = $row["title"];
$body = $row["body"];
}

Categories