While loop not working for every index - php

I am new to php, but I had used while loop and it worked. But in this case i don't know why it is not working.
I am using following query to fetch data from mysql data base.
$query="SELECT * FROM `groupMembers` WHERE group_id = '$group_id'";
if ($result = mysql_query($query)) {
# code...
echo mysql_num_rows($result);
}
It prints 2 as number of rows. But the problem is in following while loop:-
while ($data = mysql_fetch_array($result)) {
# code...
echo $data['member_id'];
}
I prints only one member's id. (the second one == member_2)
The above query returns 2 rows when run in mysql :-
member_id | group_id
----------|----------
member_1 | group_1
member_2 | group_1

i had same problem,i was calling following code two times
mysql_fetch_array($result)
Show more code - what happens before while

first try mysql_num_rows in how many rows is returns.
if "0" then can't fetch any record from your mysql and check your sql query. if return no of row then try below code:
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. "<br>";
}
} else {
echo "0 results";
}
Enjoy Coding.

That is because when it create array for your MySQL query it will change me with to same value "group_1"
Try to convert mysqli_fetch_array to mysqli_fetch_assoc instead

$query="SELECT * FROM `groupMembers` WHERE group_id = '$group_id'";
Here,$group_id can't be place between '';

use $results->fetch_assoc(); which get your data
<?php
// your database connection
if ($results->num_rows > 0) {
while ($row = $results->fetch_assoc()) {
echo 'Member Id:' . $row["member_id"] . '<br>';
}
} else {
echo " No Result";
}
?>

Related

How to print selected value from database

I am selecting a value from database and want to print it in the html page. I have tried this piece of code:
$queryreg = mysql_query("SELECT available FROM hospital WHERE h_name='$hospital' ");
$a= $queryreg;
echo $a;
But the result is showing as "Resource id #7". Please help me out
$queryreg = mysql_query("SELECT available FROM hospital WHERE h_name='$hospital' ");
$queryreg = mysql_fetch_assoc($queryreg);
$a= $queryreg;
echo $a['available'];
mysql_query() returns a resource on success. You will have to use mysql_fetch_row to retrieve values that returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.
$queryreg = mysql_query("SELECT available FROM hospital WHERE h_name='$hospital' ");
if($queryreg)
{
if(mysql_num_rows($queryreg) > 0)
{
$a = mysql_fetch_row($queryreg);
echo $a[0];
}
else
echo "No records found.";
}
else
echo "Cannot fetch records ".mysql_error();
In cases when there are multiple rows returning from query, you can use mysql_fetch_array() that fetches a result row as an associative array, a numeric array, or both
$queryreg = mysql_query("SELECT available FROM hospital WHERE h_name='$hospital' ");
if($queryreg)
{
if(mysql_num_rows($queryreg) > 0)
{
while($result = mysql_fetch_array($queryreg))
{
echo "<br>".$result[0];
}
}
else
echo "No records found.";
}
else
echo "Cannot fetch records ".mysql_error();

Having trouble getting my head around fetch_assoc()

sorry but complete newbie to php and mysqli. I have this in my code:
$sql = "SELECT tutorial_title, tutorial_author FROM tutorial_info WHERE tutorial_id<=3;";
$result = $conn->query($sql);
if($result===FALSE) {
echo "Select failed <br>";
}
else {
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Tutorial Title: " . $row["tutorial_title"]. " - Name: " . $row["tutorial_author"]. "<br>";
}
} else {
echo "0 results";
}
This works fine but I don't understand how the line while($row = $result->fetch_assoc()) works. From what I understand it fetches an array so I have something like while($row=$somearray). Why does this iterate though all the rows though? Does fetch_assoc() have a loop built in that iterates though all the rows and returns one at a time?
THere are different answer but one is:
mysqli_fetch_assoc — Fetch a result row as an associative array.
Also, Returns an associative array of strings representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in resultset.
Read mysqli_fetch_assoc in detail.

Compare rows in PHP

Hi I would like to compare two tables from two different databases.
Select from the first database
$sql= mysqli_query ("SELECT * FROM emasa.staff_detail");
$row = mysqli_fetch_array($sql);
Select from the second database
$sql2 = mysqli_query ("SELECT * FROM employee");
$row2 = mysqli_fetch_array($sql2);
Then I compare the two table
if ($row['icnum'] == $row2['emp_ic'])
{
echo "Data already exist in both database.";
}
else
{
while ($row = mysqli_fetch_assoc($sql))
{
echo "<td align='center' height='30'>" . $row ['name'] . "</td>";
echo "<td align='center'>" .$row['icnum'] . "</td>";
}
}
But my problem is it only compares the first row in the database.
My output should only display the staff name that is not available in the other database. However, this is my output.
Based on the output it only compares the first row. So how do I change my code so that it compares the whole row. Please help me, thank you!
You're not looping through the results of the query. You're simply getting back the first row and going with that.
Ex:
$sql= mysqli_query ("SELECT * FROM emasa.staff_detail");
This is returning a result set which you then need to use
$row = mysqli_fetch_array($sql);
to get the actual values. The problem comes when
$row = mysqli_fetch_array($sql);
by itself only gives you one row.
Solution 1
You must use code like this:
while($row = mysqli_fetch_array($sql))
{
//Do some comparison
}
Since you're going to have to loop through two different result sets, you're going to have to do a loop within a loop, build an array of results and then loop through the results afterwards to output your HTML.
Ex:
while($row = mysqli_fetch_array($sql))
{
while($row2 = mysqli_fetch_array($sql2))
{
if ($row['icnum'] == $row2['emp_ic'])
{
//add to array of equal data
}
else
{
//add to array of not equal data
}
}
}
foreach($array as $not_equal_or_equal_data)
{
//output your desired HTML
}
Solution 2
Depending on what you actually care about, you could do a sql statement like this
$sql = "
SELECT
*
FROM
emasa.staff_detail AS sd
JOIN db2.employee AS e
ON sd.icnum = e.emp_ic";
This would return all the rows where those two columns were equal

Retrieve MySQL multiple Query with PHP and Process

So far I have this code:
<?php
include('config.php');
$sql = "SELECT senderID as receiverID, msg, time
FROM msg
WHERE senderID = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["receiverID"];
echo $row["msg"];
echo $row["time"];
}
mysql_free_result($result);
?>
Now this simply fetch's the info and stuff, it works the only problem is the processing part. See, I can probably do this so easily in Python, but I am new in PHP, so, if someone could help me, because this is a example of the thing I get returned:
1Hello! How are you?!?!?!876765981admin to user 3574769
Now, I actually was wondering how I would be able to serperate these into its own variable or just print seperately, I am not quiet sure, this is how its suppose to look for a python thing:
firstRow = ['1','Hello! How are you?!?!?!','876765981']
secondRow = ['1','admin to user 3','574769']
Now, I am not so sure about the php structure or code for this.
In php,what you got was:
[
1 => ["receiverId"=>'1',
"msg"=>'Hello! How are you?!?!?!',
"time"=>'876765981'],
2 => ["receivedId"=>'1',
"msg"=>'admin to user 3',
"time"=>'574769']
]
To get the first row
$firstrow = $result[1]
To print it
echo $firstrow["msg"];
The $result is a nested associative array

Display mysql data in php function

Ok i got a problem now i want to display a data from the database and display it through a function now how do i do that??
like i have fetched a row from the database and its name is $row_field['data']; and it is correct now i have assigned a variable to it like this $data = $row_field['data']; now if i call it in a function it shows undefined variable even after i assigned it global in the function like this
function fun(){
global $data;
echo $data;
}
but if i assign it a value like 1 or 2 or anything it gets displayed without any error why is that so??
If it displays if you assign it a value like 1 or 2 while still in the global scope, then I can only assume that your database did not return the result you thought it did. Does the database value display if you echo it out outside of the function?
Global is evil. I dont know what you are trying to do, but why dont you just do the query in the function itself?
If you have a column named data and your php call was something like
$result = mysql_query("SELECT data FROM mytable");
while ($row_field = mysql_fetch_assoc($result, MYSQL_NUM)) {
...
}
Then you could replace ... with print $row_field['data'].
Else please provide a snippet of your code where you query the db and retrieve the result.
When learning php try to start with simple things. For example in order to get some data from a database follow the examples from php website.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
If all this goes well go a little further change a little the while loop.
$myArray = array();
while ($row = mysql_fetch_assoc($result)) {
$myArray[] = $row;
}
mysql_free_result($result);
// now you can start playing with your data
echo $myArray[0];
Small steps...

Categories