SQL query is only retrieving first record - php

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 );
}

Related

Getting specified rows from an array

Am making a really simple php page which pulls data from a really simple database and displays it as charts for a wall monitor.
I've got the data from the db, no problem, but I seem to be struggling splitting that data up
For now i'm just echoing the data to make sure i have what i need.
My code looks like this:
<?php
mysql_connect("host", "user", 'password' or die(mysql_error());
mysql_select_db("databax") or die(mysql_error());
$dbdata = mysql_query("SELECT * FROM dbcpman_resources")
or die(mysql_error());
$column = mysql_fetch_array( $dbdata );
echo $column[0]."<br>";
echo $column[1]."<br>";
echo $column[2]."<br>";
echo $column[3]."<br>";
echo $column[4]."<br>";
echo $column[5]."<br>";
?>
Indeed, it works - it will echo data from the database, but as i've not specified the row anywhere, its just giving me the first row.
I need to be able to work with each row seperately.
There will only ever be 6 rows in this table.
So can anyone help me out with how I go about replicating this for rows 2,3,4,5 and 6?
Thanks in advance!! :)
You need to loop over the result set. The easiest way is to use a while loop as this automatically terminates at the end of the result set, like this.
while ( $row = mysql_fetch_array( $dbdata );
echo $row [0]."<br>";
echo $row [1]."<br>";
echo $row [2]."<br>";
echo $row [3]."<br>";
echo $row [4]."<br>";
echo $row [5]."<br>";
}
Also if you were to change the function that returns the resuilts to use mysql_fetch_assoc() you can reference each field with the name it has on the database so the code is easier to read, like this:
I dont know your field names so I made some up.
while ( $row = mysql_fetch_array( $dbdata );
echo $row ['name']."<br>";
echo $row ['date']."<br>";
echo $row ['time']."<br>";
echo $row ['value1']."<br>";
echo $row ['value2']."<br>";
echo $row ['value3']."<br>";
}
First of all, I'd rather use mysql_fetch_assoc() instead of mysql_fetch_array() since it doesn't srew up your result, if the table structure changes.
It would be even better if you used either mysqli or PDO instead of mysql_* functions, since they are marked deprecated already!
Second please note, that either function just fetches ONE record from your resultset at a time. To fetch all records try the following:
$records = array();
while($row = mysql_fetch_assoc($dbdata)) {
$records[] = $row;
}
You can do a print_r($records); to see what's inside $records after fetching all.
put this line $column = mysql_fetch_array( $dbdata ); in while loop like this
while($column = mysql_fetch_array( $dbdata ))
{
echo $column[0]."<br>";
echo $column[1]."<br>";
echo $column[2]."<br>";
echo $column[3]."<br>";
echo $column[4]."<br>";
echo $column[5]."<br>";
}

Printing a MySQL query in PHP

function MattsScript()
{
$query = 'SELECT * FROM `ACCOUNTING` WHERE `ACCTSTATUSTYPE` = "start" AND `Process_status` IS NULL LIMIT 0,100';
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
while ($row = mysql_fetch_assoc($result))
{
echo $row['USERNAME'] . "<br />";
echo $row['ACCTSTATUSTYPE'];
}
}
I am trying to echo the results of a query. What I think is happening here is I am saving a query to a variable, the first 100 results (LIMIT 0,100) then using a loop to echo each row to the page.
However nothing is happening, no error and nothing written to the page.
Is there something I am missing?
if you are expecting only one result remove the while loop if not leave the while loop and remove the line $row = mysql_fetch_assoc($result); before the while loop. Also make sure you are querying your database correctly.
Example: $result = mysql_query($query) or die(mysql_error());

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.

Selecting one row from MySQL using mysql_* API

I have the following query:
$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage'");
$row = mysql_fetch_array($result);
print_r ($row);
and the output I am getting is:
Resource id #2
Ultimately, I want to be able to echo out a single field like so:
$row['option_value']
Without having to use a while loop, as since I am only trying to get one field I do not see the point.
I have tried using mysql_result with no luck either.
Where am I going wrong?
Try with mysql_fetch_assoc .It will returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows. Furthermore, you have to add LIMIT 1 if you really expect single row.
$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage' LIMIT 1");
$row = mysql_fetch_assoc($result);
echo $row['option_value'];
$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage'");
$row = mysql_fetch_assoc($result);
echo $row['option_value'];
Functions mysql_ are not supported any longer and have been removed in PHP 7. You must use mysqli_ instead. However it's not recommended method now. You should consider PDO with better security solutions.
$result = mysqli_query($con, "SELECT option_value FROM wp_10_options WHERE option_name='homepage' LIMIT 1");
$row = mysqli_fetch_assoc($result);
echo $row['option_value'];
use mysql_fetch_assoc to fetch the result at an associated array instead of mysql_fetch_array which returns a numeric indexed array.
Though mysql_fetch_array will output numbers, its used to handle a large chunk.
To echo the content of the row, use
echo $row['option_value'];
Try this one if you want to pick only one option value.
$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage'");
$row = mysql_fetch_array($result);
echo $row['option_value'];
What you should get as output with this code is:
Array ()
... this is exactly how you get just one row, you don't need a while loop. Are you sure you're printing the right variable?
Ultimately, I want to be able to echo out a signle field like so:
$row['option_value']
So why don't you? It should work.
It is working for me..
$show = mysql_query("SELECT data FROM wp_10_options WHERE
option_name='homepage' limit 1"); $row = mysql_fetch_assoc($show);
echo $row['data'];
is this is a WordPress?
You shouldn't do it like you've done!
To get option from DB use get_option!
this shoude work
<?php
require_once('connection.php');
//fetch table rows from mysql db
$sql = "select id,fname,lname,sms,phone from data";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$emparray = array();
for ($i = 0; $i < 1; $i++) {
$row =mysqli_fetch_assoc($result);
} $emparray[] = $row;
echo $emparray ;
mysqli_close($connection);
?>
make sure your ftp transfers are in binary mode.

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);

Categories