I have an associative array like such:
$arr = array('format' => 'A4', 'coulor' => 'red', 'height' = > '30');
I would like to use it in an mysql query like such:
reset($arr);
$first_key = key($arr); // get the first key of the array
$sql = "// sql query here...";
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_assoc($result))
{
echo $row[$first_key]; // will echo out the content of a table field
}
How to advance the cursor of this associative array so I can echo out the content of the next column in the mysql table
If you really need to use the keys of your $arr then just do:
while($row = mysqli_fetch_assoc($result))
{
foreach($arr as $key=>$v)
echo $row[$key];
}
Otherwise you can simply use mysqli_fetch_row() In this way your keys are integers, and you can get the next by doing:
while($row = mysqli_fetch_row($result)) {
echo $row[0]; // will echo out the content of a table field
echo $row[1]; // will echo out the content of a table field
}
Related
I have a simple question. I have an array that has two columns (id, name) that is a result of a MySQL query. I want to store the result of the query into a array variable so i can access each element when i need to.
I am able to store a one dimension array like the following:
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row['name'];
}
How can I store and access a two dimensional array? Also is it best to use a for loop or while loop to store these?
Simply do this:
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
To access your results you can do this:
$firstResultRow = $array[0];
$firstResultName = $array[0]['id'];
$firstResultName = $array[0]['name'];
This will tell you if a particular row exists:
if(isset($array[$x])) {
$aRow = $row[$x];
// do stuff with $aRow;
}
This will give you a row count for your array:
$rowCount = count($array);
This will set up a loop through your array:
foreach($array as $index => $row) {
$id = $row['id']
$name = $row['name'];
// $index will have the array index of the current row. 0 -> $rowCount - 1
}
Don't specifically store the index of $row but rather store the whole row.
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
Then $array will have the following structure:
$array = [
[
'id'=> ...,
'name' => ...,
],
...
];
To initially access all of the results from [mysqli_fetch_assoc][1] you will want to use the while loop like you are, mysqli_fetch_assoc will continue to output results until it doesn't have any more data. Then at that point mysqli_fetch_assoc will return NULL. This will signal to your while loop to stop iterating.
Then to access variables inside of your $array, I recommend using foreach.
You could then do:
foreach ($array as $row) {
do something with $row['name'] or $row['id']
}
You could also use a for loop, but it takes more work IMO. Compare the above with this alternative:
for ($i = 0; $i < count($array); $i++) {
$row = $array[$i];
do something with $row['name'] or $row['id']
}
Can someone please help? I'm new to PHP and struggling to make this bit of code to work. For example I have a sql database table with the following schema and data:
Type....rent_price
a..........100
b..........200
c..........300
I want to be able to echo say, "a", in one section and "200" in another. The following code will display "a" but then I can't seem to get it to display anything from the rent_price column using a second array.
$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row['type']);
for ($set1 = array (); $row = $result->fetch_assoc(); $set1[] =$row['rent_price']);
?>
<?php echo $set[0];?>
<?php echo $set1[1];?>
You loop through the results twice, without resetting. Try to loop only once:
$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
$set = array ();
$set1 = array ();
while ($row = $result->fetch_assoc())
{
$set[] = $row['type'];
$set1[] =$row['rent_price'];
}
?>
<?php echo $set[0];?>
<?php echo $set1[1];?>
Depending on what you mean by '"a" in one section and "200" in another', you may be able to forgo creating the intermediate arrays and just print the values from your query as you fetch them. Two cells in a table row, for example:
while ($row = $result->fetch_assoc()) {
echo "<tr><td>$row[type]</td><td>$row[rent_price]</td></tr>";
}
your data is in the first element of array
$set1[0]
but youre probably better off maintaining the naming throughout
$results = array();
while ($row = $result->fetch_assoc()){
$results[] = $row;
}
foreach ($results as $result){
echo $result['type'];
echo $result['rent_price'];
}
OR
$results = array();
while ($row = $result->fetch_assoc()){
$results['types'][] = $row['type'];
$results['rent_prices'][] = $row['rent_price'];
}
foreach ($results['types'] as $type){
echo $type;
}
foreach ($results['rent_prices'] as $rent_price){
echo $rent_price;
}
I'm fetching an array:
$sql = SELECT id, name, state FROM table ORDER BY name
$result = mysqli_query($conn, $sql);
$rows = array();
$dict = ["A","B","C"];
while ($row = mysqli_fetch_array($result)) {
//replace state value here before next line
$rows[] = $row;
}
Values in the state field can be 0,1,2. I want to replace the value in key=state of $row with the value from $dict so 0=>A, 1=>B, 2=>C. Value in state field equals position of $dict array.
ex. if $row=["id"=>"1","name"=>"john", "state"=>"1"]
new $row=["id"=>"1","name"=>"john", "state"=>"B"]
You can use like that:
$dict = array("A","B","C");
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$rows[$i]['id'] = $row['id'];
$rows[$i]['name'] = $row['name'];
$rows[$i]['state'] = $dict[$value['state']];
$i++;
}
If your $dict index is fixed into three index than it will work perfectly.
Explanation:
$dict[$value['state']] this will get the value as per index value.
Like if $value['state'] == 1 than it will get the "B" from $dict array.
For the safe hand you can also use like that:
$rows[$i]['state'] = (isset($dict[$value['state']]) ? $dict[$value['state']] : ''); // if not set than empty anything else that you want.
I'm trying to run a while loop for each row returned from my query, and at the same time print an array of all the vertical columns values? Here is my code so far, although I'm not sure how to achieve the array.
The thing is I dont want the array of each column value inside the while loop. Basically Im trying to display a html table row of each database row values. So I already have the values displaying in the rows from the while loop, but how to access the vertical column of data and show that as an array in my code to create a graph.
Comments in the code also..
<?php
mysql_select_db("db_name", $con);
$qry = "SELECT * FROM tbl_name WHERE col_name='$col_name'";
$result = mysql_query($qry);
if (!$result) exit("The query didnt succeded");
else {
<!-- my while loop using each individual row from the database -->
while ($row = mysql_fetch_array($result)) {
$col1 = $row['col-name1'];
$col2 = $row['col-name2'];
$col3 = $row['col-name3'];
$col4 = $row['col-name4'];
$col5 = $row['col-name5'];
include 'file_to_be_looped.php';
?>
<br/>
<br/>
<?php
}
}
?>
<!-- then just get a list of all values from a single column of the same query-->
<?php echo $col1 ?> <!--this echo produces the last value in the array, so I think im close-->
Try this:
$col=array();
$i=1;
while ($row = mysql_fetch_array($result)) {
$col[$i] = $row['col-name1'];
$i++;
And later you refer to col1 as $col[1]
EDIT:
maybe I missunderstood :
$col=array(array());
$i=1;
while ($row = mysql_fetch_array($result)) {
$col[&i]['col-name1'] = $row['col-name1'];
$col[$i]['col-name2'] = $row['col-name2'];
$col[$i]['col-name3'] = $row['col-name3'];
$col[$i]['col-name4'] = $row['col-name4'];
$col[$i]['col-name5'] = $row['col-name5'];
$i++;
and later you can refer to them as $col[1]['col-name1']
$column_array = array('col_name1' => array(),
'col_name2' => array(),
'col_name3' => array(),
'col_name4' => array(),
'col_name5' => array());
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $colname => $value) {
$column_array[$colname][] = $value;
}
}
Now if you want to see all the values in a column you can do:
print_r($column_array['col_name1']);
I have a problem iterating through an sql query:
$result = mysql_query("SELECT * FROM transactions");
while($row = mysql_fetch_array($result)) {
// this returns 3 rows
foreach ($row as $values)
{
//fputcsv($a_csv, $values;
echo $values;
}
}
The script iterates fine but it appears to be going through each row twice. So what I receive in output is the following:
value1value1value2value2value3value3
I'm not sure why this is - could anyone explain please?
Thankyou
mysql_fetch_array fetches both the named & the numerical keys. Use either mysql_fetch_assoc or mysql_fetch_row.
$result = mysql_query("SELECT * FROM transactions");
//return an associative array
while($row = mysql_fetch_assoc($result)) {
// this returns 3 rows
$values = "{$row["name_of_column1"]}, {$row["name_of_column2"]}, {$row["name_of_column3"]}";
//fputcsv($a_csv, $values;
//print the whole row array
print_r($row);
//echo value in format value1, value2, value3
echo $values;
}
You need to access $row like this $row[0] And $row shouldn't be in a foreach() itself unless it too is some kind of array you need to iterate through.
$result = mysql_query("SELECT * FROM transactions");
while($row = mysql_fetch_row($result))
{
echo $row[0];
echo $row[1];
// ... etc.
}