I'm trying to use prepared queries, but this code isn't working, it just stucks on the first use of prepare(). Commenting the fist if() does nothing, now it stucks on the second. No connection problems/no errors, just stuck.
If I do all of this using just mysqli_query() everything works great.
function addUser($id){
/*
if ($stmt = $this->mysqli->prepare("SELECT * FROM Users WHERE ID = ?")){
if (!($stmt->bind_param("s", $id))){
return false;
}
if ($stmt->execute()) {
if ($stmt->num_rows!=0){
return false;
}
}else{
return false;
}
}else{
return false;
}*/
if ($stmt = $this->mysqli->prepare("INSERT INTO Users VALUES (?, '')")) {
if (!$stmt->bind_param("s", $id)) {
return false;
}
if (!$stmt->execute()) {
return false;
}
return true;
}
return false;
}
and about debugging, if i change the code like this
function addUser($id){
echo "1";
if ($stmt = $this->mysqli->prepare("SELECT * FROM Users WHERE ID = ?")){
echo "2";
if (!($stmt->bind_param("s", $id))){
return false;
} ...
}else{
echo "3";
} ...
I'll see only "1" on the page.
start of the class:
class db{
private $mysqli;
function __construct($ip, $login, $password, $database){
$this->mysqli = new mysqli($ip, $login, $password, $database) or die("Problem with DB connection!");
$this->mysqli->set_charset("utf8");
}
You never execute() so nothing will happen, therefore no errors will raise.
Here is how I would write it:
function addUser($id){
if ($this->mysqli->connect_errno) {
die('Connect Error: ' . $this->mysqli->connect_errno);
}
if ($stmt = $this->mysqli->prepare("INSERT INTO Users VALUES (?, '')")) {
$stmt->bind_param("s", $id);//did you mean i for type int ?
$stmt->execute();//dont forget this!!
}else{
die('Connect Error: ' . $this->mysqli->connect_errno);
}
return ($stmt->rowCount() > 0)? true : false;
}
Related
When i click first time inserting new data second time click that time it is not checking
function post($payload)
{
$stmt = $this->db->prepareQuery("SELECT * FROM user WHERE emailId= ? or phone= ?");
$stmt->bind_param('ss', $payload->email, $payload->phone);
$stmt->execute();
$result = $stmt->get_result();
while ($rows=$result->fetch_assoc())
{
if($rows['emailId']!=$payload->email || $rows['phone']!=$payload->phone)
{
$stmt = $this->db->prepareQuery("insert into user(emailId,phone,name,city,category_id,password) values(?,?,?,?,?,?)");
$stmt->bind_param('ssssds', $payload->email, $payload->phone, $payload->name, $payload->city, $payload->categ, $payload->pwd);
$stmt->execute();
$stmt->close();
$this->db->commit();
return $payload;
}
else
{
$stmt->close();
echo "Already existed";
return $payload;
}
}
}
You are checking for the record like you know its going to be in the first row. How about introduce another variable say $duplicate
$duplicate = false;
while ($rows=$result->fetch_assoc())
{
if($rows['emailId']==$payload->email || $rows['phone']==$payload->phone)
{
$duplicate = true;
break;
}
}
if(!$duplicate){
$stmt = $this->db->prepareQuery("insert into
user(emailId,phone,name,city,category_id,password) values(?,?,?,?,?,?)");
$stmt->bind_param('ssssds', $payload->email, $payload->phone, $payload->name,
$payload->city, $payload->categ, $payload->pwd);
$stmt->execute();
$stmt->close();
}
else{
echo "Duplicate";
}
I am in the process of learning PDO and am trying to implement it in my current project. When I used mysqli, I could get detailed info about any error using mysqli_error($connection). I googled at what the comparable for PDO would be and found this post, and decided to implement it in my code. However, I am unable to get any error messages even when I know there is an obvious error in the sql statement.
Relevant code:
class Database {
public $connection;
function __construct() {
$this->open_database_connection();
}
public function open_database_connection() {
try {
$this->connection = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute( PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
echo $e->getMessage();
die('Could not connect');
}
} // end of open_database_connection method
public function query($sql, $params = []) {
try {
$query = $this->connection->prepare($sql);
} catch (Exception $e) {
var_dump('mysql error: ' . $e->getMessage());
}
foreach($params as $key => $value) {
if ($key === ':limit') {
$query->bindValue($key, $value, PDO::PARAM_INT);
} else {
$query -> bindValue($key, $value);
}
}
try {
$query->execute();
} catch(Exception $e) {
echo 'Exception -> ';
var_dump($e->getMessage());
}
/*
DID NOT WORK:
if (!$query->execute()) {
print_r($query->errorinfo());
}*/
$result = $query->fetchAll(PDO::FETCH_ASSOC);
$this->confirm_query($result);
return $result;
} // end of query method
function confirm_query($query) {
if (!$query) {
die('mysql error: ');
}
}
When I run the code, I do get the "mysql error", but I do not get any details about it. What am I doing wrong?
Update: As requested, I am providing additional details below.
What I am trying to do is get the user's login detail to be verified. To that end, once the user inputs his credentials , this code runs:
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//check the database for the user
$user_found = User::verify_user($username, $password);
Relevant code from the User class:
public static function verify_user($username, $password) {
global $db;
$username = $db->escape_string($username);
$password = $db->escape_string($password);
$values = [ ":username" => $username,
":password" => $password,
":limit" => 1
];
$result_array = self::find_this_query("SELECT * FROM users WHERE username=:username AND password=:password LIMIT :limit", true, $values);
return !empty($result_array)? array_shift($result_array) : false;
}
public static function find_this_query($sql, $prepared = false, $params = []) {
global $db;
$the_object_array = array();
$result = $db->query($sql, $params);
$arr_length = count($result);
for ($i = 0; $i < $arr_length; $i++) {
$the_object_array[] = self::instantiation($result[$i]);
}
return $the_object_array;
}
public static function instantiation($the_record) {
$the_object =new self; //we need new self because $the_record corresponds to one user!
foreach($the_record as $the_attribute => $value) {
if ($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
public function has_the_attribute($attribute) {
$object_properties = get_object_vars($this);
return array_key_exists($attribute, $object_properties);
}
You have to use PDO::errorInfo():
(...)
public function query($sql, $params = []) {
try {
$query = $this->connection->prepare($sql);
if( !$query )
{
$error = $this->connection->errorInfo();
die( "mysql error: {$error[2]}" );
}
} catch (Exception $e) {
var_dump('mysql error: ' . $e->getMessage());
}
(...)
}
PDO::errorInfo returns an array:
Element 0: SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard);
Element 1: Driver-specific error code;
Element 2: Driver-specific error message.
I would like to write a database connection class and I dont understand how I have to write the select method with bind_param-s. Here is the full code. And here the part of the code where I need the help:
public function select($sql){
$db = $this->connect(); //This methos connect to the DB
$stmt = $db->prepare($sql);
if($stmt === false){ //If the prepare faild
trigger_error("Wrong SQL", E_USER_ERROR);
}
$error = $stmt->bind_param("i", $id);
if($error){
return "Error: ".$stmt->error, $stmt->errno;
}
$err = $stmt->execute();
if($error){
return "Error: ".$stmt->error, $stmt->errno;
}
$result = $stmt->bind_result($id);
$stmt->close();
$dbConnection->closeConnection($db);
return $result;
}
I need to got it parameters or how can I slove it?
You need to pass your values into this function too. And eventually bind them into prepared statement.
Optionally you can pass string with types, but by default all "s" will do.
Also remember that you should connect only ONCE per script execution. and then use one single connection all the way throughout your code.
And get rid of all these error checks. Set mysqli in exception mode instead.
public function q($sql, $values = array(), $types = NULL)
{
$stm = $this->mysql->prepare($sql);
if (!$types)
{
$types = str_repeat("s", count($values));
}
if (strnatcmp(phpversion(),'5.3') >= 0)
{
$bind = array();
foreach($values as $key => $val)
{
$bind[$key] = &$values[$key];
}
} else {
$bind = $values;
}
array_unshift($bind, $types);
call_user_func_array(array($stm, 'bind_param'), $bind);
$stm->execute();
return $stm->get_result();
}
so it can be used like this
$res = $db->q("SELECT name FROM users WHERE id=?", [$id]);
or
$res = $db->q("SELECT name FROM users WHERE id=?", [$id], "i");
your other functions have to be changed as well.
class DB{
public $con;
function __construct()
{
$this->con = new mysqli("localhost", "root", "", "proba_fferenc");
}
public function select(...)
{
// as shown above
}
}
I have this REST api code on backend:
public function createDay($user_id, $day, $startLocation, $startTime) {
$stmt = $this->conn->prepare("INSERT INTO days(day,startLocation,startTime,dayDate) VALUES(?,?,?,?)");
$stmt->bind_param("ssss", $day, $startLocation, $startTime, $dayDate);
$result = $stmt->execute();
$stmt->close();
if ($result) {
// task row created
// now assign the task to user
$new_day_id = $this->conn->insert_id;
$res = $this->createUserDay($user_id, $new_day_id, $dayDate);
if ($res) {
// task created successfully
return $new_day_id;
} else {
// task failed to create
return NULL;
}
} else {
// task failed to create
return NULL;
}
}
and function createDay:
public function createUserDay($user_id, $day_id, $dayDate) {
$stmt = $this->conn->prepare("INSERT INTO user_days(user_id, day_id, $dayDate) values(?, ?, ?)");
$stmt->bind_param("iis", $user_id, $day_id, $dayDate);
$result = $stmt->execute();
if (false === $result) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->close();
return $result;
}
}
this is dbhandler file, now i have a question -
I use
$new_day_id = $this->conn->insert_id;
to get ID of current data but also how I can get $dayDate to use into createUserDay function
So I need to get $dayDate and use it into createUserDay function, is there any way?
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.