Insert Multidimensional array into Mysql Table - mysql

I have a multidimensional array like this:
TAB = Array (
[field1] => Array ( [0] => 111 [1] => 777 [2] => 222 ... )
[field2] => Array ( [0] => MAT [1] => MAT [2] => MAT ... )
[field3] => Array ( [0] => 8A [1] => 8B [2] => 8C ... )
)
I want INSERT the values of this Array to the mysql temporary TABLE1, with PDO.
How can I to do?
Thanks.

ASSUMING PHP and ASSUMING you have a TABLE1 which has two location columns and one value column (one column for the location in the first array, the second for the location in the second array and the value column for the actual value).
$dbh is your database handler.
$keys = array_keys($TAB); // because the array is associative, we need array_keys
for ($i = 0; $i < $TAB.length; $i++){
for ($j = 0; $j < $TAB[keys[$i]].length; $j++){
$stmt = $dbh->prepare("INSERT INTO TABLE1 (location1, location2, value) VALUES (:location1, :location2, :value )");
$stmt->bindParam(':location1', $i);
$stmt->bindParam(':location2', $j);
$stmt->bindParam(':value', $TAB[$keys[$i]][$j]);
$stmt->execute();
}
}

Related

Cakephp Table query: SUM returning 0

I'm having problems when using find to sum the field num_days from table events.
$events = TableRegistry::get('Events');
$query = $events->find('all')
->select(['used' => 'sum(num_days)'])
->first();
Why $query->used is always 0?
print_r($events->find('all')->select(['used' => 'sum(num_days)'])->toArray()) gives,
Array ( [0] => App\Model\Entity\Event Object ( [used] => 6 [[new]] => [[accessible]] => Array ( [*] => 1 ) [[dirty]] => Array ( ) [[original]] => Array ( ) [[virtual]] => Array ( ) [[errors]] => Array ( ) [[invalid]] => Array ( ) [[repository]] => Events ) )
6 is exactly the correct answer for the query and print_r shows it but $query->used is returning always 0.
try $query->order(['used' => 'DESC']); before $query->used
Also, we can add used as protected $_virtual = ['used']; inside Event.php Entity File

Merge multiple array to single array

I have this piece of code from which i wish to get a single array that contains all value.
$sql = "SELECT * FROM interest where interest='".$interest."' and userid!='".$myuserid."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$userid = $row["userid"];
if($searchtype == 'both')
{
$sql2 = "SELECT * FROM register where id='".$userid."' and discover = 'on' and id!='".$myuserid."'";
$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2) > 0)
{
while($row2 = mysqli_fetch_assoc($result2))
{
echo "<pre>";
print_r($row2);
echo "</pre>";
}
}
}
}
}
The o/p that i am getting is something like this
Array
(
[id] => 1
[email] => A1
[username] =>B1
[password] => C1
[gender] => C1
)
Array
(
[id] => 2
[email] => A2
[username] => B2
[password] => C2
[gender] => D2
)
Array
(
[id] => 3
[email] => A3
[username] => B3
[password] => C3
[gender] => D3
)
But i wish to get this all data in a single array like this
Array
(
[0] => Array
(
[id] => 1
[email] => A1
[username] =>B1
[password] => C1
[gender] => C1
)
[1] => Array
(
[id] => 2
[email] => A2
[username] => B2
[password] => C2
[gender] => D2
)
[2] => Array
(
[id] => 3
[email] => A3
[username] => B3
[password] => C3
[gender] => D3
)
}
can anyone tell how i can do so
Create an array variable like $a=array(); at the start of your code
Get row value in array $a[]=your row value(while loop), then print this outside loop you will get all value in single array print like
print_r($a);
Take one array variable before while loop started like $user_data = array(); and in inner loop you have to set $user_data[] = $row2;
if (mysqli_num_rows($result) > 0) {
$user_data = array();
while($row = mysqli_fetch_assoc($result)) {
$userid = $row["userid"];
if($searchtype == 'both') {
$sql2 = "SELECT * FROM register where id='".$userid."' and discover = 'on' and id!='".$myuserid."'";
$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2) > 0) {
while($row2 = mysqli_fetch_assoc($result2)) {
$user_data[] = $row2;
}
}
}
}
print_r($user_data); //Print here your user_data outside the loop.
}
You are almost near to your goal, you just need to define one array and save each row's data in it
// array which contains all rows data
$all_rows = array(); // <------ step 1
if(mysqli_num_rows($result2))
{
while($row2 = mysqli_fetch_assoc($result2))
{
// every record data is stored here
$all_rows[] = $row2; // <------ step 2
}
}
if(!empty($all_rows))
{
print_r($all_rows);
}else
{
echo "do some thing else since zero records fetched";
}

How to return mysql data using table aliases with left join and duplicate columns

I am trying to do a simple left join, while using table aliases, to return all of the values from both tables in this format:
[Alias1] => Array
(
[id] => 1
[city] => bay area
[state] => CA
)
[Alias2] => Array
(
[id] => 1
[city] => san francisco
[baseball_team] => giants
)
Here is my very simple mysqli_query:
$result = mysqli_query($sql, SELECT Alias1.id, Alias1.city, Alias1.state, Alias2.id, Alias2.city, Alias2.baseball_team FROM database.table1 AS Alias1 LEFT JOIN database.table2 AS Alias2 ON Alias1.id = Alias2.id)
To get the results... I use:
while($row = mysqli_fetch_array($result))
{
$data[] = $row;
}
print_r($data);die();
Problem: The data prints out as such:
[0] => Array
(
[0] => 1
[id] => 1
[1] => bay area
[city] => bay area
[2] => CA
[state] => CA
[3] => 1
[4] => san francisco
[5] => giants
[baseball_team] => giants
)
Other Info: I originally tried to get the data using mysql_fetch_assoc($result)... But the duplicate columns don't return at all.
Instead of:
$data[] = $row;
Use this to form the data array that you desire:
$data['Alias1'] = array(
"id"=>$row['id'],
"city"=>$row['1_city'],
"state"=>$row['state'],
);
$data['Alias2'] = array(
"id"=>$row['id'],
"city"=>$row['2_city'],
"baseball_team"=>$row['baseball_team'],
);
OR, if you expect more than one row you need to use something like:
$data[] = array(
"Alias1" => array(
"id"=>$row['id'],
"city"=>$row['1_city'],
"state"=>$row['state'],
),
"Alias2" => array(
"id"=>$row['id'],
"city"=>$row['2_city'],
"baseball_team"=>$row['baseball_team'],
),
);
Note:
If your city values are different between your two tables then you should use an alias so that you can pull the other one differently. If they are the same, I suggest you not have them listed twice in the database as this is duplicating data and leaves your database denormalized.
Edit:
Your query should be something like
SELECT Alias1.id, Alias1.city AS 1_city, Alias1.state, Alias2.id, Alias2.city AS 2_city, Alias2.baseball_team FROM database.table1 AS Alias1 LEFT JOIN database.table2 AS Alias2 ON Alias1.id = Alias2.id
See edited answers above for these aliases.

Create multi dimensional array in cakephp

Now I have 3 row of data.
id name date
1 data1 12-06-2013
2 data2 12-06-2013
3 data3 16-06-2013
now I want to group the 3 rows of data into a new array, something like:
Array
(
[2013-06-12] => Array
(
[0] => data1
[1] => data2
)
[2013-06-16] => Array
(
[0] => data3
)
)
the question is 1st i using foreach to show all date out.
<?php foreach($datax as $data):
echo $data['Model_Name']['id'];
endforeach;?>
then, while i looping i want to group up the $data sort to date as the multidimensional array as above.
Try below method,. you can add an additional column for date
$a = array(
array('datax' => array('id' => 1, 'name' => 'data1')),
array('datax' => array('id' => 2, 'name' => 'data2')),
array('datax' => array('id' => 3, 'name' => 'data3'))
);
$result = Set::classicExtract($a, '{n}.datax.id');
/* $result now looks like:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
*/
$result = Set::classicExtract($a, '{n}.datax.name');
/* $result now looks like:
Array
(
[0] => data1
[1] => data2
[2] => data3
)
*/

DB Query in Drupal 7

I am trying to run a db query in drupal where, the content type has a node association field, and I am trying to get all notes of that type, where the NID of the current node matches any of the nodes specified in said note association field.
a visual example
Nodetype1
-- Node Association Field
NodeType2
I would like to get all Nodetype1's where Node Association Field matches the NID of Nodetype2 that is currently loaded.
My current db query is like so:
db_query("SELECT * FROM field_data_field_promo_profile WHERE field_promo_profile_nid=".$N->nid);
and this returns nothing, when i know for a fact that such a node exists, I also tried dropping the WHERE statement and it returns an array like this:
DatabaseStatementBase Object ( [dbh] => DatabaseConnection_mysql Object ( [shutdownRegistered:protected] => [target:protected] => default [key:protected] => default [logger:protected] => [transactionLayers:protected] => Array ( ) [driverClasses:protected] => Array ( [SelectQuery] => SelectQuery [DatabaseSchema] => DatabaseSchema_mysql [MergeQuery] => MergeQuery [DatabaseTransaction] => DatabaseTransaction [UpdateQuery] => UpdateQuery [InsertQuery] => InsertQuery_mysql ) [statementClass:protected] => DatabaseStatementBase [transactionSupport:protected] => 1 [transactionalDDLSupport:protected] => [temporaryNameIndex:protected] => 0 [connectionOptions:protected] => Array ( [database] => cityhound_dev [username] => blahblah [password] => blahblah [host] => localhost [port] => [driver] => mysql [prefix] => Array ( [default] => ) ) [schema:protected] => DatabaseSchema_mysql Object ( [connection:protected] => DatabaseConnection_mysql Object *RECURSION* [placeholder:protected] => 0 [defaultSchema:protected] => public [uniqueIdentifier:protected] => 4fd7fba9e563e2.50177866 ) [prefixes:protected] => Array ( [default] => ) [prefixSearch:protected] => Array ( [0] => { [1] => } ) [prefixReplace:protected] => Array ( [0] => [1] => ) ) [queryString] => SELECT * FROM field_data_field_promo_profile )
Any one have some ideas ?
db_query() returns an iterable object, so you just need to iterate over it:
$result = db_query("SELECT * FROM field_data_field_promo_profile WHERE field_promo_profile_nid=".$N->nid);
foreach ($result as $row) {
$entity_id = $row->entity_id;
// etc...
}
You should use parameters in your queries to prevent SQL injections.
For instance the query above should look like this:
$result = db_query("SELECT * FROM {field_data_field_promo_profile} p
WHERE p.field_promo_profile_nid = :nid ", array(':nid' => $N->nid);
foreach ( $result as $row ) {
$entity_id = $row->entity_id;
// etc...
}