PDO Insert values from subarrays - php

array(2) {
[0]=>
array(1) {
["url_id"]=>
string(2) "45"
}
[1]=>
array(1) {
["h"]=>
string(1) "3"
}
}
echo $column_list = join(',', $items);
...
This PDO Insert Array Using Key As Column Name helps me inserting array values in MySQL table easily. But now I do have an array containing subarrays and it looks like this join(',', $items); does not work. Guess you think "of course it doesn't work" right now, but how can I store the keys and the values into a variable to use $sql = "INSERT INTO applications ($column_list) VALUES ($param_list)"; successfully.
I have tried array_merge but that did not work at all. I would like to show some code examples, but I have no idea what to try and how to achieve that.
Thanks for your help! I appreciate it!

Related

MySQL Query, get a column value by a list of rowid's, including duplicate results in result

//List of id's I want displayname for
$IDListSQL = '10,10,10,11,10,10';
//My query statement
$q = "SELECT displayname FROM accounts WHERE id IN($IDListSQL)";
//Executes query
$Res = $DB->Query($q);
//Gets all results
$Rows = $Res->fetch_all();
echo var_dump($Rows);
//Output
#->array(2)
{
[0]=> array(1)
{
[0]=> string(14) "Apple"
}
[1]=> array(1)
{
[0]=> string(10) "Orange"
}
}
The behaviour I want is an array with all the displayname's in the $IDListSQL, even if its the same ID. I also want them in the order I specified. Trying to figure this out in 1 query rather than doing up to 16 separate select queries for the purpose this is for. Any help would be appreciated kindly.
I ended up getting this done with PHP since I already had an array of ID's in the specified order. Used my same query to only get one of each ID, then joined the data into my array with the help of a couple for loops. Appreciate the help, Ctznkane525 I think what you posted would work. It sounds like it is doing the same thing I done up in PHP, trying not to use complex queries unless absolutely necessary. Speed and high ccu is critical for this app.

Doctrine QueryBuilder not returning all rows for JOIN and WHERE IN query

I'm writing a Shopware plugin, and I have the following code to build an SQL query:
$queryBuilder = $this->container->get('dbal_connection')->createQueryBuilder();
$queryBuilder->select('a.articleID', 'v.optionID', 'v.value')
->from('s_filter_articles', 'a')
->leftJoin('a', 's_filter_values', 'v', 'a.valueID = v.id')
->where('a.articleID IN (:ids)')
->andWhere('v.optionID IN (3, 8)')
->orderBy('a.articleID, v.optionID')
->setParameter(':ids', $relatedIds);
The built SQL string is the following, according to $queryBuilder->getSql():
SELECT a.articleID, v.optionID, v.value
FROM s_filter_articles a LEFT JOIN s_filter_values v ON a.valueID = v.id
WHERE (a.articleID IN (:ids)) AND (v.optionID IN (3, 8))
ORDER BY a.articleID, v.optionID ASC
When I replace ":ids" with "1,2,3,4,5" and execute the query, all rows get returned as expected. (I made sure that $relatedIds is "1,2,3,4,5", too.)
When I execute the query in PHP (via $queryBuilder->execute()->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC)), only results for the first ID (1) are returned. var_dump($result)shows the following:
array(1) { [1]=> array(2) { [0]=> array(2) { ["optionID"]=> string(1) "3" ["value"]=> string(13) "Schwarz Kombi" } [1]=> array(2) { ["optionID"]=> string(1) "8" ["value"]=> string(7) "Schwarz" } } }
Why is this not returning results for other IDs (2,3,4,5)?
I think you need a real array in
->setParameter(':ids', $relatedIds);
for example
$relatedIds = [1,2,3,4,5]
The problem was that $relatedIds is a string, so setParameter(':ids', $relatedIds) inserted it with quotes
WHERE a.articleID IN ('1,2,3,4,5')
instead of
WHERE a.articleID IN (1,2,3,4,5)
I need to pass an array instead of a string to achieve what I want.
Additionally, it is necessary to pass a type to setParameter:
setParameter(':ids', $relatedIds, \Doctrine\DBAL\Connection::PARAM_INT_ARRAY);

MySQL and PHP Duplicate Printing

I am very new to PHP and MySQL and am trying to get data from a MySQL table and print it. I make a call to the database and it works great. I am able to read info. out. but there are duplicates in the data.
So far I have:
<?php
/// Make a MySQL Connection
mysql_connect("localhost", "loop", "XXX") or die(mysql_error());
mysql_select_db("loop") or die(mysql_error());
// Retrieve all the data from the "profile" table
$result = mysql_query("SELECT * FROM profile")
or die(mysql_error());
//print out info.
while ($row = mysql_fetch_array($result)) {
echo("<pre>");
var_dump($row);
echo("</pre>");
}
?>
This produces:
array(1) {
[0]=>
array(14) {
[0]=>
string(1) "1"
["id"]=>
string(1) "1"
[1]=>
string(13) "test#test.com"
["email"]=>
string(13) "test#test.com"
[2]=>
string(8) "passcode"
["pass"]=>
string(8) "passcode"
[3]=>
string(4) "John"
["nameFirst"]=>
string(4) "John"
[4]=>
string(5) "Smith"
["nameLast"]=>
string(5) "Smith"
[5]=>
string(8) "face.jpg"
["pic"]=>
string(8) "face.jpg"
[6]=>
string(16) "Some dummy text."
["bio"]=>
string(16) "Some dummy text."
}
}
Why does it have duplicate elements? I checked the database and it is OK. Can someone explain what I am missing?
You can pass a second parameter to mysql_fetch_array function to tell it whether to return an associative array (hashmap - of columns to row values) or a regular array of row elements. By default it will return both.
http://php.net/manual/en/function.mysql-fetch-array.php
There are also dedicated functions to fetch row values as an array and hashmap:
mysql_fetch_row()
mysql_fetch_assoc()
This is because mysql_fetch_array returns both numeric and associative array by default check php manual mysql_fetch_array
Please try to use mysql_fetch_assoc instead of mysql_fetch_array because mysql_fetch_array was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
but if you still want to use this than this will help
try to pass a second parameter mysql_fetch_array($result, MYSQL_ASSOC) or mysql_fetch_array($result, MYSQL_NUM)

Trying to get 1 array of strings from a database column with mysqli

I am trying to get all the values from a column with mysqli.
I have tried
$emaildbs = $db->query("SELECT email from subscribers");
while($emaildbsrow = $emaildbs->fetch_row()) {
$emaildbsrows[] = $emaildbsrow;
}
var_dump($emaildbsrows);
but the var_dump looks like this:
array(2) {
[0]=>
array(1) {
[0]=>
string(6) "asdasd"
}
[1]=>
array(1) {
[0]=>
string(1) "s"
}
}
and the expected output is
array(2) {
[0]=> string(6) "asdasd"
[1]=> string(1) "s"
}
I have also tried:
with fetch_assoc and I get smth similar. I searched on stackoverflow, and tried numerous functions instead of fetch_row but same thing. Where am I mistaking.
You're assigning complete row to $emaildbsrows array so just change it to,
$emaildbs = $db->query("SELECT email from subscribers");
while($emaildbsrow = $emaildbs->fetch_row()) {
$emaildbsrows[] = $emaildbsrow[0];
}
var_dump($emaildbsrows);
Each row is an array itself - but as you are selecting a single column, it is a single index array.
You might want to do the following instead:
$emaildbs = $db->query("SELECT email from subscribers");
while($emaildbsrow = $emaildbs->fetch_row()) {
$emaildbsrows[] = $emaildbsrow[0];
}
var_dump($emaildbsrows);
This will add the single element from the array as a new element in $emaildbsrows. As you are only selecting a single column from the table, this will work nicely. Had you selected more than one column, this wouldn't work.
You should use abstraction libraries instead of raw mysqli, such as PDO
$sql = "SELECT email from subscribers";
$emails = $pdo->query($sql)->fetchAll(PDO::FETCH_COLUMN, 0));
or safeMysql
$emails = $db->getCol("SELECT email from subscribers");
the purpose of an abstraction library is to get rid of all the dirty job, making your code cleaner and more readable. See - everything can be done in one single line, making your code four times shorter. Assuming 20 queries per page in average it can save you 60 lines of code.
However, to tell you truth, I don't believe myself you would follow this suggestion. According to my observations, PHP users rather inclined to writing as much code as possible, producing screens of code out of every trifle operation.

Retrieving a JOIN array from MySql

I'm pulling a joined query from the DB using the following code:
$query = 'SELECT `profiles`.`city`, `users`.`first_name`, `users`.`last_name`'
. ' FROM profiles, users'
. ' WHERE ((`profiles`.`user_id` = 3) AND (`users`.`user_id` = 3))'
. ' LIMIT 1';
$result = $connection -> query($query);
$arr = $result -> fetch_array();
$feedback = $arr;
$result -> close();
return $feedback;
This isn't my final code, this is just preliminary to test my join.
The query seems to work fine, it pulls the single row of information I need but I noticed that when I var_dump it, it's put the array into 2 different indexes, a numerical index and an index of the name of the db field. Here's what the var_dump looks like:
array(6) { [0]=> string(4) "Reno" ["city"]=> string(4) "Reno" [1]=> string(4) "John" ["first_name"]=> string(4) "John" [2]=> string(3) "Doe" ["last_name"]=> string(3) "Doe" }
This is effectively doubling the size of my query result. For a single row this won't be that big of a deal but if/when I begin to use this same method to draw multiple records, doubling the size of the result can be costly.
I've tried to do a foreach loop:
foreach ($arr as $key=>$value) {
$feedback[$key] = $value;
}
but it leaves me with the same result. Am I doing something wrong and if so, how do I correct it or is this normal?
Thanks for you help
The default result type for mysqli_result::fetch_array() is MYSQLI_BOTH meaning you get both named and numeric result array indices (see http://php.net/manual/en/mysqli-result.fetch-array.php).
Try using fetch_assoc() instead.
To reduce the size, you'll want to look at the second optional argument to mysql_fetch_array. This is documented here:
http://www.php.net/manual/en/function.mysql-fetch-array.php
You can specify if you just want numerical-indexes or associative arrays.
If you use fetch row (http://www.php.net/manual/en/mysqli-result.fetch-row.php) you will fetch without the names. I think this is what you are looking for, right?
EDIT: This also apllied to mysql, but the function is mysql_fetch_row($result) instead of mysqli

Categories