I have the following columns in the same table
Column 1
--------
1
2
3
Column 2
--------
4
5
6
I want it to be displayed like
Columns
--------
1
2
3
4
5
6
You can use unionAll
$first = DB::table('yourTable')
->select('column1 as res');
$result = DB::table('yourTable')
->select('column2 as res')
->unionAll($first)
->get();
You can make the Union of your data by taking out separately and merge it after. You can use union() as well as merge(), One thing to mention is that both data must have same skelton means structure.
use DB;
public function yourFunction(){
$data_1 = DB::table('table_name')->get();
$data_2 = DB::table('table_name')->get();
//your final data
$final_data = $data_1->union($data_2);
}
Assuming values are in the same row:
$data = DB::table('table_name')->select('column1', 'column2')->get();
$c = count($data);
if ($c) {
$col1 = [];
$col2 = [];
foreach ($data as $k => $d) {
$col1[] = $d->column1;
$col2[$c + $k] = $d->column2;
}
$result = array_merge($col1, $col2);
foreach ($result as $value) {
echo $value."\n";
}
} else {
echo "No data in table.";
}
Related
everyone.
In the codeigniter there is update_batch function by using it we are able to bulk update multiple rows.
$this->db->update_batch('table_name', $update_data_array, 'where_condition_field_name');
I want similar functionality in core PHP in one function or in one file. Is there any workaround?
Is there any way to extract update_batch function from Codeigniter in one file/function?
I tried to extract this function but it is very lengthy process and there will be many files / functions should be extracted.
Please help me in this regard
Thanks in advance
You can also insert multiple rows into a database table with a single insert query in core php.
(1)One Way
<?php
$mysqli = new mysqli("localhost", "root", "", "newdb");
if ($mysqli == = false) {
die("ERROR: Could not connect. ".$mysqli->connect_error);
}
$sql = "INSERT INTO mytable (first_name, last_name, age)
VALUES('raj', 'sharma', '15'),
('kapil', 'verma', '42'),
('monty', 'singh', '29'),
('arjun', 'patel', '32') ";
if ($mysqli->query($sql) == = true)
{
echo "Records inserted successfully.";
}
else
{
echo "ERROR: Could not able to execute $sql. "
.$mysqli->error;
}
$mysqli->close();
? >
(2)Second Way
Let's assume $column1 and $column2 are arrays with same size posted by html form.
You can create your sql query like this:-
<?php
$query = 'INSERT INTO TABLE (`column1`, `column2`) VALUES ';
$query_parts = array();
for($x=0; $x<count($column1); $x++){
$query_parts[] = "('" . $column1[$x] . "', '" . $column2[$x] . "')";
}
echo $query .= implode(',', $query_parts);
?>
You can easily construct similar type of query using PHP.
Lets use array containing key value pair and implode statement to generate query.
Here’s the snippet.
<?php
$coupons = array(
1 => 'val1',
2 => 'va2',
3 => 'val3',
);
$data = array();
foreach ($coupons AS $key => $value) {
$data[] = "($key, '$value')";
}
$query = "INSERT INTO `tbl_update` (id, val) VALUES " . implode(', ', $data) . " ON DUPLICATE KEY UPDATE val = VALUES(val)";
$this->db->query($query);
?>
Alternatively, you can use CASE construct in UPDATE statement. Then the query would be something
like:
UPDATE tbl_coupons
SET code = (CASE id WHEN 1 THEN 'ABCDE'
WHEN 2 THEN 'GHIJK'
WHEN 3 THEN 'EFGHI'
END)
WHERE id IN(1, 2 ,3);
I have 2 arrays and I want to check those arrays with 2 value matches,
if those 2 value not matches I want to insert into database.
Code I have tried :
$data1 = {['reg_no'=>123,'name'=>'John'],['reg_no'=>1234,'name'=>'Lisa']};
$data2 = {['reg_no'=>123,'name'=>'John'],['reg_no'=>1234,'name'=>'Lisa'],['reg_no'=>12345,'name'=>'Roger']};
foreach($data1 as $d1)
foreach($data2 as $d2)
if($d1['reg_no'] != $d2['reg_no'] && $d1['name'] != $d2['name'])
//insert into database
// this not work because it will enter all data that not match
endif
endforeach
endforeach
you can use FirstOrNew Or FirstOrCreate in laravel.
like insert if not exist
$students = User::firstOrNew(['student_id' => $request->student_id, 'course_code' => $request->course_code]);
$students->foo = $request->foo;
$students->save();
$data1 = {['reg_no'=>123,'name'=>'John'],['reg_no'=>1234,'name'=>'Lisa']};
$data2 = {['reg_no'=>123,'name'=>'John'],['reg_no'=>1234,'name'=>'Lisa'],['reg_no'=>12345,'name'=>'Roger']};
$data = array_uintersect($data1, $data2, "strcasecmp");
if($data['reg_no'] != $data1['reg_no'] && $data2['reg_no']) {
// insert
}
I have 2 tables guest_info and guest_profile.two columns are there g_uid and company_id.Based on company_id(I have companyID), i have to take all g_uid.
In guest_info table,
g_uid | companyID
1 5
2 5
3 6
In guest_profile table,display all values from this table(only need to display first two datas)
g_uid | fname
1 xyz
2 fds
3 fsdf
Go to folder "Models" That´s where you´ll do all your CRUD operations to the database.
For example, you can create a model file called "guest_profile_model.php"
Now you open that file and paste the code bellow:
<?php
class guest_profile_model extends CI_Model {
public function select($company_id) {
$this->db->query("select * from `guest_info` INNER JOIN `guest_profile` ON guest_info.g_uid = guest_profile.g_uid WHERE guest_info.company_id = ".$company_id." LIMIT 2");
$result = $this->db->query($query);
return $result->result_object();
}
}
That´s it, now from within your controller you just need to load and call it.
Example:
$this-> load-> model('guest_profile_model ');
$company_id = 1;
$queryResult = $this -> guest_profile_model ->select(company_id);
print_r($queryResult);
Notice that the query return is going to be an object, that is because of the "result_object" in the model, you can change that to be an array if you want to.
//Try this sql query to join 2 table in codeigniter
$company_id = 5;
$this->db->query("select * from `guest_info` INNER JOIN `guest_profile` ON guest_info.g_uid = guest_profile.g_uid WHERE guest_info.company_id = ".$company_id." LIMIT 2");
$this->db->select('*');
$this->db->from('Table1 AS a');
$this->db->join('Table2 AS b', 'a.id = c.id', 'LEFT');
$this->db->join('Table3 AS c', 'a.name = c.name', 'LEFT');
$result = $this->db->get();
hopefully you get my example.
More info : https://www.codeigniter.com/userguide3/database/query_builder.html?highlight=joins#selecting-data
I am trying to get a random row from the top 30 records in a table. I sort all the records by score first, and take 30 records in a scope of the eloquent model:
public function scopePopular($query, $d)
{
return $query->where('d', $d)->orderBy('score', 'desc')->take(30);
}
Then in a class:
$cnt = Record::popular($d)->count();
if ($cnt == 0)
return;
$randIndex = rand(0, $cnt-1);
$record = Record::popular($d)->skip($randIndex)->take(1)->first();
return $record;
But when I check in php artisan tinker, I found that Record::popular($d)->count(); will return all the records number instead of 30. How can I correct this problem? Thanks.
Use get() before count() to run the query before count:
$cnt = Record::popular($d)->get()->count();
You are running the query 2 times. That is not necessary.
$cnt = Record::popular($d)->count(); // First query
if ($cnt == 0)
return;
$randIndex = rand(0, $cnt-1);
$record = Record::popular($d)->skip($randIndex)->take(1)->first(); // Second query
return $record;
Instead you can do it like this:
return Record::popular($d)->get()->random(); // One query only
I have this table:
Friends
id | friendid
10 | 15
12 | 10
10 | 13
and i want to put all values (either from id or friendid columns) in one variable. is it posible?
i have this code:
$id = 10;
$id = DB::table('friends')->where('id', $x)->orWhere('friendid', $x)->lists('friendid');
but this line of code only returns values from 'friendid' column and what i want is to store values from 'friendid' and 'id' columns.
You can pass a second argument to lists, which will give set the keys of the resulting array:
$query = DB::table('friends')->where('id', $x)->orWhere('friendid', $x);
$results = $query->lists('friendid', 'id);
If you want it all as values of a single array, use this:
$query = DB::table('friends')->where('id', $x)->orWhere('friendid', $x);
$ids = [];
foreach ($query->select('id', 'friendid')->get() as $record) {
$ids[] = $record->id;
$ids[] = $record->friendid;
}