My simple query:
$list = Doctrine_Query::create()
->from('liste l')
->where('l.id =?', $id)
->fetchOne();
$id = 123;
I know that there is no entry with the $id =123 in my database. When I count $list, I get the result 1. How do I know with my query or the result of my query that there is no entry with the $id = 123 in my database?
var_dump gives me false!
So I just do a quick:
if ($list == FALSE) {
....}
Related
This query returns 13 individual arrays:
$array = array($pgff_id, $pgfm_id, $pgmf_id, $pgmm_id, $mgff_id, $mgfm_id, $mgmf_id, $mgmm_id, $pgf_id, $pgm_id, $mgf_id, $mgm_id, $fid, $mid);
foreach($array as $id) {
$stmt = $db->prepare("SELECT birth_year, death_year FROM index WHERE id = ?");
$stmt->execute([$id]);
$data = $stmt->fetch(PDO::FETCH_ASSOC);
print_r shows that they look like this:
Array ([birth_year] => 1750 [death_year] => 1824)
Array ([birth_year] => 1770 [death_year] => 1836)
... etc
Is it possible to assign a number or name to these individual arrays? The results are not useful without a way to identify them.
I tried doing it like shown below. This way does number the arrays but orders the results as they are found in the table. I really need the results ordered as they are in $array (which the first method does manage).
$in = str_repeat('?,', count($array) - 1) . '?';
$sql = "SELECT birth_year, death_year FROM index WHERE id IN ($in)";
$stmt = $db->prepare($sql);
$stmt->execute($array);
$data = $stmt->fetchAll();
Taking your code and adding in id as an expression in the query would result in this:
$in = str_repeat('?,', count($array));
$sql = "SELECT id, birth_year, death_year FROM index WHERE id IN ($in)";
$stmt = $db->prepare($sql);
$stmt->execute($array);
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo "here starts another row:<br>";
echo "id = ".$row["id"]."<br>";
echo "birth_year = ".$row["birth_year"]."<br>";
echo "death_year = ".$row["death_year"]."<br>";
}
So, that's how you can access it.
You can rearrange the data in the rows after you've received them from the database, again by using a foreach loop:
$birth = [];
$death = [];
foreach ($rows as $row) {
$id = $row["id"];
$birth[$id] = $row["birth_year"];
$death[$id] = $row["death_year"];
}
Now you can access both arrays to get the birth or death year based on the id like this:
echo $birth[4]. 'and '. $death[4];
where id is 4.
Can somebody help me convert this Sql Query
SELECT *
FROM customer c
LEFT JOIN customer_order co
ON c.customer_number = co.customer_number
AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid'
AND c.order_status = 'unserve'
AND co.cus_ord_no IS null
into Codeigniter query just like the image below for example
When query statements do not have clauses that need to change conditionally then using $this->db-query() is the way to go.
$sql = "SELECT * FROM customer c LEFT JOIN customer_order co
ON c.customer_number=co.customer_number AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid' AND c.order_status='unserve' AND co.cus_ord_no IS null";
$query = $this->db->query($sql)->result();
echo json_encode($query);
It might be wise to include a check on the return from query() though because if it fails (returns false) then the call to result() will throw an exception. One way that can be handled is like this.
$query = $this->db->query($sql);
if($query !== FALSE)
{
echo json_encode($query->result());
return;
}
echo json_encode([]); // respond with an empty array
Query Builder (QB) is a nice tool, but it is often overkill. It adds a lot of overhead to create a string that literally is passed to $db->query(). If you know the string and it doesn't need to be restructured for some reason you don't need QB.
QB is most useful when you want to make changes to your query statement conditionally. Sorting might be one possible case.
if($order === 'desc'){
$this->db->order_by('somefield','DESC');
} else {
$this->db->order_by('somefield','ASC');
}
$results = $this->db
->where('other_field', "Foo")
->get('some_table')
->result();
So if the value of $order is 'desc' the query statement would be
SELECT * FROM some_table WHERE other_field = 'Foo' ORDER BY somefield 'DESC'
But if you insist on using Query Builder I believe this your answer
$query = $this->db
->join('customer_order co', "c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared')", 'left')
->where('c.customer_status','unpaid')
->where('c.order_status','unserve')
->where('co.cus_ord_no IS NULL')
->get('customer c');
//another variation on how to check that the query worked
$result = $query ? $query->result() : [];
echo json_encode($result);
You can do
public function view_customers()
{
$sql = "SELECT * FROM customer c LEFT JOIN customer_order co ON c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared') WHERE c.customer_status='unpaid' AND c.order_status = 'unserve' AND co.cus_ord_no IS null";
return $this->db->query($sql)->result();
}
You can use row() for one output to object, or row_array() if one output but array. result() is multiple objects and result_array() is multiple arrays.
My way do usually is like this:
Controller:
public function view()
{
$this->load->model('My_Model');
$data = new stdclass;
$data->user_lists = $this->my_model->view_users(array('nationality'=>'AMERICAN'));
}
Model:
public function view_users($param = null) //no value passed
{
$condition = '1';
if (!empty($param)) { //Having this will trap if you input an array or not
foreach ($param as $key=>$val) {
$condition .= " AND {$key}='{$val}'"; //Use double quote so the data $key and $val will be read.
}
}
$sql = "SELECT * FROM users WHERE {$condition}"; //Use double quote so the data $condition will be read.
// Final out is this "SELECT * FROM users WHERE 1 AND nationality='AMERICAN'";
return $this->db->query($sql)->result();
}
For this update query, I'm trying to get the id after I run it.
$results = DB::table('testDB123.users')
->where('fbID', '=', $x['id'])
->update([
'updated_at' => $x['currDate'],
'fbFirstName' => $x['firstName'],
'fbLastName' => $x['lastName']
]
);
Tried this with no luck $results->id
Is there anything similar to insertGetId for update queries?
$id = DB::table($table1)->insertGetId([...])
update() method doesn't return an object, so you have two options:
Option 1
Use updateOrCreate():
$user = User::updateOrCreate(['fbID' => $x['id']], $dataArray);
$id = $user->id;
Option 2
Get an object and update it:
$user = User::where('fbID', '=', $x['id'])->first();
$user->update($dataArray);
$id = $user->id;
I want to run following query in symfony doctrine.
SELECT p.id AS id FROM skiChaletPrice p WHERE ski_chalet_id = ? AND month = ?
I wrote my doctrine query as following.
$q = Doctrine_Query::create()
->select('p.id AS id')
->from('skiChaletPrice p')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from);
$result = $q->fetchOne();
if ($result->count() > 0) {
return $result->toArray();
} else {
return null;
}
But my result always include all columns in the table. What the issue? Please help me.
The issue is that fetchOne() will return a Doctrine object, which implicitly contains all the columns in the table. $result->toArray() is converting that doctrine object to an array, which is why you get all the columns.
If you only want a subset of column, don't hydrate an object, instead do something like this:
$q = Doctrine_Query::create()
->select('p.id AS id')
->from('skiChaletPrice p')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from);
$results = $q->execute(array(), Doctrine::HYDRATE_SCALAR);
See http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/data-hydrators.html
This is how I should do it:
$result = Doctrine_Query::create()
->select('id')
->from('skiChaletPrice')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from)
->limit(1)
->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
// result will be a single id or 0
return $result ?: 0;
// if you want array($id) or array() inseatd
// return (array) $result;
I'm having a bit of a problem with join SUM in fuel php.
When I use it like this
$query = DB::select(
'stream_post.*',
'SUM(stream_comment.comment_stream_id)'
)->from('stream_post');
$query->join('stream_comment', 'LEFT');
$query->on('stream_post.stream_id', '=', 'stream_comment.comment_stream_id');
$query->join('users_metadata');
$query->on('stream_post.user_id', '=', 'users_metadata.user_id');
$query->limit(10);
$query->order_by('stream_id', 'DESC');
$result = $query->execute();
if(count($result) > 0) {
foreach($result as $row)
{
$data[] = $row;
}
return $data;
}
I get this error
Column not found: 1054 Unknown column 'SUM(stream_comment.comment_stream_id)' in 'field
What do im doing wrong?
You need to use the expr function to create an expression in the select statement
$result = DB::select(DB::expr(' SUM(stream_comment.comment_stream_id) as count'))->from('stream_post')->execute();
Documented here http://docs.fuelphp.com/classes/database/usage.html