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.
Related
I want to merge two of my columns (yanlis_cevaplar, cevap_icerik) into an array and this code here gives me only one column in array when I print it (yanlis_cevaplar).
How do I fix it?
$cevaplar = "SELECT yanlis_cevaplar FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap1 = array(); //create empty array
while ($row = $cevap_sonuc->fetch_array()) { //loop to get all results
$cevap1[] = $row; //grab everything and store inside array
}
$cevaplar2 = "SELECT cevap_icerik FROM cevaplar";
$cevap_sonuc2 = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap2 = array(); //create empty array
while ($row = $cevap_sonuc2->fetch_array()) { //loop to get all results
$cevap2[] = $row; //grab everything and store inside array
}
$tumcevaplar = array_merge($cevap1, $cevap2);
print_r($tumcevaplar);
Instead of making multiple queries, you can just fetch all the columns you want in one single query:
$cevaplar = "SELECT yanlis_cevaplar, cevap_icerik FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
// Now you can fetch all the rows straight away without any loop.
// The MYSQLI_ASSOC will return each row as an associative array
$result = $cevap_sonuc->fetch_all(MYSQLI_ASSOC);
print_r($result);
This will result in something like this:
Array
(
[0] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
[1] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
... and so on ..
)
If this isn't what you want, then you need to show us an example.
I also recommend that you go through some basic SQL tutorials. How SELECT works is SQL 101. Here's one of many guides: https://www.tutorialspoint.com/mysql/mysql-select-query.htm
I am trying to do a mysql fetch but it keeps adding numbered and labeled keys to the array. I want it to record only the labeled names and data in the array.
Am I using the wrong mysql call?
global $con,$mysqldb;
$sql="SHOW FIELDS FROM ".$dbtable;
$tr = mysqli_query($con,$sql);
$tl = mysqli_fetch_array($tr);
$tl = mysqli_fetch_array($tr);
$sql="SELECT * FROM ".$mysqldb.".".$dbtable." ORDER BY ".$tl['Field']." LIMIT 3";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$table[$row[1]] = $row;
}
foreach($table as $item => $data){
foreach(array_keys($data) as $pointer => $field) {
echo"pointer=".$pointer."\t";
echo"field=".$field."\n";
echo "data=".$data[$field]."\n";
}
}
reults
pointer=0 field=0 data=3823
pointer=1 field=PID data=3823
pointer=2 field=1 data=AA
pointer=3 field=symbol data=AA
pointer=4 field=2 data=1
pointer=5 field=value data=1
I want to omit 0, 2, & 4 from the array.
Take a look at the PHP.net manual for the mysqli_fetch_array() function.
You'll see there's an option called resulttype that will accept 1 of 3 values - MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH the default.
Using MYSQLI_ASSOC will remove the numbered keys.
Or check mysqli_fetch_assoc().
Thanks to thebluefox for a speedy response.
I replaced the fetch with:
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
And now the results are being recorded as they should.
In the phpMyAdmin interface I run the following SQL query:
SELECT id FROM table WHERE family = '1' AND type = 'B1'
and receive the following results:
'1', '18546269', '51534064' which are correct.
Then I wrote the following code in PHP:
$query = "SELECT id FROM table WHERE family = '1' AND type = 'B1'";
$result = mysql_query($query);
$array = mysql_fetch_array($result);
echo '(', implode(',',$array) ,')';
But receive the following result:
(1,1) which I didn't expected.
I thought that (1,18546269,51534064) would be displayed.
Then I wrote the following code to verify what should be displayed:
print_r ($array);
and was very surprised that the values were:
Array ( [0] => 1 [id] => 1 ).
In the end I wrote:
while($array = mysql_fetch_array($result)) {
echo $array['id'],',';
}
and as expected received exactly this:
1,18546269,51534064,
which I can't use because I need a string exactly like that: (1,18546269,51534064).
In fact I 'just' need a variable that gives me the same values of the SQL query that I run in phpMyAdmin.
I'm really confused and would be great if one of you guys could help me.
Solutions with mysqli would be appreciated as well. :-)
$query = "SELECT id FROM table WHERE family = '1' AND type = 'B1'";
$result = mysqli_query($link, $query);
$ids = '';
while($row = mysqli_fetch_array($result)) $ids .= $row['id'].',';
// Filter the text a bit
$ids = rtrim($string, ',');
$ids = '('.$ids.')';
echo $ids;
You basically initiate a variable, put all the ids in it, remove the last comma, append the brackets and that's it.
As documented under mysql_fetch_array():
Return Values
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.
[ deletia ]
Example #2 mysql_fetch_array() with MYSQL_NUM
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_free_result($result);
?>
That is to say, the function returns only one row, by default as an array consisting of both associative and numeric-indexed columns from the resultset. You want instead make multiple calls to the function, with a suitable result_type parameter (as shown above).
mysql_fetch_array fetches array of row, not array of column. That means, if you would have ID and name, the fetched array would contain on each row an id and a name.
Quite a simple modification of your code that should fix the problem would be
$i=0;
$data=array();
while($array = mysql_fetch_array($result)) {
$data[$i]=$array['id'];
$i++;
}
echo '(', implode(',',$data) ,')';
I am trying to add array data from mysql. But only the last row details are getting added. I tried array_push also but did not work. Can any one help
$sql="SELECT * FROM server_details";
$result=mysqli_query($dbC, $sql);
while ($row = mysqli_fetch_array($result))
{
$services=array(
$row['server_name'] => array($row['server_add'] => $row['port'])
);
}
By not creating a new array in every iteration of the loop :
$sql = "SELECT * FROM server_details";
$result = mysqli_query($dbC, $sql);
$services = array();
while ($row = mysqli_fetch_array($result)) {
$services[$row['server_name']] = array($row['server_add'] => $row['port']);
}
Perhaps you're looking for this:
$services[ $row['server_name'] ] = array($row['server_add'] => $row['port']);
In the end you'll get in your $services variable an associative array, indexed by server_name column values.
If they're not unique, you should do this instead...
$services[ $row['server_name'] ][] = array($row['server_add'] => $row['port']);
This way you'll still get the same associative array, but its values will be indexed arrays; thus you won't lose any information for records with the same server_name.
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.