This might seem like a really easy question but it has got me stumped lol. I am trying to print the rows received from the database. I want to store the rows inside an array and then print them using a for loop. I know that the query works however when I try to print the array elements it only prints the word array. I have tired doing it with a foreach loop and a simple for loop. If anyone can point me in the right direction would be a life saver.
Printing Php Code
<?php
$type = "FREE";
$free = getTerms($type);
echo "<p>";
for($j = 0; $j < count($free); $j++)
{
echo "start".$free[$j]."end";
}
echo "</p>";
?>
geting the rows from the database
function getTerms($type)
{
$terms = array();
$connection = mysql_open();
$query = "select terms from terms_and_con where accountType='$type' && currentTerms='YES'";
$results = mysql_query($query, $connection) or show_error("signUp.php", "", "");
while($row = mysql_fetch_array($results))
{
$terms[] = $row;
}
mysql_close($connection) or show_error("signUp.php", "", "");
return $terms;
}
Each entry in the $free array is itself an array (from $row).
Try
echo 'start', $free[$j]['terms'], 'end';
Alternatively, you may find a foreach loop more semantically appropriate
foreach ($free as $row) {
echo 'start', $row['terms'], 'end';
}
Edit: I'd advise using mysql_fetch_assoc() instead of mysql_fetch_array() if you're only going to use associative entries from $row.
the thing is function mysql_fetch_array ( as the name suggests) returns an ( in your case both associative and number) array. so $row is actually array(0 => VALUE, 'terms' => 'VALUE')
So what you are trying to echo is actually an array.
Simple fix:
replace:
$terms[] = $row;
with:
$terms[] = $row[0];
Related
I use foreach to show items from mysql table, but it lists first items first.
I want to list last items first.
The code:
foreach ( $result as $print ) {
$print->sender_user;
$print->reciever_user;
$print->content;
}
I mean that if I add a new item to mysql table this code should show
it above the other items. But it shows first added item last.
Simple, use array_reverse
http://php.net/manual/en/function.array-reverse.php
array_reverse — Return an array with elements in reverse order
$result = array_reverse($result);
foreach ( $result as $print ) {
$print->sender_user;
$print->reciever_user;
$print->content;
}
Otherwise if it's numerically indexed you can always use for
$len = count($result)-1;
for($i=$len; $i>=0; --$i){
$row = $result[$i];
}
And my favorite
$result = [1,2,3,4];
$row = end($result);
do{
echo $row."\n";
}while($row = prev($result));
Try it here
https://3v4l.org/NINss
And with just while, you cant do prev in the while condition because you lose the last element of the array, so it's a bit lamer.
$result = [1,2,3,4];
$row = end($result);
while($row = current($result)){
echo $row."\n";
prev($result);
}
https://3v4l.org/No1Rb
I think that is about it, I could probably do one with goto but that would be showing off.
What would the benefits be of storing db values into an array and then looping through the array vs just using a while loop?
Outputting db results to an array:
$records = array();
if($results = $db->query("SELECT name, address FROM town")) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row;
}
$results->free();
}
}
Loop through array:
foreach($records as $r) {
$r->name;
}
VS a simple While loop:
if($result = $db->query("SELECT name, address FROM town")) {
if($count = $result->num_rows) {
while($row = $result->fetch_object()) {
echo $row->name, ' ', $row->address, '<br />';
}
$result->free();
}
}
Just a while loop and printing the result is easy and fast, but in certain times you want to do more then just print the array and then it becomes handy if you already work with arrays.
The most common use for this is freeing the resultset, allowing you to perform other db queries (updates, inserts...) before actually making any use of the results you got in the first place.
I'm experimenting with MySQLi and using the following code to check differences for how I should approach my array formatting/usage for fetch_array(MYSQLI_ASSOC);
here is my code:
include "Database.php";
$ArrayQuery = $mysqli->query("SELECT * FROM accountinformation");
while ($ArrayResults = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
echo count($ArrayResults);
echo "<br>";
}
echo "<br><br><bR><br>";
$Empty = array();
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
foreach ($ArrayResult AS $ArrayRes)
{
$Empty[] = $ArrayRes;
}
}
print_r($Empty);
The problem is, that i'm using the same Variable for my while loop, the first one returns 3 then 3 Which is expected.
But the problem is, with my second query; it returns a blank array
array( ) when print_r();
and when I do:
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
print_r($ArrayResult);
}
For my Second while loop, it returns nothing for output.
I have checked my variables $ArrayResults and $ArrayResult are not duplicates, they are in fact unique.
Why is my second while loop returning nothing when my first one is working?
Update
When I produce a second query into the mixture with a different starting variable:
$ArrayQuer = $mysqli->query("SELECT * FROM accountinformation");
and modify my second while loop:
while ($ArrayResult = $ArrayQuer->fetch_array(MYSQLI_ASSOC))
{
print_r($ArrayResult);
}
I get the expected output? So is it a case of MySQLi not allowing the same parameters to be used twice throughout the script?
mysqli_data_seek
Adjusts the result pointer to an arbitrary row in the
result
while ($ArrayResults = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
echo count($ArrayResults);
echo "<br>";
}
echo "<br><br><bR><br>";
mysqli_data_seek($ArrayQuery,0); // Addition Made Here
$Empty = array();
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
foreach ($ArrayResult AS $ArrayRes)
{
$Empty[] = $ArrayRes;
}
}
print_r($Empty);
To re-use an already fetched array; you should use mysqli_data_seek(); (Notice I have added it above your `$Empty Variable) This should be the problem.
See the manual here:
http://us.php.net/manual/en/mysqli-result.data-seek.php
Think of this scenario; Why would you re-buy something you already own?
Fits perfectly in your case
Actually I am very new to PHP.
My code goes here:
<?php
$mysql = mysql_connect('localhost','Susi','susi');
mysql_select_db('mydb', $mysql);
$rs = mysql_query("show tables;");
$nonTable = array('table_1','table_2');
while ($tabs = mysql_fetch_assoc($rs)) {
foreach ($tabs as $tables) {
echo $tables.'<br />';
}
}
?>
In this case $rs stores the entire table of the database "mydb" .
There is another array $nontable which contains some tables which are already in Table list of "mydb" database.
I want to pass those table names to the while loop excluding the tables in "$nontable" array.
I tried
array_diff($rs,$nontable)
but it provided NULL result.
I will be very happy if somebody helps me out...
Thanks in advance...
Do you mean:
while ($tabs = mysql_fetch_assoc($rs)) {
foreach ($tabs as $tables) {
if(!in_array($tables, $nonTable)) {
echo $tables."<br />";
}
}
}
Your $rs does not contain any result... It contains the resource id
hence it outputs you NULL for array difference.
Your variable $tabs which you are iterating in while loop, is the
associative array with value
Now if you want those tables names which are NOT in $nontable array
then you have to do this
while ($tabs = mysql_fetch_assoc($rs)) {
foreach ($tabs as $tables) {
if(!in_array($tables, $nonTable)) {
echo $tables."<br />";
}
}
}
You can't do array_diff($rs,$nontable) because $rs is not an array, so you need to do it in such way:
<?php
$mysql = mysql_connect('localhost','Susi','susi');
mysql_select_db('mydb', $mysql);
$rs = mysql_query("show tables;");
$nonTable = array('table_1','table_2');
while ($tabs = mysql_fetch_array($rs)) {
$diff = array_diff($tabs, $nontable)
foreach ($diff as $tables) {
echo $tables.'<br />';
}
}
EDITED: also you need to use mysql_fetch_array instead of mysql_fetch_assoc
As #Sudhir said, you can use in_array() function in PHP. This function search your expected item through an array and will return True if it can find it. So using the code that #Sudhir suggested, will work for you as you want.
To know more about in_array() function, see http://php.net/manual/en/function.in-array.php
I have the following:
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
$thisResult['name'] = $myRow["name"] ;
$thisResult['race'] = $myRow["race"] ;
$thisResult['sex'] = $myRow["sex"];
$thisResult['dob'] = $myRow["dob"];
}
I can't figure out how to print this back out.
I want to get each row and iterate through each row in the array like a datareader. I'm not sure what to do. I do not want to do the echo in the while. I need to be able to print it out elsewhere. But I don't think I've done it right here to be able to print it later.
I also tried, this, however:
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
print($thisResult[$myRow["name"]] = $myRow);
}
I then tried:
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
print (odbc_result($myRow,"name"));
}
but got an error.
Thank you for any help.
EDIT: when I do this:
while($myRow = odbc_fetch_array( $result )){
print ($myRow["name"]);
}
I get undefined index name. I am mainly concerned with saving to an array but I have to be able to do it in the loop first.
Declare an array before and assign the values to it:
$rows = array();
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
$rows[] = $myRow;
}
Then you can print it e.g. this way:
foreach($rows as $row) {
foreach($row as $key => $value) {
echo $key . ': '. $value;
}
}
or however you want to.
You don't have to access and assign $thisResult['name'] = $myRow["name"] in your while loop as $myRow already is an array. You just copy the values which is unnecessary.
You say you have a lot of rows. Depending of what you really want to do with data, it might be better to put all this functionality into the while loop to avoid creating an array.
How about something like:
$output = '';
while($myRow = odbc_fetch_array( $result )) {
$output = $output."Your name is {$myRow["name"]} and your race is {$myRow["race"]}\n";
}
// print output later...