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>
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
This is some PHP code for login on a page.
if ($_POST['submit']=="Log In") {
$query = "SELECT * FROM user WHERE email='".mysqli_real_escape_string($link, $email)."' AND password='$md5' LIMIT 1";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
print_r($row);
}
But when I submit LOGIN it doesn't work.
$userCheck = query("SELECT * FROM users WHERE users_email =?",$_POST['user']);
if(count($userCheck)===1){
//we found a match
$data = $userCheck[0];
//now we compare the encryted password
if(crypt($_POST['password'],$data['users_hash'])===$data['users_hash']){
//the password match... the encrypted password
$logged=1;
//so we set the cookie if the user checked the cookie box
//cookie and session code
echo 1;
}else{
//meaning wrong password
echo 2;
}
}else{
//wrong username
echo 0;
}
I am using a custom function working with PDO... I can post the function here if you need to
custom query function using PDO
function query(/* $sql [, ... ] */){
// SQL statement
$sql = func_get_arg(0);
// parameters, if any
$parameters = array_slice(func_get_args(), 1);
// try to connect to database
static $handle;
if (!isset($handle))
{
try
{
// connect to database
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
// ensure that PDO::prepare returns false when passed invalid SQL
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (Exception $e)
{
// trigger (big, orange) error
trigger_error($e->getMessage(), E_USER_ERROR);
exit;
}
}
// prepare SQL statement
$statement = $handle->prepare($sql);
if ($statement === false)
{
// trigger (big, orange) error
trigger_error($handle->errorInfo()[2], E_USER_ERROR);
exit;
}
// execute SQL statement
$results = $statement->execute($parameters);
// return result set's rows, if any
if ($results !== false)
{
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
else
{
return false;
}
}
to use it, see the synthax on the top
or:
ex:
$check = query("SELECT * FROM table WHERE column=?",$text);
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.
I have integrated google loing to my website. It's working fantastic. When someone logs in via google for the firs time, then a new entry is stored in the database.
But, when he logs in again..only the last login (a column on the table) should be updated...but instead, mysql adds a new row.
What am I doing wrong here?
public function trigger_registration_from_google($fname,$lname,$email)
{
global $conn;
try
{
if(useremailexists($email))
{
$date = date('Y-m-d');
//run update query
//user already exists, only update
try
{
$s = $conn->prepare("UPDATE users set last_login = :last_login where emailid = :email ");
$s->bindParam(':last_login',$date);
$s->bindParam(':email',$email);
$s->execute();
$s->closeCursor();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{
//insert
//insert now..since he is a new user
$date = date('Y-m-d');
$v=1;
$r="google";
try
{
$s = $conn->prepare("INSERT INTO users(fname,lname,emailid,registeredby,registeredon,last_login,verified) values (:fname,:lname,:emailid,:registeredby,:registeredon,:last_login,:verified)");
$s->bindParam(':fname',$fname);
$s->bindParam(':lname',$lname);
$s->bindParam(':emailid',$email);
$s->bindParam(':registeredby',$r);
$s->bindParam(':registeredon',$date);
$s->bindParam(':last_login',$date);
$s->bindParam(':verified',$v);
$s->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//function
Edit
useremailexists
function useremailexists($email)
{
//check if the email exists
global $conn;
try
{
$s = $conn->prepare("SELECT * from users where emailid = :email");
$s->bindParam(':email',$email);
$s->execute();
if($s->rowCount() > 0)
{
return true;
}
else
{
return false;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//function
Validate if the function useremailexist return true or false , we can't help you without this piece of code.
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);