MYSQL Error Get Prepared Statement - php

How do I get the prepared statement of the mysqli_stmt-object?
If there is an error while executing the mysql-statement I want to return the statement.
$id = "89c483c8";
$query = "SELECT * FROM database WHERE id = ?";
if (!($stmt = $database->prepare($query) { ... }
else {
$stmt->bind_param("s", $id);
if (!$stmt->execute())
return $stmt->get_statement; //doesn't exist
}
"$stmt->get_statement" of course doesn't work. So how do I get the full query? In this example:
"SELECT * FROM database WHERE id = 89c483c8"

This is the best way to catch sql errors :
try {
$res = $mysqli_instance->query($query);
}catch (mysqli_sql_exception $e) {
print "Error Code <br>".$e->getCode();
print "Error Message <br>".$e->getMessage();
print "Strack Trace <br>".nl2br($e->getTraceAsString());
}
Or the simplest way :
echo $stmt->error
http://php.net/manual/en/mysqli.error.php

Related

Check PDO query for result and then reuse the data

I am new to PDO, and am in the process of upgrading an application from mysql_query to PDO. This is surely a stupid question - but I hope someone can help me wrap my head around it.
I need to see if a PDO query has any data:
- if it doesn't, throw an error
- if it does, retrieve that data
I could do this easily with mysql_num_rows, but that's deprecated as we all know.
The issue is that once I've checked if there is any data, I can no longer retrieve it.
The check runs fine, but then when trying to retrieve the actual result, it's empty. I can of course execute the query again after the check - but I'd rather avoid having to run a query twice.
try
{
$result = $pdo2->prepare("SELECT first_name FROM users WHERE email = :email;");
$result->bindValue(':email', $email);
$result->execute();
$data = $result->fetchAll();
}
catch (PDOException $e)
{
$error = 'Error fetching user: ' . $e->getMessage();
echo $error;
exit();
}
if (!$data) {
echo "No data!";
} else {
echo "Data found!";
}
$row = $result->fetch();
echo "First name: " . $row['first_name'];
How can I solve this?
I tried to assign $result to another variable ($test = $result), and then run the data check on the $test variable instead - but even so, the $result variable STILL doesn't return any data after running the check (see the commented lines):
try
{
$result = $pdo2->prepare("SELECT first_name FROM users WHERE email = :email;");
$result->bindValue(':email', $email);
$result->execute();
$test = $result; // Duplicating the variable
$data = $test->fetchAll(); // Running the check on the duplicated variable
}
catch (PDOException $e)
{
$error = 'Error fetching user: ' . $e->getMessage();
echo $error;
exit();
}
if (!$data) {
echo "No data!";
} else {
echo "Data found!";
}
$row = $result->fetch(); // Still doesn't return the result!
echo "First name: " . $row['first_name'];
This is really doing my head in... I think there's a simple solution somewhere, I just can't see it. Please help!
$result->fetch() only fetches rows that haven't already been fetched. Since you fetched everything with $result->fetchAll(), there's nothing left.
If you want the first row, you can use:
$row = data[0];
If you want to process all the rows, use:
foreach ($data as $row)
Instead of fetching everything, you can use the rowCount() method.
if (!$result->rowCount()) {
echo "No data";
} else {
echo "Data found!";
}
There are caveats regarding the use of rowCount() with SELECT queries in PDO, but I think it generally works with MySQL.
As you are using a try/catch block you can raise your own exceptions as well as catch those thrown by PDO - so you could do something like this:
try{
$sql='SELECT first_name FROM users WHERE email = :email;';
$stmt = $pdo2->prepare( $sql );
if( !$stmt )throw new Exception('Failed to prepare sql statement');
$result=$stmt->execute( array( ':email' => $email ) );
if( !$result )throw new Exception('Failed to get any results');
$rows = $stmt->rowCount();
if( $rows == 0 )throw new Exception('Empty recordset');
while( $rs=$stmt->fetch( PDO::FETCH_OBJ ) ){
echo $rs->firstname;
}
}catch ( PDOException $e ){
exit( 'Error fetching user: ' . $e->getMessage() );
}
You can always fetch individual rows and for the first row, check if the data is returned and process if not. Then enter a do...while() loop which processes the data and then reads the next row at the end of the loop...
try
{
$result = $pdo2->prepare("SELECT first_name FROM users WHERE email = :email;");
$result->bindValue(':email', $email);
$result->execute();
$row = $result->fetch(); // Fetch first row of data
if (!$row) {
echo "No data!";
} else {
echo "Data found!";
do {
echo "First name: " . $row['first_name'];
}
while ($row = $result->fetch());
}
}
catch (PDOException $e)
{
$error = 'Error fetching user: ' . $e->getMessage();
echo $error;
exit();
}

How to execute multiple queries using PDO for Sql Server

I'd like to execute some queries that doesn't return result set, and then execute a real query, and fetch its result.
Here is an exemple that doesn't work :
<?php
try {
$db = new PDO('dblib:host=myhost;dbname=master','user','password');
$query = "declare #entier int = 1;";
$db->exec($query);
$query = "select #entier;";
$stmt = $db->query($query);
$rows = $stmt->fetchAll();
print_r($rows);
}
catch (PDOException $e) {
print ($e->getMessage());
}
catch (Exception $e) {
print ($e->getMessage());
}
?>
This code neither doesn't work :
try {
$db = new PDO('dblib:host=myhost;dbname=master','user','password');
$query = "declare #entier int = 1; select #entier;";
$stmt = $db->query($query);
$rows = $stmt->fetchAll();
print_r($rows);
}
catch (PDOException $e) {
print ($e->getMessage());
}
catch (Exception $e) {
print ($e->getMessage());
}
?>
But this code works :
<?php
try {
$db = new PDO('dblib:host=myhost;dbname=master','user','password');
$query = "select 1;";
$stmt = $db->query($query);
$rows = $stmt->fetchAll();
print_r($rows);
}
catch (PDOException $e) {
print ($e->getMessage());
}
catch (Exception $e) {
print ($e->getMessage());
}
?>
Thanks for your help
I know this is old, but for other people finding this from Google: you need to use PDOStatement::nextRowset to iterate over the result sets from your multiple queries.
However, it seems there are memory issues when using nextRowset with dblib in some versions (it tried to allocate 94Tb in my case...), so I ended up re-engineering to avoid multiple SQL queries altogether (instead duplicating the value of the DECLARE where it was being used).
PDO::query docs (http://php.net/manual/it/pdo.query.php) say
PDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.
This could mean that you can execute with query() both queries with and without result

Can't get array from PDO query

i'm trying to get an array from a SQL query using pdo, what i send to the method it's for example $connection->selectFrom('Person',array(1,2));
when i try to get the results it returns an empty array, here is my code:
public function selectFrom($table,$indexes){
try{
$pdo=$this->getPdo();
// HERE I GET ALL THE COLUMN NAMES FROM THE TABLE I RECEIVE
$columns = $this->getColumnNames($table);
$finals = array();
// IN THIS CICLE I GET THE COLUMNS THAT MATCH THE INDEXES I RECEIVE
for($i=0;$i<count($indexes);$i++){
$finals[$i] = $columns[$indexes[$i]];
}
// FROM HERE I GET THE QUERY STATEMENT WICH IS SELECT column1,column2 from $table
$query = $this->getSelectSQL($table, $finals);
// ALL OF THE ABOVE WORKS BUT HERE IT STOPS WORKING
$results = $pdo->query($query);
return $results;
}catch(PDOException $ex){
echo "EXCEPTION ".$ex;
}
}
Thanks to #Cymbals for your answer, the final code ended up like this:
public function selectFrom($table,$indexes){
try{
$pdo=$this->getPdo();
$columns = $this->getColumnNames($table);
$finals = array();
for($i=0;$i<count($indexes);$i++){
$finals[$i] = $columns[$indexes[$i]];
}
$query = $this->getSelectSQL($table, $finals);
$query.= " WHERE Available = 1";
$stmt = $pdo->prepare($query);
$stmt->execute();
$results = $stmt ->fetchAll();
return $results;
}catch(PDOException $ex){
echo "EXCEPTION ".$ex;
}
}
Try this after getting the query, prepare and execute it
$stmt = $pdo->prepare($query);
var_dump($stmt);// if the prepare fails or sql query is messed up it will give false
$results = $stmt->execute();
return $results;

How can I use prepared statements combined with Transactions with PHP?

My goal is to use a transaction and a prepared statement simultaneously, to achieve both integrity of data, and prevention of SQL injection.
I have this:
try {
$cnx = new PDO($dsn,$dbuser,$dbpass);
$cnx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cnx->beginTransaction();
$cnx->query("SELECT * FROM users WHERE username=$escaped_input");
$cnx->query("SELECT * FROM othertable WHERE some_column=$escaped_input_2");
$cnx->commit();
}
catch (Exception $e){
$cxn->rollback();
echo "an error has occured";
}
I would like to incorporate the query as one would with a prepared statement:
$stmt=$cxn->prepare("SELECT * FROM users WHERE username=?");
$stmt->execute(array($user_input));
$stmt_2=$cxn->prepare("SELECT * FROM othertable WHERE some_column=?");
$stmt_2->execute(array($user_input_2));
How can I achieve that?
Edit
I get this error:
PHP Parse error: syntax error, unexpected T_CATCH
Here is my updated code:
try
{
$cnx = new PDO($dsn,$dbuser,$dbpass);
$cnx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cnx->beginTransaction();
$stmt=$cnx->prepare("SELECT * FROM users WHERE username=?");
$stmt->execute(array($username));
$cnx->commit();
while ($row=$stmt->fetch(PDO::FETCH_OBJ)){
echo $stmt->userid;
}
catch(Exception $e) {
if (isset($cnx))
$cnx->rollback();
echo "Error: " . $e;
}
Just call "execute" after you call "beginTransaction".
Where you call "prepare" doesn't really matter.
Here's a complete example:
http://php.net/manual/en/pdo.begintransaction.php
EXAMPLE:
try {
$cnx = new PDO($dsn,$dbuser,$dbpass);
$cnx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cnx->beginTransaction();
$stmt=$cxn->prepare("SELECT * FROM users WHERE username=?");
$stmt->execute(array($user_input));
$stmt_2=$cxn->prepare("SELECT * FROM othertable WHERE some_column=?");
$stmt_2->execute(array($user_input_2));
$cnx->commit();
}
catch (Exception $e){
$cxn->rollback();
echo "an error has occurred";
}
PS:
1) I'm assuming, of course, that $user_input and $user_input_2 are available immediately. You don't want your transaction hanging open unnecessarily long ;)
2) Based on your comment reply above, I think you might be confusing "execute" and "begin tran/commit". Please look at my link.
3) Do you even need a transaction? You're just doing two "select's".
4) Finally, why not do one "join" (or union, if compatible) instead of two "select's"?
try
{
$cnx = new PDO ($dsn,$dbuser,$dbpass);
$cnx->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cnx->beginTransaction ();
$stmt = $cnx->prepare ("SELECT * FROM users WHERE username=?");
$stmt->execute(array($username));
$cnx->commit();
while ($row = $stmt->fetch (PDO::FETCH_OBJ)){
echo $row->userid;
}
}
catch (Exception $e) {
if (isset ($cnx))
$cnx->rollback ();
echo "Error: " . $e;
}
}
Did you mean this?
try {
$cnx = new PDO($dsn,$dbuser,$dbpass);
$cnx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cnx->beginTransaction();
$stmt=$cnx->prepare("
SELECT * FROM users, othertable
WHERE users.username=?
AND othertable.some_column=?");
$stmt->execute(array($user_input,$user_input_2));
$cnx->commit();
}
catch (Exception $e){
$cnx->rollback();
echo "an error has occured";
}
That is assuming that the two tables data does not have duplicate field names, otherwise you're going to have to use:
SELECT users.field1 as u_field1, othertable.field1 as o_field1 FROM users, othertable
WHERE users.username=?
AND othertable.some_column=?

I want to get the exact message out of this error

I understand I have to include mysql_errno y mysql_error here somewhere instead of 'Query Failed' and I tried with $results as an argument but i have not found out how.
If someone can help me out, thanks:
static function execSQl2($query)
{
/*
Execute a SQL query on the database
passing the tablename and the sql query.
Returns the LAST_INSERT_ID
*/
$db = null;
$lastid = null;
//echo "query is $query";
try
{
$db = Model::getConnection();
$results = $db->query($query);
if(!$results) {
throw new Exception('Query failed', EX_QUERY_FAILED);
}
$lastid = $db->insert_id;
}
catch(Exception $e)
{
/* errors are handled higher in the
object hierarchy
*/
throw $e;
}
Model::closeConnection($db);
return $lastid;
}
throw new Exception(mysql_error(), EX_QUERY_FAILED);

Categories