while loop within foreach - php

I've got a form with questions which gets answered. Then on the following page I'm trying to validate the questions to see if the answer is correct or not because eventually I must work out a percentage for the test.
$tid1 = $_SESSION['tid'];
$departmentid = $_SESSION['deptid'];
$userid = $_SESSION['userid'];
foreach($_POST['question'] as $key => $answer) {
include 'datalogin.php';
mysql_query("INSERT INTO ex_answer (id,class_name,testname,name,percentage,qnr,answer_chosen,points_scored,result)
VALUES ('0','$departmentid','$tid1','$userid','0','$key','$answer[0] $answer[1] $answer[2] $answer[3] $answer[4] $answer[5] $answer[6] $answer[7] $answer[8]','0','0')");
$sql1="SELECT * FROM ex_question WHERE test_name = '$tid1' AND q_nr = '$key'";
$result1=mysql_query($sql1);
while($row1 = mysql_fetch_array($result1)) {
$q_nr=$row1['q_nr'];
echo $q_nr;
}
}
The problem is (I think) that it is not selecting the question number q_nr = '$key' correctly from the table because echo $q_nr gives no output

If you are getting a valid result (Test the sql in your Database client ) then you should just use the following to access it as an associative array:
mysql_fetch_assoc($result1);
instead of the mysql_fetch_array() or use
mysql_fetch_array($result1, MYSQL_ASSOC)
Test what is being returned to you, comment out your while loop and then do:
$row1 = mysql_fetch_array($result1);
print_r($row1);
before you while loop add the following for validation:
if (!$result1) {
die('Could not query:' . mysql_error());
}

Use mysql_fetch_assoc to be able to use column name indexes on returned array.

You can also output the SQL and test it on the DB, that will show that you are getting the expected results

Related

Not enter while loop after mysql_fetch_assoc

please take a look at this code :
$sql = "SELECT * FROM shop";
$result = mysql_query($sql);
echo $result;
echo "before lop";
while ($xxx = mysql_fetch_assoc($result)) {
echo "inside lop";
echo $xxx['column_name'];
}
echo "after lop";
When I run such code i receive :
Resource id #244
before lop
after lop
It did not enter while lop, and I really don't know why :(
I used before such code and there were no problems.
Can someone help me?
$sql = "SELECT * FROM shop";
$result = mysql_query($sql) or die(mysql_error());
echo mysql_num_rows($result);
Check how many records are present in your shop table. I think shop table is empty.That is why not entering in the while loop.
You can do like this
$count = mysql_num_rows($result);
if($count > 0) {
while ($xxx = mysql_fetch_assoc($result)) {
echo $xxx['column_name'];
}
}
I would guess that the call to mysql_fetch_assoc() has returned false, possibly due to no results being returned from the database, this would cause the while loop to not execute even once. I would check the output of var_dump(mysql_fetch_assoc($result)) to ensure that data has been returned.

Query Result: What is $row[0]

I know this may sound like a stupid question from a programming-newbie, but I just want to make sure I understand correctly.
After a query, what does $row[0] stand for/ result in?
Is my understanding correct that $row[0] shows ALL results?
HERE ARE EXAMPLES:
$query = "SELECT count(commentid) from comments where jokeid = $jokeid";
$result = mysql_query($query);
$row=mysql_fetch_array($result);
if ($row[0] == 0)
{
echo "No comments posted yet. \n";
} else
{
echo $row[0] . "\n";
echo " comments posted. \n";
AND THIS ONE
$query = "Select count(prodid) from products where catid = $catid";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if ($row[0] == 0)
{
echo "<h2><br>Sorry, there are no products in this category</h2>\n";
}
else
{
$totrecords = $row[0];
Thanks in advance.
$row[0] will simply echo the first column in your database.
0 is the first because all arrays in PHP (and in most programming languages) are zero-based - they simply start with zero.
$row[0] will be the value of the first column in your results. If you use mysql_fetch_assoc($result) you will have an array in the form:
array(column_name => column_value);
e.g.
$row = mysql_fetch_asssoc($result);
$value_column_1 = $row['column_1'];
You can also use mysql_fetch_object($result) to get an object with column names as the parameters.
$row = mysql_fetch_object($result);
$value = $row->column_name
mysql_fetch_array() takes the next (in your examples first) row out of the resultset and stores the data in an array $row.
$row[0] now represents the first value of that row.
So in total in your examples the variable holds the first value of the first row of your resultset.

Figuring out why I am getting a Resource ID #5 error

This is a part of my code, and the echo is to test the value and it gives me Resource ID #5
$id = mysql_query("SELECT id FROM users WHERE firstname='$submittedfirstname' AND lastname='$submittedlastname' AND email='$submittedemail'") or die(mysql_error());
$counter = mysql_num_rows($id);
echo $id;
I am just getting into programming, and lately seeing lot of Resource ID outputs/errors while working with Databases.
Can someone correct the error in my code? And explain me why it isnt giving me the required output?
This is not an error. This is similar to when you try to print an array without specifying an index, and only the string "Array" is printed. You can access the actual data contained within that resources (which you can think of as a collection of data) using functions like mysql_fetch_array().
In fact, if there were an error here, the value of $id would not be a resource. I usually use the is_resource() function to verify that everything is alright before using variables which are supposed to contain a resource.
I guess what you intend to do is this:
$result = mysql_query("SELECT id FROM users WHERE firstname='$submittedfirstname' AND lastname='$submittedlastname' AND email='$submittedemail'") or die(mysql_error());
if(is_resource($result) and mysql_num_rows($result)>0){
$row = mysql_fetch_array($result);
echo $row["id"];
}
Did you mean to echo $counter? $id is a resource because mysql_query() returns a resource.
If you are trying to get the value of the id column from the query, you want to use e.g., mysql_fetch_array().
Here is an excerpt from http://php.net/mysql.examples-basic:
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
Adapted to the code you provided, it might look something like this:
$result =
mysql_query("SELECT id FROM users WHERE firstname='$submittedfirstname' AND lastname='$submittedlastname' AND email='$submittedemail' LIMIT 1")
or die(mysql_error());
if( $row = mysql_fetch_array($result, MYSQL_ASSOC) )
{
$id = $row['id'];
}
else
{
// No records matched query.
}
Note in my code that I also added LIMIT 1 to the query, as it seems like you are only interested in fetching a single row.
are you looking for
while ($row = mysql_fetch_array($id)) {
echo $row['id'];
}
?
$kode_gel = substr($_GET['gel'],0,3);
$no_gel = substr($_GET['gel'],3,5);
$cek = mysql_query("SELECT id_arisan
FROM arisan WHERE kode_gel = '".$kode_gel."'
AND no_gel = '".$no_gel."'");
$result = mysql_fetch_array($cek);
$id = $result['id_arisan'];
header("location: ../angsuran1_admin.php?id=".$id);

SQL query is only retrieving first record

I have a query which is designed to retireve the "name" field for all records in my "tiles" table but when I use print_r on the result all I get is the first record in the database. Below is the code that I have used.
$query = mysql_query("SELECT name FROM tiles");
$tiles = mysql_fetch_array($query);
I really cant see what I have done wrong, I have also tried multiple searches within google but I cant find anything useful on the matter at hand.
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['age'];
echo "<br />";
}
?>
'mysql_fetch_array'
Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
This means that it returns array (contains values of each field) of A ROW (a record).
If you want other row, you call it again.
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
// Do something with $row
}
Hope this helps. :D
Use "mysql_fetch_assoc" instead of "mysql_fetch_array".
$query = mysql_query('SELECT * FROM example');
while($row = mysql_fetch_assoc($query)) :
echo $row['whatever'] . "<br />";
endwhile;
I believe you need to do a loop to invoke fetch array until it has retrieved all the rows.
while ($row = mysql_fetch_array($query) ) {
print_r( $row );
}

How do I loop through a PHP array containing data returned from MySQL?

Ok I have a table with a few fields. One of the fields is username. There are many times where the username is the same, for example:
username: bob
password: bob
report: 1
username: bob
password: bob
report: 2
I did a SQL statement to select * where username='bob'; but when I do the following PHP function, it will only return the last result:
$thisrow = mysql_fetch_row($result);
I need to get every field from every row. How should I go about doing this?
$mainsection="auth"; //The name of the table
$query1="select * from auth where username='$user'";
$result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); //do the query
$thisrow=mysql_fetch_row($result);
echo "Study: " . $thisrow[1] . " - " . $thisrow[5];
Sorry for such a dumb question. I can't seem to get the while loops of more than one field working for the life of me.
mysql_fetch_row fetches each row one at a time. In order to retrieve multiple rows, you would use a while loop like this:
while ($row = mysql_fetch_row($result))
{
// code
}
Use a loop, and use mysql_fetch_array() instead of row:
while($row = mysql_fetch_array($result)) {
echo "Study: " . $row[1] . " - " . $row[5];
// but now with mysql_fetch_array() you can do this instead of the above
// line (substitute userID and username with actual database column names)...
echo "Study: " . $row["userID"] . " - " . $row["username"];
}
I suggest you to read this:
http://www.w3schools.com/php/php_mysql_select.asp
It will give you an overview idea of how to properly connect to mysql, gather data etc
For your question, you should use a loop:
while ($row = mysql_fetch_row($result)){//code}
As said by htw
You can also obtain a count of all rows in a table like this:
$count = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM table"));
$count = $count["count"];
You can also append a normal WHERE clause to the select above and only count rows which match a certain condition (if needed). Then you can use your count for loops:
$data = mysql_query("SELECT * WHERE username='bob'");
for ($i = 0; $i
Also, mysql_fetch_array() is usually a lot easier to use as it stores data in an associative array, so you can access data with the name of the row, rather than it's numeric index.
Edit:
There's some kind of bug or something going on where my second code block isn't showing everything once it's posted. It shows fine on the preview.
I like to separate the DB logic from the display. I generally put my results into an array that I can call within the HTML code. Purely personal preference; but here's how'd I'd approach the problem: (I'd take the $sql out of the error message in production)
<?php
$sql="
SELECT *
FROM auth
WHERE username='$user';
";
$result = mysql_query($sql)
or die("Failed Query : ".mysql_error() . $sql); //do the query
while ($ROW = mysql_fetch_array($result,MYSQL_ASSOC)) {
$USERS[] = $ROW;
}
?>
HTML CODE
<? foreach ($USERS as $USER) { ?>
Study: <?=$USER['dbFieldName'];?> - <?=$USER['dbFieldName2'];?>
<? } //foreach $USER ?>
$qry=mysql_query(select * where username='bob');
if(mysql_num_rows($qry))
{
while($row=mysql_fetch_array($qry,MSQL_NUM))
{
echo $row[0]." ".$row[1]." ".$row[2]."<br>";
}
}

Categories