I am a novice at PHP and i have encountered a problem with the following code...
<?php
// Connects to Database
mysql_connect("localhost", "root") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$data = mysql_query("SELECT country_id, country_name FROM country, channels WHERE channels.channel_id = country.channel_id AND channels.channel_id = '1'")
or die(mysql_error());
echo "<table border=0 cellpadding=15>";
echo "<tr align = center bgcolor=white>
<td><b>Country ID</b></td><td><b>Country Name</b></td>" ;
while (mysql_fetch_row($data)) {
$cid = mysql_result($data, 1);
$cname = mysql_result($data, 2);
# inserts value into table as a hyperlink
echo "<tr align = center bgcolor=white><td>$cid</td><td><a href=view_country_detail.php?cid=$cid>$cname</td>";
}
# displays table
print '</table>';
?>
to explain the problem i am getting, i am after generated hyperlinks to drill down to the companies which share the to be clicked country's id from the code above to then display a similar layout on the 'view_country_detail' page. i cant work out why the output for the table gives me a repeated row for the first two id's for the country column in the db. any help would be greatly appreciated as i am totally lost here. Thanks
I don't understand why you use mysql_fetch_row and then don't want to actually use the row you fetch.
You should not be using mysql_result here. What you are doing is fetching data from row 1 of the result set and then data from row 2 regardless of which row the pointer is on in your while loop.
Try this:
while ($row = mysql_fetch_assoc($data)) {
$cid = $row['country_id'];
$cname = $row['country_name'];
}
I personally find it much more readable in code to reference the fields by the associative keys used when using mysql_fetch_assoc or mysql_fetch_array.
Try structuring your while loop as follows:
while($row = mysql_fetch_array($data)){
$cid = $row[0]; //if you have the column names, replace 0 with 'column_name'
$cname = $row[1];
//then echo statement
}
Also, mysql_* functions have started the deprecation process and should no longer be used, even the php manual pages state the use of mysql_* is discouraged. Look into using the similar mysqli_* functions or PDO.
Try this:
while ($row = mysql_fetch_row($data)) {
$cid = $row[0];
$cname = $row[1];
...
}
mysql_fetch_row returns an array.
HOWEVER
You should look at stopping using the mysql_* functions - they're being deprecated. If you switch to PDO or mysqli, it helps make your code more secure, too.
Related
i need displaying the company name from the database but this code does not work for me. Please help. Thanks
<?php
// connect to the database
include('php/db.php');
$result = mysql_query("select name from company where company_id = 1");
echo $result['name'];
?>
Try This One
// connect to the database
include('php/db.php');
$result = mysql_query("select name from company where company_id='1'");
while($row = mysql_fetch_array($result))
{
echo $row['name']."<br>";
}
Try this code:
while($row = mysql_fetch_array($result))
{
echo ""+$row['name'];
echo "<br>";
}
mysql_query returns an object, you first need to turn the object into an associative array using mysql_fetch_assoc();
You can then access elements of that array using the method you have used.
You may want to look at using the mysqli functions, as mysql functions are depreciated.
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>";
}
it's just fetching the first element from the table.
Table name is categories which contains 2 columns : id, category
I cant understand why is it fetching just first row from the table.
<?php
$sql = "SELECT category FROM categories";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
//print_r($row);
?>
You need to iterate through the result set in order to retrieve all the rows.
while($row = mysql_fetch_assoc($result)) {
print($row);
}
Also, stop using mysql_ functions. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which.
Use this in while loop :
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
Just like you wrote mysql_fetch_assoc($result); will get only one row. You have to use loop to get it all.
If you call mysql_fetch_assoc just once, you'll get only the first row...
while(false !== $row = mysql_fetch_assoc($result)) {
print_r($row)
}
The function you are using only does one record.
Try. ..while($row = mysqli_fetch_array($result))
{
echo $row['id'] . " " . $row['category'];
echo "";
}
For retrieve result set Use loop as per your need
foreach
Use when iterating through an array whose length is (or can be) unknown.
as
foreach($row as $val)
{
echo $val;
}
for
Use when iterating through an array whose length is set, or, when you need a counter.
for(i=0;i<sizeof($row);i++)
{
echo $row[$i];
}
while
Use when you're iterating through an array with the express purpose of finding, or triggering a certain flag.
while($row=mysqli_fetch_array($query))
{
echo $row['flag'];
}
I think I need a basic PHP / MYSQL refresh, because nothing is working for me.
My MYSQL Table has two rows of information.
$results = mysql_query("SELECT Name, Description FROM products");
$results = mysql_fetch_assoc($results);
print_r($results);
When printing this, all I get is one result. Array ( [Name] => Banana [Description] => It's a lovely banana ). There are definitely two results in the table. Why is this happening?
Secondly, this loop only returns the first letter of each result, and I don't know why!
foreach($results as $res) {
?>
Name : <?php echo $res['Name']; ?><br />
Description : <?php echo $res['Description']; ?><br />
<?php } ?>
My brain is seriously scrambled today :(
while($res = mysql_fetch_assoc($results)){
?>
Name : <?php echo $res['Name']; ?><br />
Description : <?php echo $res['Description']; ?><br />
<?php } ?>
MySQL has been deprecated and you should either move to PDO or MySQLi. To answer your question for the latter, you should use a prepared statement (although in this case it doesn't matter much since you don't need to sanitize the query)
$connection = new mysqli('localhost','root','pw','db');// start mysqli connection
$results = $connection ->prepare('SELECT Name, Description FROM products');// create the statement you want to work with
(object)array('Name'=>'','Description'=>'');// set up the variables you want to put retrieved data in
$results ->bind_result($res ->Name, $res ->Description);// attach the variables to the prepared statement
while($results ->fetch()){// execute the prepared statement
// perform actions with $res->Name and $res ->Description
}
To answer your first question, it is because mysql_fetch_assoc() only gets one row of data from the result set at a time. Typically, a while loop is used to gather all results like this:
$results = mysql_query("SELECT Name, Description FROM products");
$result_array = array(); // don't name this array the same as your result set ($results) or you will overwrite it.
while($row = mysql_fetch_assoc($results)) {
$result_array[] = $row;
}
I honestly don't know why you would only be echoing out the first letter of each field. Does it just appear that way on screen do to some problem with your HTML construct? In other words if you look at the HTML source, is it shown correctly?
Here is my PHP MySQL query:
$query = "SELECT falsegoto FROM timeconditions WHERE [timeconditions_id] = 0";
$result = mysql_query($query);
There should be only a single result from this query, and I'm not sure how display it in PHP?
mysql_result() seems to only work with larger data sets?
Any help or explanation would be valued.
As Peeha mentiod, your using mysql, but it's better to use mysqli
So the code will then look like this:
$query = "SELECT falsegoto FROM timeconditions WHERE [timeconditions_id] = 0";
$result = mysqli_query($query);
while($row = myslqi_fetch_assoc($result){
// DO STUFF
}
I use this for everything. It just loops through every row in the result. and if there's just one row, it while's only one time....
use it like this :
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
You have to fetch the row, there are a few methods of doing it: mysql_fetch_object, mysql_fetch_row, mysql_fetch_array and mysql_fetch_assoc.
These methods will read a single line from the result and remove it from the handler, so if you loop the call it will read all the rows, one by one until it reaches the end and returns false.
example:
while($obj = mysql_fetch_object($result)){
echo $obj->name;
}
PHP.net documentation:
mysql_fetch_object,
mysql_fetch_row,
mysql_fetch_array,
mysql_fetch_assoc