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
Related
$result = mysql_query($strSql);
foreach($bestmatch_array as $restaurant)
{
while($row = mysql_fetch_array($result))
{
if($restaurant == $row[0])
{
$value = $row[1];
}
}
}
What I am trying to do is sort the result of array formed by query according to the values stored in $bestmatch array.
I don't know what I am doing wrong but the 4th line just seems to run once. Please help guys. Thanx in advance.
php mysql_fetch_array() not working as expected
Your expectation is not right.
foreach($bestmatch_array as $restaurant)
{
// This loop will only run for first iteration of your foreach.
while($row = mysql_fetch_array($result))
{
}
// everything has been fetched by now.
}
That is a logically incorrect sequence.
You expect your inner loop to be called over and over again as many times as you have the outer loop run but record fetch does not work like that. For outer loop's first run all the rows in $result will be fetched and since you do not reset the counter after your while loop that means after the first run there will be no more rows for the next run.
Solution? Fetch the row from mysql first then use a simple in_array call to check whether that restaurant is there in your array.
$result = mysql_query($strSql);
while($row = mysql_fetch_array($result))
{
$name=$row[0];
if(in_array($name,$bestmatch_array))
$value=$name;
}
Store the results of the query in the array first:
$result = mysql_query($strSql);
$results_row = array();
while($row = mysql_fetch_array($result))
{
$results_row[] = array($row[0],$row[1]);
}
foreach($bestmatch_array as $restaurant)
{
foreach ($results_row as $key => $value)
{
if($restaurant == $results_row[$key][0])
{
$value = $results_row[$key][1];
}
}
}
Some code to fetch the field names by connecting it with db:
<?php
#mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$result = mysql_query("SELECT * FROM sample");
$storeArray = Array();
while ($row = mysql_fetch_array($result)) {
if (mysql_num_rows($result) > 0) {
$storeArray = $row['name'];
echo $storeArray;
}
}
?>
The above code works just fine but when it runs it gives me ramuraja. Here ramu and raja are seperate fields. But its giving me a joined output.
How can i get the two field value seperately like ramu and raja.
You print / echo the values directly after one another. Using echo $storeArray.'<br>'; would print a linebreak additionally, thus printing
ramu
Raja
However, you could also store all the variables in an array, for example with $storeArray[] = $row['name']; instead of $storeArray = $row['name'];. That would create a new array element, the value being $row['name'], while the key is incrementing for every element being added.
After having received all rows that match the query, you could loop through the array and Display the answers.
EDIT: Please check out mysqli or PDO; those PHP extensions are standard with newer versions and should be used instead of the old (and now deprecated) mysqli solution. Don't worry, they can do the same (and much more).
You need to do a for each statement to iterate through the array and echo the field along with a line break
First of all, you're declaring $storeArray as an array in this line: $storeArray = Array();, but later you replace it with a string $storeArray = $row['name'];
If you want to use $storeArray as an array, change this line:
$storeArray = $row['name'];
into
$storeArray[] = $row['name']; //add element to the array
Now loop all the results (remove echo $storeArray;)
After you've fetched all the results you kan echo them like:
foreach($storeArray as $name){
echo $name.'<br>';
}
Some confusion in code ....
first check ifthere are results:
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
....
}
}
than be more clear about what you wont:
an array :
$storeArray = Array();
or a string:
$storeArray = $row['name'];
I would so like this:
$storeArray = Array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$storeArray[] = $row['name'];
}
}
// array
print_r($storeArray);
// string
echo implode(',', $storeArray);
I am making a mysql query . I want to add result to an array. suppose I am selecting all user from user table. I want to get everyones name. if the row=5 i want to save every name according to the row index.
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
//echo ($row);
$num=mysql_num_rows($query);
echo ($num);
for ($i=1; $i<=$num;$i++){
//here I want to save all name to an array.
}
Please help.
You might be looking for something like this:
$rows = array();
// while there are more records, add them to `$rows`
while($row = mysql_fetch_assoc($result)) {
$rows []= $row;
}
Note that mysql_fetch_assoc() will just return false if there are no (more) records in the result set. So you don't need the call to mysql_num_rows()
$num = mysql_num_rows($query);
if($num > 0)
{
while($row = mysql_fetch_array($query)
{
$names[] = $row['name'];
}
}
That will create an array called $names which you can loop through later. Also, it's a good time to look into mysqli_* functions, or PDO.
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];
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...