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);
Related
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
Hei,
I need a function in php that checks if a value entered by form is already in database (sql - server -- PDO), and return TRUE or FALSE.
I tried to do this, but I got stuck and didn't found a solution on internet.
could you give me a hint on how to threat the above condition ?
function check_code($code) {
GLOBAL $handler;
$code = check_input($code);
try{
$query2 = $handler -> prepare("SELECT code from stock where code = :code");
$query2 -> execute(array(
':code' => $code
));
return >???<
}
catch(PDOException $e){
echo $e -> getMessage();
} }
return something like row_count(result) > 0
I've never work with sql-server before but I had worked with PDO many times, basically this is how would check in pdo
<?php
function check_code($code)
{
GLOBAL $handler;
$code = check_input($code);
try {
$query2 = $handler->prepare("SELECT code from stock where code = :code");
$query2->execute(array(':code' => $code));
$results = $query2->fetchColumn();
if (count($results) > 0) {
echo "exists";
} else {
echo "does not exist";
}
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
?>
NB: Avoid using the Global var... Stop using `global` in PHP
I am trying to retrieve data from the database. I'm using PDO and the execute statement seems to be giving problems that I can't figure out.
public function doesAdminEmailExist($email){
$this->m_dbHandler->queryDB("SELECT id FROM Admin WHERE email = ? ", array($email));
$ret = $this->m_dbHandler->fetchOne();
if(!empty($ret)) return $ret["id"];
else return -1;
}
The queryDB function in another class is given below:
public function queryDB($query, $params=array()){
try {
$stmt = $this->m_dbConn->prepare($query);
if($stmt === false){
$arr = $this->m_dbConn->errorInfo();
throw new Exception("Could not prepare query: ". $arr[2]." // query: ".$query);
}
else {
$bool_status = $stmt->execute($params);
if($bool_status){ // Query was successful
$this->result = $stmt;
}
else { // Query was not successful
$arr = $stmt->errorInfo();
throw new Exception("Could not execute query: ". $arr[2]." // query: ".$query);
}
}
}
catch (Exception $e) {
//throw $e;
$arr = $this->m_dbConn->errorInfo();
throw new Exception("An error occurred: ". $arr[2]." // query: ".$query);
}
}
When I run in my browser, I get the following error
<server_response>
<return_status>true</return_status>
<return_message>error Occured. Rethrowing <br>An error occurred: // query: SELECT id FROM Admin WHERE email = ? </return_message>
</server_response>
I am very new to php and this is my first attempt at using mysqli. I can't seem to figure out why I am getting this error? I have reviewed similar questions on it but I still don't understand what the problem is.
Here is my code:
<?php
require_once('abstractDAO.php');
class customerDAO extends abstractDAO {
function __construct() {
try{
parent::__construct();
} catch(mysqli_sql_exception $e){
throw $e;
}
}
public function getCustomers(){
//The query method returns a mysqli_result object
$result = $this->mysqli->query('SELECT * FROM customers');
$customers = Array();
if($result->num_rows >= 1){
while($row = $result->fetch_assoc()){
$customer = new Customer($row['customerName'], $row['phoneNumber'], $row['emailAddress']);
$customers[] = $customer;
}
$result->free();
return $customers;
}
$result->free();
return false;
}
/*
* This is an example of how to use a prepared statement
* with a select query.
*/
public function getCustomer($customerName){
$query = 'SELECT * FROM customers WHERE customerName = ?';
$stmt = $this->mysqli->prepare($query);
$stmt->bind_param('s', $customerName);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows == 1){
$temp = $result->fetch_assoc();
$customer = new Customer($temp['customerName'], $temp['phoneNumber'], $temp['emailAddress']);
$result->free();
return $customer;
}
$result->free();
return false;
}
public function addCustomer($customer){
if(!$this->mysqli->connect_errno){
$query = 'INSERT INTO customers VALUES (?,?,?)';
$stmt = $this->mysqli->prepare($query);
$stmt->bind_param('sss',
$customer->getCustomerName(),
$customer->getPhoneNumber(),
$customer->getEmailAddress());
$stmt->execute();
if($stmt->error){
return $stmt->error;
} else {
return $customer->getCustomerName() . ' added successfully!';
}
} else {
return 'Could not connect to Database.';
}
}
}
?>
Let me know if you need any more code snippets.
Any suggestions would be very much appreciated!
mysqli::prepare returns false if there was an error.
false is not an object, thus you get the error:
call to method function on bind_param() on a non-object.
You can get the error message by examining the $mysqli->error property.
public function addCustomer($customer) {
if(!$this->mysqli->connect_errno) {
$query = 'INSERT INTO customers (customerName,phoneNumber,emailAddress)
VALUES (?,?,?)';
$stmt = $this->mysqli->prepare($query);
if (!$stmt) {
$err = $this->mysqli->error;
echo $err;
// do something with $err
return $err;
}
$stmt->bind_param('sss',
$customer->getCustomerName(),
$customer->getPhoneNumber(),
$customer->getEmailAddress());
if(!$stmt->execute()){
return $stmt->error;
} else {
return $customer->getCustomerName() . ' added successfully!';
}
} else {
return 'Could not connect to Database.';
}
}
The most typical reason why prepare fails is a malformed or invalid query, but without knowing the customer schema or constraints I can't be sure what your particular problem is.
Getting no results no matter how broad my query
PHP: 5.3
Sqlite3: 3.6
PDO: 5.3.3
I would think this should be a very simple process but even looking around I still don't know why I'm getting 0 results. Here is my code:
<?php
$sqlite = new PDO('sqlite:/example.db');
$result = $sqlite->query('SELECT * from foo');
if(!$result)
{
echo 'fail';
return false;
}
?>
Any ideas on what I am doing wrong? The 'foo' table will only have four columns, and this test db only has one table. Running the query in sqlite displays the results fine.
You have to execute the statement first than fetch the result.
You might add try/catch block around the execute method call. and do some error handling.
Here's an example of catching an Exception. Do not use it as a design guideline.
<?php
try
{
$sqlite = new PDO('sqlite:/example.db');
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
$statement = $sqlite->prepare('SELECT * from foo');
try
{
$statement->execute();
}
catch(PDOException $e)
{
echo "Statement failed: " . $e->getMessage();
return false;
}
$result = $statement->fetchAll();
var_dump($result);
?>