MySQL - Return associative array by query - php

I need to know if there is a chance to get an PHP5 array from a MySQL PDO Query like this:
Array = (
keywordID = 1321,
keyword = "Its a test",
position = Array(
today = 12,
month = 17
)
)
Now i have this MySQL Query:
$sql = "SELECT
keywords.id AS keywordID,
keywords.keyword,
statistic.position
FROM
keywords
LEFT JOIN statistic ON (statistic.kid = keywords.id)
WHERE
keywords.uid = ? AND statistic.date IN (?, ?)";
$stmt = WPStatsDB::getInstance()->prepare($sql);
$stmt->execute(array($array['userID'], date("d.m.Y", time()), date("d.m.Y", strtotime('-30 days'))));
$result = $stmt->fetchAll();
This is the current result of var_dump($result):
This is one of the results. I try to write it in my post.
array(244) {
...
[1]=>
array(6) {
["keywordID"]=>
string(4) "1978"
[0]=>
string(4) "1978"
["keyword"]=>
string(20) "Weiterbildung in NRW"
[1]=>
string(20) "Weiterbildung in NRW"
["position"]=>
string(2) "38"
[2]=>
string(2) "38"
}
...
}
EDIT 1:
I need the attribute position as array with two values not as int with only one value. I need position as array with the two attributes for less database queries.
Today and Month are values with information of position of today and the position from the day a month ago of today.
EDIT 2:
Sorry, i've forgot to say that i can't edit this table. The table statistics contains the stats of every day of every keyword connected to every domain. It's very big.
I really don't know how i can solve this.
Thanks for help!! :-)

It's arguable what's faster, in a lot of cases is faster to do separated queries for the relationship.
You either
1) Get a row for each position and deal with it after you get the result
2) Go on a loop for each keyword and get the positions on a separate query for each keyword
3) You do a group by keyword id in MySQL and retrieve the positions with something like group_concat. You can then parse that afterwards. This may seem faster but probably depends on your dataset and may not be as good as you'd expect it to be.

Yes, you can. Use any ORM, list of examples

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.

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.

Inserting an array into the database

I have am creating a check function that enables me to check that data with the specific id and categoryid is already present in the database:
$fields['Occupation'] = array(3) { [0]=> string(1) "1" [1]=> string(1) "6" [2]=> string(1) "7" }
Line in question:
$occCheck = Jojo::selectQuery("SELECT * FROM {refocus_candidate_category} WHERE canid=? AND categoryid=?", array($emailCheck['id'], $fields['Occupation']));
Why am I getting this Error and how do I resolve:
Unknown column 'Array' in 'where clause'
Full Check Function:
if($occCheck != FALSE)
{
Jojo::updateQuery("UPDATE {refocus_candidate_category} SET canid=?, categoryid=? WHERE canid=? AND categoryid=?", array($emailCheck['id'], $fields['Occupation']));
}else{
Jojo::insertQuery("INSERT INTO {refocus_candidate_category} SET canid=?, categoryid=? WHERE canid=? AND categoryid=?", array($emailCheck['id'], $fields['Occupation']));
}
It looks $fields['Occupation'] is an array and it's going to be replaced by categoryid=>?< category ID. What about doing it step-by-step for each category make a question to the database?
OR
$occCheck = Jojo::selectQuery("SELECT * FROM {refocus_candidate_category}
WHERE canid=".$emailCheck['id']."
AND categoryid in
(".implode(",",$fields['Occupation']).")");
if $emailCheck['id'] is not an array
It's not exactly clear what you are trying to do in your queries, as you are writing these strange values SET canid=?.
But the problem you are facing is, that you are concatinating entire array in your SQL query string. try to echo an array then you will see it getting printed as Array. That's the source of your problem query gets expanded like someField=Array. Now that Array is not even in single quotes, so mysql is assuming it to be a column. Thus your error.
Remove that array($emailCheck['id'], $fields['Occupation']). And just set $emailCheck['id'], $fields['Occupation'][0]. your field['Occupation'] is and entire array so choose some as per your need.
Is there a specific reason you're passing an Array to the ...Query( functions rather than separate arguments? PHP is passing the one parameter through to the database - which interprets it as a string - so your query is actually searching for the word "Array" instead.
Try this instead:
$occCheck = Jojo::selectQuery("SELECT * FROM {refocus_candidate_category}".
" WHERE canid=? AND categoryid=?",
$emailCheck['id'], $fields['Occupation']);
You have to make up your mind what Occupation you want to query for:
$occCheck = Jojo::selectQuery("
SELECT * FROM {refocus_candidate_category} WHERE canid=? AND categoryid=?",
array($emailCheck['id'], $fields['Occupation'][1]));
In this case i used occupation with index 1, and that will result in occupation 6 selected.

mysql query looped with results stored in an array

I have a shipping module I'm working to wrap up and am trying to query a mysql table, count the number of rows for a given line item on a PO, and store that result in an array. I don't think I can do group by within mysql as it will not provide a result for a line item that hasn't had any shipments against it. The intent is to take the original order quantity, count the number of units shipped against that via my query, and then subtract the units shipped from the original amount providing the remaining units to be shipped against that line item.
To ensure I receive even the zero qty for line items without shipments and to store that in the array I am trying to loop my query and store each single result as a value within my array. I'm open to suggestions on changing the approach if there is a better way.
Here is what I have for my query:
// I have a previous query that provides the number of line items for a given po. that number is stored in variable $num1
$a=1;
$LiShipped = array();
while($a<$num1){
$query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
$LiShipped[] = mysql_fetch_array($query2);
$a++;
}
Unfortunately when I go to iterate through my array it appears as though nothing is stored in the array.
<?php
echo $LiShipped[0]; //results nothing
echo var_dump($LiShipped); // results array(1) { [0]=> NULL } array(2) { [0]=> NULL [1]=> NULL } array(3) { [0]=> NULL [1]=> NULL [2]=> NULL }
?>
Looks like all null values.
You need to execute the query (by calling mysql_query()) before you try and attempt to retrieve the result:
$query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
$query2 = mysql_query( $query_2); // <-- NEED THIS
$LiShipped[] = mysql_fetch_array( $query2);
Note the above omits basic error checking and sanitation of the SQL query to prevent SQL injection.
You are not executing your query, it can't work. Try this code:
// I have a previous query that provides the number of line items for a given po. that number is stored in variable $num1
$a=1;
$LiShipped = array();
while($a<$num1){
$query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
$res = mysql_query($query2);
while($LiShipped[] = mysql_fetch_array($res));
$a++;
}

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