Hi i am using a PDO wrap object
https://github.com/Xeoncross/DByte/blob/master/example.php
having some issue with Updates features.
This is their defined function for update
static function update($table, $data, $value, $column)
{
$keys = implode('`=?,`', array_keys($data));
if($statement = DB::query(
"UPDATE`$table`SET`$keys`=? WHERE`$column`=?",
array_values($data + array($value))
))
return $statement->rowCount();
}
My function to update
public function update_users($user_id, $user_name, $user_email, $user_role, $user_phone){
$user_data = array(
'user_name' => $user_name,
'user_email' => $user_email,
'user_pass' => $user_pass,
'user_role' => $user_role,
'user_phone' => $user_phone,
);
$result = DB::update('users', $user_data, $user_id);
}
This is not working Error i am getting is,
Warning: Missing argument 4 for DB::update(), called in \XXXClass.php on line 47 and defined in XXXX\Application\inc\DB.php on line 120
You need to pass in the column name (4th argument of the method):
$result = DB::update('users', $user_data, $user_id, 'user_id'); // I presume `user_id` is the name of that column
Also it doesnt hurt to place spaces between SQL keywords and column/table names:
"UPDATE `$table` SET `$keys`=? WHERE `$column`=?"
Related
I have reg_dental_camp table having columns id, reg_name, reg_email, reg_phone, reg_type, reg_info, created_at, updated_at
I want to fetch the table data in Laravel and show them using ajax.
The function I have written is:
public function showUsers(){
$table ="SELECT * FROM `reg_dental_camp`";
$primaryKey = 'id';
$userColumns = array(
array( 'db' => 'id', 'dt' => 'id' ),
array( 'db' => 'reg_name', 'dt' => 'reg_name' ),
array( 'db' => 'reg_email', 'dt' => 'reg_email' ),
array( 'db' => 'reg_phone', 'dt' => 'reg_phone' ),
array( 'db' => 'reg_type', 'dt' => 'reg_type' ),
array( 'db' => 'reg_info', 'dt' => 'reg_info' ),
array(
'db' => 'created_at',
'dt' => 'created_at',
'formatter' => function( $d, $row ) {
return date( 'jS M y', strtotime($d));
}
)
);
if($_SERVER['HTTP_HOST']=='localhost'){
$sql_details = array(
'user' => 'root',
'pass' => '',
'db' => 'ubl',
'host' => 'localhost'
);
}
$userResult = SSP::simple( $_GET, $sql_details, $table, $primaryKey, $userColumns);
print_r($userResult);
}
While visiting from the main page it is showing error number 500 on ajax call URL and visiting directly to the ajax call URL is is giving SQL error SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM `reg_dental_camp`
How can I solve this problem? Thanks in advance
Your are using simple method wrongly
Simple implementation from GitHub
static function simple ( $request, $conn, $table, $primaryKey, $columns )
{
$bindings = array();
$db = self::db( $conn );
// Build the SQL query string from the request
$limit = self::limit( $request, $columns );
$order = self::order( $request, $columns );
$where = self::filter( $request, $columns, $bindings );
// Main query to actually get the data
$data = self::sql_exec( $db, $bindings,
"SELECT `".implode("`, `", self::pluck($columns, 'db'))."`
FROM `$table`
$where
$order
$limit"
);
// Data set length after filtering
$resFilterLength = self::sql_exec( $db, $bindings,
"SELECT COUNT(`{$primaryKey}`)
FROM `$table`
$where"
);
$recordsFiltered = $resFilterLength[0][0];
// Total data set length
$resTotalLength = self::sql_exec( $db,
"SELECT COUNT(`{$primaryKey}`)
FROM `$table`"
);
$recordsTotal = $resTotalLength[0][0];
/*
* Output
*/
return array(
"draw" => isset ( $request['draw'] ) ?
intval( $request['draw'] ) :
0,
"recordsTotal" => intval( $recordsTotal ),
"recordsFiltered" => intval( $recordsFiltered ),
"data" => self::data_output( $columns, $data )
);
}
So you need to provide table name only not a query. Change table variable to
$table = "reg_dental_camp"
I'm trying to implement a verification email process to my website but I got an error
Fatal error: Uncaught Error: Call to a member function execute() on
bool in :56 Stack trace: #0 {main} thrown in on line 56
Here is my code:
$user_activation_code = md5(rand());
// Nuevo Usuario
$hashed = password_hash($password,PASSWORD_DEFAULT);
$insert_query = 'INSERT INTO clientes (full_name,email,user_activation_code,user_email_status,password,permissions,street,numero,interior,city,state,zip_code,country) VALUES ("$name","$email","$user_activation_code",:user_email_status,"$hashed",cliente,"$street","$numero","$interior","$city","$state","$zip_code",Mexico)';
$statement = $db->prepare($insert_query);
$statement -> execute(
array(
'full_name' => $_POST['name'],
'email' => $_POST['email'],
'password' => $hashed,
'user_activation_code' => $user_activation_code,
':user_email_status' => 'no verificado'
)
);
$result = $statement->fetchAll();
You need to properly bind your array to the query.
PDO for using an associative array you need to have the values in both the query string and the same values in your key.
$insert_query = 'INSERT INTO clientes (full_name,email,user_activation_code,user_email_status,password,permissions,street,numero,interior,city,state,zip_code,country) VALUES (:full_name,:email,:user_activation_code,:user_email_status,:password,"cliente","$street","$numero","$interior","$city","$state","$zip_code","Mexico")';
array(
':full_name' => $_POST['name'],
':email' => $_POST['email'],
':password' => $hashed,
':user_activation_code' => $user_activation_code,
':user_email_status' => 'no verificado'
)
Please also bind your other values such as: $city, $state etc.
I'm starin to use Carbon to manage Dates in PHP with MySQL, but I'm having problems with a simple Insert statement. To run SQL statements I'm using Medoo, this is my code to insert:
public function register($code, $fullname, $address, $phones, $email, $now){
$registration = $this->_app['medoo']->insert("customers",[
'cus_code' => $code,
'cus_fullname' => $fullname,
'cus_address' => $address,
'cus_phone_s' => $phones,
'cus_email' => $email,
'created_at' => $now
]);
return $registration;
}
And this is where I pass the value:
$code = $request->get('code');
$name = $request->get('name');
$phones = $request->get('phone_s');
$address = $request->get('address');
$email = $request->get('email');
$now = Carbon::now('America/Monterrey');
$customer_registration = $app['customer.model']->register($code, $name, $address, $phones, $email, $now);`
if($customer_registration){
$request_status = true;
}else {
$request_errors[] = "Ocurrio un error al registrar el cliente";
}
The statement returns an error and this is the output if I debug it:
INSERT INTO "customers"
("cus_code", "cus_fullname", "cus_address", "cus_phone_s", "cus_email", "created_at")
VALUES
('n20', 'notaria 20', 'lerdo 202', '1234567890', 'mail#mail.com')
As you can see, the date is missing and It doesn't make any sense because if I echo it inside my function...
public function register($code, $fullname, $address, $phones, $email, $now){
echo '<p>this is the variable now: '.$now.'</p>';
$this->_app['medoo']->debug()->insert("customers",[
'cus_code' => $code,
'cus_fullname' => $fullname,
'cus_address' => $address,
'cus_phone_s' => $phones,
'cus_email' => $email,
'created_at' => $now
]);
die();
return $registration;
}
outputs...
this is the variable now: 2017-05-14 00:52:00
INSERT INTO "customers"
("cus_code", "cus_fullname", "cus_address", "cus_phone_s", "cus_email", "created_at")
VALUES
('n20', 'notaria20', 'lerdo 202', '1234567890', 'mail#mail.com')
I changed $now for Date('Y-m-d H:m:s') and It works, but for my app I need to use Carbon.
I hope I was clear with this, I'm not so good with english, please help!
The answer of this question is in comments and which is not the way to post in SO so I am posting the answer here to close the question.
Here he needs to pass timestamp in SQL format as laravel's insert() doesn't affect created_at and updated_at values and needs manual efforts to add created_at values, so the correct way to pass it into insert() method manually should be:
Carbon::now('America/Monterrey')->format('Y-m-d H:m:s');
Thus the code should look like this
$now =Carbon::now('America/Monterrey')->format('Y-m-d H:m:s');
$this->_app['medoo']->debug()->insert("customers",[
'cus_code' => $code,
'cus_fullname' => $fullname,
'cus_address' => $address,
'cus_phone_s' => $phones,
'cus_email' => $email,
'created_at' => $now
]);
I am trying to build the array that will return to my ajax success. How do I build the array after binding it to something like :some variable.
The following script runs to completion, and inserts with no problem into sql. But the variables comment and transaction come back as null in the response. I think the problem is using $comment and $transaction when building the array. What is the right way to reference these values in the array?
require('../dbcon2.php');
//Connection 1
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("UPDATE listings SET comment = :comment, transaction = :transaction, ad_link = :ad_link WHERE id = :id");
// Bind
$stmt->bindParam(':id', $_POST['id']);
$stmt->bindParam(':comment', $_POST['comment']);
$stmt->bindParam(':transaction', $_POST['transaction']);
$stmt->execute();
// Build array
$response = array
('state' => 200, "success" => true, "id" => ':id', "comment" => $comment, "transaction" => $transaction
);
exit(json_encode($response));
}
catch (Exception $e) {
// create a asociative array
$data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
// encode data and exit.
exit(json_encode($data));
}
As per OP's wish:
Do as you did for "id" => ':id'
"id" => ':id', "comment" => ':comment', "transaction" => ':transaction'
Plus, quoting Jeroen (kudos to)
Why don't you use the $_POST variable? That contains the values you need and you use them already in your database query.
You can't retrieve bound values after calling ->bindParam(); also, the variables $comment and $transaction aren't defined (unless you set them yourself or when using voodoo php settings).
That said, you already know those values:
$response = array(
'state' => 200,
"success" => true,
"id" => $_POST['id'],
"comment" => $_POST['comment'],
"transaction" => $_POST['transaction'],
);
Btw, in the exception branch you have a small bug:
$data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
^
You should use $e->getMessage() instead.
I am doing a update on my framework. Previously i am using zf1 zend db select for my data access object class. Now, i would like to make a shift and upgrade to zf2. I have problems translating for the insert, update, select, and delete queries and wonder if someone can shed some light to assist me.
What are the new classes that i should use?
Does it involve alot of re-coding?
Any references will helps alot ( Been looking through stackoverflow, but haven found a comprehensive guide)
Below is my code for insert/update/delete/select for zf1
Insert
$userdata = array('email' => $email,
'name' => $name,
'gender' => $gender,
'location' => $location,
'fbid' => $fbid,
'ipaddress' => $ipaddress,
'jointimestamp'=>new Zend_Db_Expr('NOW()'));
$this->dbo->insert('users', $userdata);
return $this->dbo->lastInsertId();
Select
if($this->dbo->fetchOne('SELECT id FROM users WHERE username = ?',$username)){
return true;
}else{
return false;
}
Update
$userdata = array($field => $value);
$this->dbo->update('user', $userdata, $this->dbo->quoteInto('useremail = ?', $this->user));
Also, does zf2 has fetchall, fetchone, fetchrow methods etc?
Appreciate any advices.
After reading the documentation, i have come out with the insert/select/update queries for zf2. Below is the code snippet for benefit of those who may need it in future. I am using Zend\Db\Select as a standalone classes for my custom mvc framework.
Adapter
$adapter = new Zend\Db\Adapter\Adapter(array(
'driver' => 'pdo_mysql',
'host' => DB_HOST,
'database' => DB_PREFIX.DB_NAME,
'username' => DB_USER,
'password' => DB_PW
));
Select
$select = $this->sql->select()
->from('table')
->join('users', 'users.id = table.userid')
->order("table.createdtimestamp DESC");
$statement = $this->sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($result);
return $resultSet->toArray();
Insert
$insert = $this->sql->insert()
->into("messages");
$userdata = array(
'message' => $message,
'createdtimestamp'=>new Zend\Db\Sql\Expression('NOW()'),
'userid' => $userid);
$insert->values($userdata );
$statement = $this->sql->prepareStatementForSqlObject($insert);
$result = $statement->execute();
//return last insert id
return $this->dbo->getDriver()->getLastGeneratedValue();
Update
$update = $this->sql->update()
->table('posts')
->where(array('pid'=>$pid));
$numbercountarr = array('numbercount' => new Zend\Db\Sql\Expression('numbercount+ 1'));
$update->set($numbercountarr );
$statement = $this->sql->prepareStatementForSqlObject($update);
result = $statement->execute();
To count rows
$statement = $this->sql->prepareStatementForSqlObject($query);
$result = $statement->execute();
return $result->count();
Hope this can help those who need it save some time.