how can I use 'compare' sentence in findOneBy? - mysql

$em = $this->getDoctrine()->getEntityManager();
$repository = $em->getRepository('UserBundle:items');
$items = $repository->findOneBy(
array('isCancel' => false,
'user' => $username,
array('toDate' => 'ASC'));
I want to add comparing function as
where registeredtime > now()
I can use compare sentence with findOneBy?
or I have to write whole sql?

You can do that as follows
$em = $this->getDoctrine()->getEntityManager();
$repository = $em->getRepository('UserBundle:items');
$items = $repository->findOneBy(
array('isCancel' => false,
'user' => $username,
array('toDate' => 'ASC'));
$criteria = Criteria::create()->where(Criteria::expr()->gt("registeredtime", now()));
$filteredItems = $items->matching($criteria);

You could try it:
...
$startDate = new DateTime();
$qb = $repository->createQueryBuilder('e');
$event = $qb
->andWhere($qb->expr()->eq('e.start_date', ':start_date'))
->setParameter('start_date', $startDate)
->getQuery()
->getOneOrNullResult();

Related

Laravel Empty Password hashing

When I trying to update user data and let The Password Field empty it hashed again that means the password will change and you can't log in again
so is there any way to fix this problem ??
Code
$this->validate($request, [
'first_name'=> 'required|string',
'last_name' => 'required|string',
'email' => 'required|email|unique:users,email,'.Auth::id(),
'password' => 'sometimes|nullable|string|min:8,'.Auth::id(),
'avatar' => 'image|mimes:jpg,jpeg,gif,png,svg|max:2048,'.Auth::id(),
'gender' => 'required',
'country_id'=> 'required',
]);
$user = User::find(Auth::id());
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->email = $request->email;
$user->gender = $request->gender;
$user->country_id = $request->country_id;
$user->password = bcrypt(request('password'));
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save( public_path('/images/avatars/' . $filename ) );
$user->avatar = $filename;
}
$user->save();
return redirect()->back();
You need to check if there is a passoword in the request object first.
if($request->password){
$user->password = bcrypt(request('password'));
}
After editing it, it will be like this:
$this->validate($request, [
'first_name'=> 'required|string',
'last_name' => 'required|string',
'email' => 'required|email|unique:users,email,'.Auth::id(),
'password' => 'sometimes|nullable|string|min:8,'.Auth::id(),
'avatar' => 'image|mimes:jpg,jpeg,gif,png,svg|max:2048,'.Auth::id(),
'gender' => 'required',
'country_id'=> 'required',
]);
$user = User::find(Auth::id());
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->email = $request->email;
$user->gender = $request->gender;
$user->country_id = $request->country_id;
if($request->password){
$user->password = bcrypt(request('password'));
}
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save( public_path('/images/avatars/' . $filename ) );
$user->avatar = $filename;
}
$user->save();
return redirect()->back();
You can simply test on the password if it is present.
$this->validate($request, [
'first_name'=> 'required|string',
'last_name' => 'required|string',
'email' => 'required|email|unique:users,email,'.Auth::id(),
'password' => 'sometimes|nullable|string|min:8,'.Auth::id(),
'avatar' => 'image|mimes:jpg,jpeg,gif,png,svg|max:2048,'.Auth::id(),
'gender' => 'required',
'country_id'=> 'required',
]);
$user = User::find(Auth::id());
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->email = $request->email;
$user->gender = $request->gender;
$user->country_id = $request->country_id;
if ($request->password) {
$user->password = bcrypt($request->password);
}
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save( public_path('/images/avatars/' . $filename ) );
$user->avatar = $filename;
}
$user->save();
return redirect()->back();
First you may change your validation rule to check if password is not empty when present:
'password' => 'sometimes|required|string|min:8',
Then bcrypt if it's not empty and present on the request vie $request->filled() method:
if ($request->filled('password'))
{
$user->password = bcrypt($request->password);
}

i want to separate Date and time format in json from laravel

how are you ?
i have Laravel project and the json return date like this
2019-05-04
and time like this
18:00:00
how can i make it like this
year : 2019
month : MAY
Day : 04
time : 06:00
timeS : PM
my code now is this
the model
public $table = 'bookings';
protected $dates = [
'date',
'created_at',
'updated_at',
'deleted_at',
];
protected $fillable = [
'date',
'time',
'user_id',
'type_id',
'persons',
'order_no',
'created_at',
'updated_at',
'deleted_at',
'table_cat_id',
'booking_status_id',
];
the controller is
public function index(Request $request)
{
$user = Auth::user();
if(isset($user->id)){
$bookings = Booking::where('user_id', $user->id)->get();
}else{
$bookings = null;
}
return response()->json($bookings);
}
You dont have added your code to the question, so i will try provide an answer using carbon:
//add this line to your controller:
use Carbon\Carbon;
//Parse the date you want to use:
$date = Carbon::parse($date); //Or use Carbon::now() to get the current time
$year = $date->year;
$month = $date->format('F');
$day = $date->day;
$timeS = $date->format('A');
$time = $date->format('H:i');
//now return your json:
return response()->json([
'year' => $year,
'month' => $month,
'day' => $day,
'timeS' => $timeS,
'time' => $time,
]);
Update
To work with your code:
Choose the date you want to use, like created_at or updated_at.
Then, do something like this:
//add this line to your controller:
use Carbon\Carbon;
public function index(Request $request)
{
$user = Auth::user();
if(isset($user->id)){
$bookings = Booking::where('user_id', $user->id)->get();
//With the created_at field:
foreach($bookings as $booking){
$date = Carbon::parse($booking->created_at);
$year = $date->year;
$month = $date->format('F');
$day = $date->day;
$timeS = $date->format('A');
$time = $date->format('H:i');
$dates = array(
'year' => $year,
'month' => $month,
'day' => $day,
'timeS' => $timeS,
'time' => $time
);
$booking->dates = $dates;
}
}else{
$bookings = null;
}
return response()->json($bookings);
}
Hope it helps.
Another solution
You can append the $dates to your model.
To do it follow this steps:
Add the $appends to your model:
protected $appends = ['dates'];
Use Carbon in your model:
use Carbon\Carbon;
Create a getDatesAttribute function in your model (it is an accessor):
public function getDatesAttribute()
{
$date = Carbon::parse($this->created_at) //You can use any date field you want
$year = $date->year;
$month = $date->format('F');
$day = $date->day;
$timeS = $date->format('A');
$time = $date->format('H:i');
return array (
'year' => $year,
'month' => $month,
'day' => $day,
'timeS' => $timeS,
'time' => $time
);
}
Now, everytime you execute a query with your model, the dates will be include to the returned collection. You can access it with:
$record->dates
Note that $record is the just an example name.
Read more about Appending Values To JSON here.

JSON data array query

i am using jsonTable to parse the data in to the Google table and it is working fine. now i have a problem to add multiple queries at the same time and display the data only in two columns of array which is already defined. here is my code:
$data = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$table = array();
$table['cols'] = array(
array('label' => 'Vehicle', 'type' => 'number'),
array('label' => 'Distance Left', 'type' => 'number')
);
$rows = array();
while ($nt = mysql_fetch_array($data))
{
$temp = array();
$temp[] = array('v' => 'Nextoilchange');
$temp[] = array('v' =>$nt['Nextoilchange']);
// insert the temp array into $rows
$rows[]['c'] = $temp;
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
my first problem is this i want to add multiple queries in $data and each query gives one result. and my next problem is i want to display the data of multiple queries in above column defined as Distance left. and in vehicle column i want to add static data like above in $temp(1st row). i have searched a lot and i am confused how to do this. Please help me i want to display the table like this:
Vehicle Distance Left
nextoilchange 500
nextfilter 300
nextcheckup 400
I'm not tested this . If not not work try something like this .
<?php
$data[1] = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$data[2] = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$table[1]['cols'] = array(array('label' => 'Vehicle', 'type' => 'number'),array('label' => 'Distance Left', 'type' => 'number'));
$table[2]['cols'] = array(array('label' => 'Vehicle', 'type' => 'number'),array('label' => 'Distance Left', 'type' => 'number'));
foreach($table as $key=>$eachtable)
{
$cols = $eachtable['cols'];
while ($nt = mysql_fetch_array($newdata))
{
foreach($cols as $key1=>$each_col)
{
if($each_col['label'] == $nt) //you have match the conditions
{
$row[$key1] = $nt['yourvalue'];
}
else
{
$row[$key1] = $nt['yourvalue1'];
}
$rows[] = $row;
}
}
$table[$key]['rows'] = $rows;
}
$jsonTable = json_encode($table);

ZF2 how to rename name of field with join

Because my join includes a field named 'id' as well, I need to rename this field name during my sql so it won't override my id field name from the first selected tabel.
My query look likes as follow;
$select = new \Zend\Db\Sql\Select();
$select->from('websites');
$select->join(array('s' => 'websites_statistics'), 's.website_id = websites.id');
$select->where(array('websites.website' => $website));
$select->order('s.timestamp DESC')->limit(1);
$rowset = $this->tableGateway->selectWith($select);
$row = $rowset->current();
return $row;
So, 's' 'id' field should be renamed to something like 'stat_id'.
Thanks in advance!
Nick
$select = new \Zend\Db\Sql\Select();
$select->from('websites');
->join(array('s' => 'websites_statistics'), 's.website_id = websites.id',
array('stat_id' => 's.id')); // <-- here is the alias
->where(array('websites.website' => $website));
->order('s.timestamp DESC')
->limit(1);
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$select->from(array('p' => 'sub_categories'), array('subcategory_id'=>'p.subcategory_id','subname'=>'p.name'))
->join(array('pa' => 'categories'), 'pa.category_id = p.category_id', array('catname'=>'pa.name'));
$result = $this->getAdapter()->fetchAll($select);
*
And also we can use this method
use Zend\Db\Sql\Expression;
->join(array('s' => 'websites_statistics'), 's.website_id = websites.id',
array('stat_id' => new Expression('s.id'))); // <-- here is the alias
This is best method If you have to use Mysql 'AS' on zf2
example : array('Month' => new Expression('DATE_FORMAT(`salesInvoiceIssuedDate`, "%m")'))

SELECT and list children and parent - alternative [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
SELECT and list children and parent
I received this answer from xception:
https://stackoverflow.com/a/12770593/445820
Unfortunately, GROUP_CONCAT isn't the solution for me and the other question is too extended, therefore I am re-asking this question.
I need an alternative to that query with subqueries. Since I'm not good enough with queries, this task is beyond my abilities too.
Help please.
Here is the code:
// Prepare query
$columns = "c.rule_id, c.rule_title, GROUP_CONCAT(r.rule_description ORDER BY r.rule_position ASC SEPARATOR '~sep~') AS rule_desc, ";
$columns .= "GROUP_CONCAT(r.parse_bbcode ORDER BY r.rule_position ASC SEPARATOR '~sep~') AS bbcode, ";
$columns .= "GROUP_CONCAT(r.parse_links ORDER BY r.rule_position ASC SEPARATOR '~sep~') AS links, ";
$columns .= "GROUP_CONCAT(r.parse_smilies ORDER BY r.rule_position ASC SEPARATOR '~sep~') AS smilies";
$sql_array = array(
'SELECT' => $columns,
'FROM' => array(RULES_TABLE => 'c'),
'LEFT_JOIN' => array(
array(
'FROM' => array(RULES_TABLE => 'r'),
'ON' => 'r.parent_id = c.rule_id',
),
),
'WHERE' => 'c.parent_id = 0 AND r.public = 1',
'GROUP_BY' => 'c.rule_id',
'ORDER_BY' => 'c.cat_position',
);
$sql = $db->sql_build_query('SELECT', $sql_array);
$result = $db->sql_query($sql);
$cat_count = 1;
$alpha_count = 'abcdefghijklmnopqrstuvwxyz';
while ($row = $db->sql_fetchrow($result))
{
$template->assign_block_vars('rules', array(
'RULE_CATEGORY' => $row['rule_title'],
'ROW_COUNT' => $cat_count,
));
$rules_ary = explode('~sep~', $row['rule_desc']);
$parse_bbcode = explode('~sep~', $row['bbcode']);
$parse_links = explode('~sep~', $row['links']);
$parse_smilies = explode('~sep~', $row['smilies']);
$counter = 0;
foreach ($rules_ary as $key => $rule)
{
$uid = $bitfield = $options = '';
generate_text_for_storage($rule, $uid, $bitfield, $options, $parse_bbcode[$key], $parse_links[$key], $parse_smilies[$key]);
$template->assign_block_vars('rules.rule', array(
'RULE_DESC' => generate_text_for_display($rule, $uid, $bitfield, $options),
'ALPHA_COUNT' => $alpha_count{$counter},
));
$counter++;
}
$cat_count++;
}
$db->sql_freeresult($result);
Some of the functions might be unknown to you. FYI this is phpBB related code.
Sorry for not adding the code in the first time.
// Prepare query
$columns = "c.rule_id, c.rule_title, r.rule_description AS rule_desc, ";
$columns .= "r.parse_bbcode AS bbcode, ";
$columns .= "r.parse_links AS links, ";
$columns .= "r.parse_smilies AS smilies";
$sql_array = array(
'SELECT' => $columns,
'FROM' => array(RULES_TABLE => 'c'),
'LEFT_JOIN' => array(
array(
'FROM' => array(RULES_TABLE => 'r'),
'ON' => 'r.parent_id = c.rule_id',
),
),
'WHERE' => 'c.parent_id = 0 AND r.public = 1',
'ORDER_BY' => 'c.cat_position',
);
$sql = $db->sql_build_query('SELECT', $sql_array);
$result = $db->sql_query($sql);
$cat_count = 0;
$alpha_count = 'abcdefghijklmnopqrstuvwxyz';
$prev_rule_id = 0;
$r_rule_titles = array();
$rule_id = null;
while ($row = $db->sql_fetchrow($result))
{
if( $rule_id != $row['rule_id'] ) {
$rule_id = $row['rule_id'];
$cat_count++;
$counter = 0;
$template->assign_block_vars('rules', array(
'RULE_CATEGORY' => $row['rule_title'],
'ROW_COUNT' => $cat_count,
));
}
$uid = $bitfield = $options = '';
generate_text_for_storage($row['rule_desc'], $uid, $bitfield, $options, $row['bbcode'], $row['links'], $row['smilies']);
$template->assign_block_vars('rules.rule', array(
'RULE_DESC' => generate_text_for_display($row['rule_desc'], $uid, $bitfield, $options),
'ALPHA_COUNT' => $alpha_count{$counter},
));
$counter++;
}
$db->sql_freeresult($result);