PHP get MySQL database as associative array by row - php

I have a simple mySQL database table that I am loading into a PHP array. I would like the id column of the mySQL table (which is auto incremented, but I don't think that's relevant) to be the array key for each element of the PHP array, instead of the array being numeric.
Instead of this:
Array(
Array(id=>'1', field1=>someval, field2=>val),
Array(id=>'2', field1=>val, field2=>otherval),
Array(id=>'4', field1=>val, field2=>otherval)
)
I want this:
Array(
1=>Array(field1=>someval, field2=>val),
2=>Array(field1=>val, field2=>otherval),
4=>Array(field1=>val, field2=>otherval)
)
I don't care if id is left in the associative array for each row.
Is there a way to do this without looping through the original mySQL array and using up lots of processing time?

You can do it at the fetch time like this:
$query_ret = mysql_query(...);
$result = array();
while ($row = mysql_fetch_assoc($query_ret)) {
$result[array_shift($row)] = $row;
}

"Is there a way to do this without looping through the original mySQL array and using up lots of processing time?"
I believe the answer to this is no. The best you can do is to try to be as efficient as possible when looping through the array.

If you have PDO, you should definitely see Example #3 from the PDO documentation for fetchall: http://www.php.net/manual/en/pdostatement.fetchall.php#example-1022
Not only is this way more efficient use of your server's memory and processing power... it would also enable you to take advantage of several of PDO's other powerful APIs.

Related

Creating an array by looping through a mySQL database, capturing entries only once in PHP

i'm relatively new to coding and I need a little help. I'm basically trying to loop through an entry in a mySQL database and push any new entry into an array , so that it only comes up once in my array.
// SQL query
$response = $bdd->query('SELECT serie_bd FROM inventaire_bd');
//creating array to group all elements from the db so that they do not repeat
$serie_bd_groupe=array();
while($data_collected = $response->fetch())
{
if(array_key_exists($data_collected,$serie_bd_groupe)==false)
{
array_push($data_collected,$serie_bd_groupe);
}
}
Will this work? - it seems like the loop will just stay stuck after it comes accross an entry a second time because the if statement wont execute itself.
Also in the future, are their any php equivalent to jsfiddle.net so i can test code syntaxically?
Thank you for your time
Your array keys will be default integers, so you don't want to check those. Instead of this:
if(array_key_exists($data_collected,$serie_bd_groupe)==false)
you should do this:
if(!(in_array($data_collected,$serie_bd_groupe)))
http://php.net/manual/en/function.in-array.php
On the other hand, if you're expecting your collected data to be the array key rather than value, you'd do something like this, instead of your array_push:
$serie_bd_groupe[$data_collected] = 1;
then your key check would work.
If you are looking for UNIQUE values (serie_bd) from your database, update your query to include "DISTINCT" like this:
$bdd->query('SELECT DISTINCT serie_bd FROM inventaire_bd');
On the other hand, I think you are looking for http://phpfiddle.org/

Trouble retrieving data using PDO syntax, PHP

I'm brand new to the PDO syntax and I'm liking the learning curve! I'm refactoring code - migrating over from archaic mysqli_* methods.
Predictably, I've run into some snags, being a novice. One of the big ones is (forgive if this is a dumb question) retrieving data from the DB and echoing it out on the page. Here is what I have so far:
$getURLid = $_GET['id'];
$idQuery = $connection->prepare("SELECT * FROM pages WHERE page_id = :getURLid");
$idQuery->execute(array(':getURLid' => $getURLid));
$idRetrieved = $idQuery->fetchAll(); // This is the part I'm unclear on.
When I echo $idRetrieved['value'] to the page, nothing shows up. I'm missing something or misunderstanding how it works. Maybe fetchAll isn't what I should be using.
If it is, is a loop necessary to retrieve all rows? I was under the impression that fetchAll would loop through them automatically based on what I've read.
Thanks for the help.
Read the doco for PDOStatement::fetchAll closely. It returns an array of row data.
The type of data representing each row depends on your fetch mode which by default is PDO::FETCH_BOTH. This would mean each row is an array with both numeric and associative keys. If you're only going to access the data associatively, I'd recommend using PDO::FETCH_ASSOC, eg
$idRetrieved = $idQuery->fetchAll(PDO::FETCH_ASSOC);
You would then either need to loop or access each row via its index, eg
foreach ($idRetrieved as $row) {
echo $row['value'];
}
// or
echo $idRetrieved[0]['value']; // assuming there's at least one row.

fetch a single postgres record as an associative array without using while loop

If I have a statement that I know will return only one result:
$emp_query = "SELECT * FROM table WHERE id = 'employee_id' LIMIT 1"
Is there any way I can access the result of pg_query($con, $csr_query); as an associative array without using a pg_fetch_assoc and a while loop? A while loop seems unnecessary when I know I'm retrieving only one record. Maybe there is some way in PDO as well, I'm just setting it up this way first because I'm more comfortable with the simple way. Thanks.
Something like pg_fetch_result:
http://www.php.net/manual/en/function.pg-fetch-result.php

Echoing the sum of a table in PHP

I have 2 columns in a table called Points. The 2 columns are UserPoints and UserID.
I want to be able to echo the total amount of points a user has.
I've got something like this but I dont think its right.
$getTotalPoints = mysql_query("SELECT SUM(UserPoints) FROM `Points` WHERE `UserID` = '1'") or die(mysql_error());
$totalPoints = mysql_fetch_array($getTotalPoints);
When i echo the above statement by echoing "$totalPoints" i get "Array".
Anyone know the correct query to do this ?
You're getting Array because that's what's stored in $totalPoints. Look closely at your code and you'll see you used the mysql_fetch_array() function, which retrieves a row of results from the results set as an array. If you do var_dump() on $totalPoints you'll see the following:
Array
(
[0] => 12345
[SUM(UserPoints)] => 12345
)
The sum you're looking for is at index 0 or the column name, in this case SUM(UserPoints), so you can output it using echo $totalPoints[0] or echo $totalPoints['SUM(UserPoints)'].
Alternatively, you could use the mysql_result() function. I think this is more in-line with the behavior you were expecting. It fetches a single value from the row from the result set. So, instead of mysql_fetch_array() you'd wrote:
$totalPoints = mysql_result($result, 0);
For more information on mysql_result(), check out the PHP documentation for it.
As an aside, I would recommend not using mysql_* functions if you have the option. A newer interface like PDO, or at least mysqli, would be better. This will depend on your project of course... if you're working with a large legacy code base it may be difficult to change. But if you're starting out now, I think you'd benefit from the newer libraries. You can see my opinion and some guidance on transitioning extensions in this article I wrote.
Hope this helped... and good luck!
mysql_fetch_array fetches a result row as an associative array, a numeric array, or both. by default it creates both. all that you need is to echo $totalPoints[0];
or, if you rewrite you request as
$getTotalPoints = mysql_query("SELECT SUM(UserPoints) total FROM `Points`
WHERE `UserID` = '1'") or die(mysql_error());
$totalPoints = mysql_fetch_array($getTotalPoints);
echo $totalPoints['total'];
mysql_fetch_array returns an array. Therefore you need to treat $totalpoints as an array.
try adding this line to the end of your snippet:
echo $totalPoints[0];
There are several ways to retrieve data with the mysql functions I suggest reading about them in the php manual.
Here is mysql_fetch_array
The resultset row is an array with as many elements as you got in the SELECT.
In you case you only got 1 element (the sum).
So you should:
echo $totalPoints[0];
If you need to debug this kind of issues I recommend you to read about print_r function.

How do I organize an array that is an html line containing variables pulled from mysql table?

I am attempting to alphabetically organize an options list populated from an array; the problem is that the array array contains html tags at the front so sorting it seems imposable. I have tried 'ORDER BY' in the mysql query from which the array variables are pulled, but the command gets lost.
The whole system seems hardwired to sort the list by the key column in the mysql table, which is simply not acceptable. Is there any way around this issue? Any help would be VERY appreciated!
Here is an example of what I'm trying to do:
$options = array();
$query1=mysql_query("Select * From table1 Where name='blah'");
while($queryvalue1=mysql_fetch_array($query1)) {
$array1 = $queryvalue1['Column1'];
$query2=mysql_query("Select * From table2 Where id In ($array1) Order by value DESC");
while($queryvalue2=mysql_fetch_array($query2)) {
$var1 = $queryvalue2['Column2'];
$var2 = $queryvalue2['Column3'];
$options[] = "<option value='$var'>$var2</option>"
}
}
$options = implode(PHP_EOL, $options);
There's certainly ways to do it, but they are all much slower than letting the database sort for you.
It might not be the simplest solution, but I'd suggest getting rid of the HTML tags and repopulating the database, even if you have to use a temporary table while you fix the rest of your code. Do it right so you don't have to continually work around a serious problem for the rest of the application lifecycle.

Categories