Query multiple mysql rows and separate into variables after? - php

I am trying to select multiple rows from the database and then separate the rows into array values so I can use them throughout my code.
This is what I have right now...
$result = mysql_query("SELECT url, image, placement FROM advert
WHERE user='1'") or die(mysql_error());
//This grabs 3 rows with placement name equal to 'sideadtop','sideadmiddle','sideadbottom'
($row = mysql_fetch_array($result, MYSQL_NUM));
$keytop = array_search('sideadtop', $row);
$sideadtop['url'] == $row[$keytop]['url'];
$sideadtop['image'] == $row[$keytop]['image'];
$keymiddle = array_search('sideadmiddle', $row);
$sideadmiddle['url'] == $row[$keymiddle]['url'];
$sideadmiddle['image'] == $row[$keymiddle]['image'];
I am trying to get the url and image values for each ad placement value. I am not sure how the output for the mysql query is sent to php. Is it sent as a multideminsional array or just a array?
Should I be calling individual MySQL queries or is there an easy way to call multiple rows and than separate them after?

mysql_fetch_* will only fetch one row. I think what you want is this:
$result = mysql_query("SELECT url, image, placement FROM advert WHERE user='1'")
or die(mysql_error());
$adverts = array();
while(($row = mysql_fetch_assoc($result))) {
$adverts[$row['placement']] = $row;
}
It will create an array like this:
Array(
'sideadtop' => Array(
'url' => ...,
'image' => ...,
'placement' => ...
),
'sideadmiddle' => Array(...),
'sideadbottom' => Array(...)
)
You can access the individual adverts with $adverts['sideadtop'], $adverts['sideadmiddle'], etc.
Imo this is a better approach than creating a variable for each element.

Calling mysql_fetch_assoc/mysql_fetch_array will get you one row of the data. You can then iterate this, to get all the rows.
I would tend to use mysql_fetch_assoc, for a small performance increase.
E.g.
$result = mysql_query("SELECT url, image, placement FROM advert
WHERE user='1'") or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$keytop[] = array_search('sideadtop', $row);
$sideadtop['url'][] == $row[$keytop]['url'];
$sideadtop['image'][] == $row[$keytop]['image'];
$keymiddle[] = array_search('sideadmiddle', $row);
$sideadmiddle['url'][] == $row[$keymiddle]['url'];
$sideadmiddle['image'][] == $row[$keymiddle]['image'];
}
I would also think about how you would like the resulting data structured, but you should get the gist.

Related

SQL OR statement does not work in PHP

I want to get some elements from a database (phpmyadmin). The database "top" is set up like:
ID || Name
____________
1 || Home
2 || About
3 || Users
4 || Admin
...
I use the following Code to get the information:
<?php
$sql = "SELECT ID
FROM top
WHERE Name='Users' OR Name='Admin'";
$query = mysqli_query($dbconnect, $sql);
$oq = mysqli_fetch_assoc($query);
if(in_array($_GET['ID'], $oq)){
//Execute some Code
}
?>
If I execute the sql-code I get the result I want (ID 3 and 4) but in "$oq" there is only one element (the first one -> 3) left. Therefore the Code I want to execute is only displayed once.
You have to use a while loop:
$oq = array();
while($row = mysqli_fetch_assoc($query)) {
echo $row['ID'];
$oq[] = $row['ID'];
}
As you have done it you're only fetching one row in $oq. You will have to add each value to the array $oq in order to use in_array() for the test.
There are some other techniques you can use here, for instance you could fetch everything (an array of arrays) and loop through the array, depending on your needs.
You will have to use array to use have multiple DB values
$values=array();
while($row = mysql_fetch_array($result)){
$values = array('ID'=>$row['ID']);
}

Associative array not storing first result from SQL

I have a database in MySQL and I'm using this query to select certain rows from it using PHP:
$q = "SELECT Number, Body
FROM boxes
WHERE Number BETWEEN '1' AND '4' ORDER BY Number ASC";
Then calling the query and initiating arrays:
$r = $mysqli->query($q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$array = array();
$content = array();
Then attempting to sort the results into an associative array where the 'number' is the key and the 'body' is the value.
while ($row = mysqli_fetch_assoc($r)) {
$array = array(
$content[$row['Number']] = $row['Body']
);
This works fine except it will not store the first value. This is the result of print_r($content);, missing the first row.
Array ( [2] => This is entry two [3] => This is entry three [4] => This is entry four )
I have tried running the SQL query within PHPMyAdmin and it returns all four rows as I would expect.
Does anyone have any ideas what I'm doing wrong?
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
You are getting first returned row by this line. You have to remove it and it will work properly.
mysqli_fetch_array and mysqli_fetch_assoc returning NEXT row on every call.

php & mysql - loop through columns of a single row and passing values into array

I have a mysql table with columns id, f1, f2, f3, ..., f20 where id is productID and f1,...f20 are product features. Depending on each product, some might have all, none or only some columns filled.
Each column holds a delimited string like a#b#c#d where a,b,c,d are values in different languages (a=english, b=french etc)
I need to select a row by it's id, explode each column's value (f1,f2...) with '#' in order to get the language part I need and then pass the values to an array in order to use in my product spec page.
How do I loop through the fetched row (i'm using $row = my_fetch_array) and put the exploded value into a one dimension array like $specs=('green', 'M', '100', 'kids'...) etc?
PS:I know, is complicated but I cant come up with a better idea right now.
Try this:
$result = mysql_query("...");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$arr = array();
foreach ($row as $k=>$v)
{
$features = explode("#", $v);
$value = $features[1]; // get the specific language feature
$arr[] = $value;
}
$specs = join(", " , $arr);
}
Not sure this is the best way togo but you could define an array with your langs, then access the result by lang
<?php
$langs=array('eng'=>0,'fr'=>1,'ger'=>2,'geek'=>3);
while ($row=mysql_fetch_assoc($result)) {
$specs=explode('#',$row['f1']);
$other=explode('#',$row['f2']);
...
}
//Get lang from cookie that you could set elsewhere
$lang=(isset($_COOKIE['lang']))?$_COOKIE['lang']:'eng';
echo $specs[$langs[$lang]];
?>
My solution for how I understand you question:
// Make a MySQL Connection
$sQuery = "SELECT f1,f2,... FROM table WHERE id = ...";
$oResult = mysql_query($sQuery) or die(mysql_error());
//Fetch assoc to use the column names.
$aRow = mysql_fetch_assoc($oResult);
//Prepare the product properties array
$aProductProperties = array("English"=>array(),"French"=>array(),"Dutch"=>array());
//Loop over all the columns in the row
foreach($aRow as $sColName=>$sColVal){
//Explde the column value
$aExplodedCol = explode("#",$sColVal);
//The code below could be nicer when turned into a looped that looped over every language,
//But that would make the code less readable
$aProductProperties['English'][$sColName] = $aExplodedCol[0];
$aProductProperties['French'][$sColName] = $aExplodedCol[1];
$aProductProperties['Dutch'][$sColName] = $aExplodedCol[2];
}
//Done, you should now have an array with all the product properties in every language

fastest way to display mysql db records

I have slow query problem, may be i am wrong, here is what i want,
i have to display more than 40 drop down lists at a single page with same fields , fetched by db, but i feel that the query takes much time to execute and also use more resources..
here is an example...
$sql_query = "SELECT * FROM tbl_name";
$rows = mysql_query($sql_query);
now i use while loop to print all records in that query in drop down list,
but i have to reprint same record in next drop down list up to 40 lists, so i use
mysql_data_seek() to move to first record and then reprint the next list and so on till 40 lists.
but this was seems slow to me so i use the second method like this same query for all 40 lists
$sql_query2 = "SELECT * FROM tbl_name";
$rows2 = mysql_query($sql_query2);
do you think that i wrong about the speed of query, or do you suggest me the another way that is faster than these methods....
Try putting the rows into an array like so:
<?php
$rows = array();
$fetch_rows = mysql_query("SELECT * FROM table");
while ($row = mysql_fetch_assoc($fetch_rows)) {
$rows[] = $row;
}
Then just use the $rows array in a foreach ($rows as $row) loop.
There is considerable processing overhead associated with fetching rows from a MySQL result resource. Typically it would be quite a bit faster to store the results as an array in PHP rather than to query and fetch the same rowset again from the RDBMS.
$rowset = array();
$result = mysql_query(...);
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
// Append each fetched row onto $rowset
$rowset[] = $row;
}
}
If your query returns lots of rows (thousands or tens of thousands or millions) and you need to use all of them, you may reach memory limitations by storing all rows into an array in PHP. In that case it may be more memory-conservative to fetch rows individually from MySQL, but it will still probably be more CPU intensive.
Instead of printing the records, going back, and printing them again, put the records in one big string variable, then echo it for each dropdown.
$str = "";
while($row = mysql_fetch_assoc($rows)) {
// instead of echo...
$str .= [...];
}
// now for each dropdown
echo $str;
// will print all the rows.

How to roam in SQL query more than one time in PHP

A friend of mine has asked me a question which i do not know how.
The problem is he wants to use a result set of a query more than one time. Whenever he wants.
There is example tables and example output attached.
I will query two times only:
Select * from ornek1_ust
Select * from ornek1_alt
Is it possible to roam in a result set we already have with PHP to have some output like example output. I want to query database with full data for once. Then i want to use it wherever i want whenever i want.
Example Tables:
Example Output:
You'd want to "cache" the results within PHP. To fetch the data, you'd do a simple join query:
SELECT ornek_ust1.isim AS ust, ornek1_alt.ism AS alt
FROM ornek_ust1
JOIN ornek1_alt ON ornek_ust1.id = ornek1_alt.ust_ID
ORDER BY ornek_ust1.isim, ornek1_alt.ism
and within PHP, do something like:
$data = array();
$sql = "SELECT ...";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res)) {
$data[$row['ust'][] = $row['alt'];
}
which will build an array that looks like your desired data:
$data = array(
'ust data1' => array(
0 => 'alt data 1'
1 => 'alt data 2'
),
'ust_data2' => ... etc...
)
It sounds like you want to be using mysql_result() to be able to pull out data from a resultset at will.
If you want to loop through the whole dataset and still have it available to loop through again, you can use mysql_data_seek() to set the internal pointer back to the beginning.
Just store the query results in an array....
$sql = "Select * from ornek1_ust";
$results = array();
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$results[] = $row;
}
// Use $results further on in your code

Categories