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
]);
Related
I'm trying to validate float in my laravel app.
I'm using laravel validation and anything I try is not correct.
I tried something like
$validator = Validator::make($request->all(), [
'packages.*.real_price' => 'required|regex:/^\d*(\.\d{2})?$/'
]
I tried with numeric, integer, and basically everything that I can find on the internet, but every time I receive error like:
TypeError: Argument 6 passed to App\Http\Controllers\ProductController::createPackageInfo() must be of the type float, string given
As you can see I'm giving string to test it. Any suggestions?
I'm sending request like
{
"sku":"asd",
"slug":"admin#admin.com",
"category":"2",
"type":"accessory",
"product_info":[
{
"country":184,
"name":"asd",
"slug":"asd",
"description":"asd"
}
],
"packages":[
{
"country":98,
"name":"asd",
"slug":"asd",
"qty":"12",
"real_price":"123",
"sale_price":"asd",
"delivery_price":"123"
}
]
}
How am I calling this method?
try{
$createdPackageInfo = self::createPackageInfo($createdPackage, $country, $name, $slug, $real_price, $sale_price, $delivery_price, $image);
}catch (\Exception $e) {
Log::log('Something bad happened', 'POST', $e);
return response()->json(['response' => false, 'message' => 'Something went wrong with creating package info'], 400);
}
and function that I'm calling
private static function createPackageInfo(int $package_id, int $country_id, string $name, string $slug, float $real_price, float $sale_price, float $delivery_price, string $image)
{
$packageInfo = PackageInfo::create(['package_id' => $package_id, 'country_id' => $country_id, 'name' => $name, 'slug' => $slug, 'real_price' => $real_price, 'sale_price' => $sale_price, 'delivery_price' => $delivery_price, 'image' => $image]);
return $packageInfo->id;
}
The error is pretty clear, when you call your function createPackageInfo, you pass (I guess) the result of the string you showed.
I guess you typed your params in createPackageInfo() function, and in your JSON, we can you have :
"real_price":"123",
"sale_price":"asd",
Double quotes mean the values are STRING typed.
You can simply use :
$createdPackageInfo = self::createPackageInfo($createdPackage, $country, $name, $slug, (float) $real_price, (float) $sale_price, (float) $delivery_price, $image);
How about custom validating if the string is numeric, then do a type conversion of it everytime you pass it to the function
$validator = Validator::make($request->all(), [
'packages.*.real_price' => 'required|numeric'
]
And when you are calling this method, typecast it,
$typecasted_real_price = $real_price+ 0.0;
$createdPackageInfo = self::createPackageInfo($createdPackage, $country, $name, $slug, $typecasted_real_price, $sale_price, $delivery_price, $image);
// or
$createdPackageInfo = self::createPackageInfo($createdPackage, $country, $name, $slug, ($real_price+ 0.0), $sale_price, $delivery_price, $image);
Logic behind adding 0.0
$num = "1000";
// Performing mathematical operation to implicitly type conversion
echo $num + 0.0, "\n"; // value = 1000
echo gettype($num + 0.0), "\n"; // type = double
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.
it may seem to be a silly question, but i dont know why, this thing isn't working for me.
I have an exisiting array
$data = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'password' => $enc_password,
'date_of_adding' => date('d/m/Y'),
'support_timestamp' => $timestamp
);
now i want to insert or append a new key with value into this existing array.
where the new key and its value is
'username' => $username
what i did is that
$data['username'] = $username;
but still the thing isn't working.
Can anybody tell what i am doing wrong??
try this
$data = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'password' => $enc_password,
'date_of_adding' => date('d/m/Y'),
'support_timestamp' => $timestamp
);
$data2 = array('username'=>$username);
$data = array_unshift($data,$data2);
You can do like this:
$data[]=array('username' => $username)
It will append the new array into an existing array
It should work using $data['username'] = $username;
Have a look at it here. Click the run icon
You may use
$data2 = array('username'=>$username);
$data = array_push($data,$data2);
or visit
demo
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.
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`=?"