title says, is there a way to select column name from multiple table?
DB::list_columns('table1'); //returns columns of table1
what I want to do is
DB::list_columns('table1', 'table2');
I want to select all columns of 2 or more tables.
is it possible?
Use DB::list_tables() in foreach read the current table using DB::list_columns($current_table)
If you use PDO_Connection, this is not supported.
Thanks for those who replied, here is what I did
$col1 = DB::list_columns('table1');
foreach ($col1 as $key => $value) {
array_push($columns['col1'], $key);
}
$col2 = DB::list_columns('table2');
foreach ($col2 as $key => $value) {
array_push($columns['col2'], $key);
}
$colnames = array_merge($col1, $col2);
#CBroe thanks for giving me idea!
Related
I have a 2D array , which holds the result of a mysql query. here is my code
$res=$ $this->dbconnection->Query($Query);
$query_result= array();
while($colRow=mysqli_fetch_array($res))
{
$query_result[]= $colRow;
}
Now i want 1D array which contains all rows under a particular column in $query_result.
For example, the database table contains the fields Name and ID,I know , $query_result[]= $colRow['Name'] will give query results into ID. But I need all rows under Name and Id separately , such as $name= $query_result['Name'],$Id= $query_result['ID'].
Is there any easy way to accomplish this?
Since PHP 5.5.0 you can use...
$myfield_arr = array_column($query_result, 'myfield_name');
... to isolate a column from a two dimensional array.
See http://php.net/manual/en/function.array-column.php
Please try maybe
$res=$ $this->dbconnection->Query($Query);
$query_result= array();
while($colRow=mysqli_fetch_array($res))
{
if (empty($query_result))
$query_result = $colRow;
else
{
foreach ($colRow as $key=> $val)
$query_result[$key][] = $val;
}
}
After clarifying question in comments with you, solution is:
while($colRow=mysqli_fetch_array($res)){
foreach ($colRow as $key => $value) {
if(!isset($query_result[$key])) $query_result[$key]=array();
$query_result[$key][] = $value;
}
}
Use something like this:
foreach ($rows as $key => $value) {
$$key = $value;
}
Converting array of rows into array of columns:
<?php
$arr2dm = [['key1' => 'val11', 'key2' => 'val21'], ['key1' => 'val12', 'key2' => 'val22']];
foreach ($arr2dm as $arr) {
foreach ($arr as $k => $v) {
$res[$k][] = $v;
}
}
print_r($res);
http://sandbox.onlinephpfunctions.com/code/514050d07f9ed599e010ccd11e51fc18e39647fa
RESOLVED
I have used the answer from alfasin, but as that gave me WAY too much information, i wrote a little script to just get the field names. As the field names apeared first, it was rather simple:
$here = array();
$SQL = "SHOW COLUMNS FROM User";
foreach($conn->query($SQL) as $row) {
$here[] = $row[0];
}
echo '<pre>';print_r($here);echo '<pre>';
This left me with the new array $here containing the column names, hope this helps someone in the future :)
Original question:
Let me clarify a bit, I have a mysql table and I'm trying to select * from it, and display the result in an html list <ol>. I can manage to grab the row data JUST FINE, but I cannot for the life of me figure out how to grab the table column names, in order to match them up with the row, respectively. this is my code that is grabbing the row data:
//get those results
$sql = "SELECT DISTINCT *
FROM User
WHERE Owner = '".$owner."'";
foreach($conn->query($sql) as $row) {
//split array in half
$hax = count($row);
$halfHax = $hax / 2;
//set up a for loop to give results
$u = 1;
for($i = 2; $i <= $halfHax; $i++){
echo $row[$u].'<br>';
$u++;
}
}
this is giving me all the result where Owner == $owner just like it should, but I would like the column names to list with those, I could hard-code it out, but more columns may be added/changed so I would rather not. Any ideas?
Try:
SHOW COLUMNS FROM mytable
http://dev.mysql.com/doc/refman/5.0/en/show-columns.html
Fetch rows as associative arrays in order to keep your column names as array keys.
Here's my suggestion:
$sql = "SELECT DISTINCT * FROM User WHERE Owner = :owner";
$sth = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':owner' => $owner);
while($row=$sth->fetch(PDO::fetch_assoc) as $row) {
//split array in half
$hax = count($row);
$halfHax = $hax / 2;
//set up a for loop to give results
foreach ($row as $key => $value) {
echo $key.'='.$value.'<br />';
}
}
To just list the column names:
array_keys($row);
Please refer to SHOW COLUMNS at the MySQL Reference if you want more information about the columns.
But I'd suggest using mysqli_fetch_assoc and then using foreach (array_expression as $key => $value) to get the column name and it's value, for each row.
I am imploding data inside of an array, called the following:
["Levels_SanctionLevel_array"]=>
string(14) "IR01,IR02,IR03"
I need to explode this data and input each value as a row inside of mysql. Such as
pri_id value
---------------
01 IR01
02 IR02
03 IR04
Now where I am getting stuck is this:
The array listed above could have 1 value, 3 values (right now I am showing three values) or 5 values, and I dont want to input NULL values inside of my database.
Appreciate any guidance anyone can share...
$data = explode(',',$your_string);
foreach ($data AS $value) {
// INSERT INTO DB
}
A simple loop works correctly, but has the drawback of making multiple queries to the database:
$str = "IR01,IR02,IR03";
$vals = explode(',', $str);
foreach ($vals AS $value) {
// insert into database
}
As DB operations are a more significant bottleneck than building a query in PHP, I would opt to generate the SQL code for a single query as follows:
$str = "IR01,IR02,IR03";
$vals = explode(',', $str);
$query = 'INSERT INTO my_data VALUES ';
foreach ($vals as $value) {
$query .= "('', '".$value."'),";
}
$query = rtrim($query, ',');
// insert into database
Why don't you use an iterator over the array to construct the sql query? That way you will only insert as many elements as you have in the array.
Like the answer above. I think we were answering at the same time.
Supposing your major array is $data:
foreach ($data as $values)
{
$value = explode(",", $values);
foreach ($value as $v)
{
$sql = "INSERT INTO table(value) VALUES('$v')";
}
}
what is the optimal way for me to insert and array of 1000 lines and 10 columns each into a mysql table below is how i display it so it would be a similar construct but i need some directions
foreach ($stack as $val) {
print "<tr>\n";
foreach ($val as $no) {
print " <td>$no</td>\n";}
print "</tr>\n";
}
You can insert multiple rows with a single insert as follows :
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
look at implode() to create the values string from your array
Better way to insert thousands of data into DB is to use implode function implode
i'm guessing u got something like this
$stack = array("man1" => array("name"=>"ik", "class"=>"highskl", "age"=> "12"),"man1" => array("name"=>"ijk", "class"=>"higkl", "age"=> "13"));
and you want to insert them into a table, try and use the table fields as index for the inner arrays then adjust the code to look like this
foreach ($stack as $entry => $value) {
$query = "INSERT INTO table set ";
foreach ($value as $key => $val) {
$query .= $key ."= ".$val.",";}
//use a string function to remove the last comma
$result = mysql_query($query) or die("Error in Query ".$entry." ",mysql_error());
//this helps to track error..
}
Say i am having set of rows in a table and each row is having a column called city with some values assigned to it
iam iterating through the result set and i need to assign the list of city values of each row in to an array only unique
foreach($res as $row){
$cities =array();
$cities[] = $row['city'];
//when i say
var_dump($cities);
//Iam not able to get array .how do i do that
$maincities = array('A','B',C)
}
You're resetting $cities to a new array for each row you loop through. Better would be:
$cities = array();
foreach ($res as $row)
{
if ( ! in_array($row['city'], $cities)) {
$cities[] = $row['city'];
}
}
You should but $cities =array();before the foreach loop. Now you are erasing the array at each iteration.
Regards,
Alin
You empty the $cities variable every time in the loop.
It is probably a lot better practise to only have unique cities in your resultset (SELECT DISTINCT city FROM ...)
For example:
$cities =array();
foreach($res as $row){
$cities[] = $row['city'];
}
var_dump($cities);
However it depends on the content of $res
Using keys to eliminate duplicates:
$cities = array();
foreach($res as $row)
$cities[$row['city']] = true;
$cities = array_keys($cities);