I've got a database that contains info on some images. The columns are id, name, description, location and visible.
I'm trying to have PHP read in the location column as an array WHERE visible=1, but it's not working. Can anyone see where I'm going wrong?
I know I should be using mysqli, before anyone points this out to me. I will do, once I've got this array syntax sorted out.
My code is below:
<?php
$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("shibby",$con);
$sql = "SELECT location from gallery WHERE visible=1";
$photos= mysql_query($sql,$con);
print_r(mysql_fetch_array($result));
mysql_close($con);
$i = 0;
foreach ($photos as $photo) {
$i = 0;
if ($i < 3) {
echo '<td><center><img src="'.$photo.'.jpg"></td>';
$i++;
} elseif ($i == 3) {
echo '</tr><tr>';
$i = 0;
}
}
Undefined variable 'result' (line 12)
Change
$photos= mysql_query($sql,$con);
print_r(mysql_fetch_array($result));
with
$photos= mysql_query($sql,$con);
print_r(mysql_fetch_array($photos));
Use:
$photos= mysql_fetch_array(mysql_query($sql,$con));
And remove the line:
print_r(mysql_fetch_array($result));
And yes, use PDO or MySQLi :)
Please do NOT USE MYSQL methods on new projects!! Use mysqli or PDO (I prefer the latter as the first one is a PITA to get right)
If you really insist on correcting the existing code, fix the location retrieval as follows:
$result= mysql_query($sql,$con);
while ($row = mysql_fetch_row($result)) {
$photos[] = $row['location'];
}
mysql_fetch_array and mysql_fetch_row only get one row of the results, not the complete set, hence the need for the loop in the above
remove print_r from this line and replace this
mysql_fetch_array($photos); // you had used wrong variable
Related
I am trying to get a single value from database and store it in a variable Here is the structure of my Database
mysql_connect("localhost","root","") or die(mysql_error());;
mysql_select_db("test") or die(mysql_error());
$result = mysql_query('SELECT * FROM names WHERE name = noshair');
while($row = mysql_fetch_array($result));
{
echo $row['course'] . "<p>";
}
When I use the above code it prints all the courses against my name from data base but I want a specific course name to be selected, like there are 5 courses against my name and i just want all of then separately to be saved in separate variable.
Give this query a try:
SELECT DISTINCT name, GROUP_CONCAT(DISTINCT course ORDER BY course) AS courses;
FROM names
WHERE name = noshair
and change your echo statement to this:
echo $row['courses'] . "<p>";
This should output a list of your course like this -> 'java, c#, php, maths' which you could then put in a variable.
Perhaps you should try the query:
SELECT GROUP_CONCAT(course)
FROM names
WHERE name = noshair;
As side notes, you should stop using mysql_ functions (use mysqli_ or some similar interface). And learn to use parameters in your queries.
Why don't you use php foreach statement like these:
foreach ($row['course'] as $key => $value)
{
echo $value;
}
better still you can use the PHP Implode or Explode method to display them separately.
I think you have to excape the matching value for WHERE:
Try this:
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$result = mysql_query("SELECT * FROM `names` WHERE `name` = 'noshair'");
while($row = mysql_fetch_array($result));
{
$courses[] = $row['course'];
}
var_dump( $courses );
The code saves all the contents to an Array.
Use array to save all courses separately.Then the course name will be save in separate indexes of array like $array[0]="math" and $array[1]="english" .Then use the for loop to save each value in separate variables by setting the condition of loop with total number of values in array.Then the courses will be save separately in different variables like $sub1, $sub2 and so on.Try this code
$con=mysql_connect("localhost","root","")
if(!$con)
{
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('test', $con);
if (!$db_selected) {
die ('Can\'t use test : ' . mysql_error());
}
$result = mysql_query('SELECT * FROM names WHERE name = noshair');
while($row = mysql_fetch_array($result));
{
$value=$row['course'] . "<p>";
echo $value;
$array[]=$value;
}
$total=count($array);
for($i=0;$i<$total;$i++)
{
$n=$i+1;
${'sub'.$n} = $array[$i];
}
I'm a PHP and MySQL newbie trying to write a simple query against a table consisting of 2 columns: one with a text string and the second with a date string. The code below returns the first column (the text string) but not the second date string:
<?php
$link = mysql_connect('localhost', 'myuser', 'mypassword');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('archive')or die("cannot select db");
$string = $_POST['keywords'];
$search_query = "SELECT text, date_written FROM archive_table WHERE text LIKE '%$string%'";
$result = mysql_query($search_query,$link);
$rows = mysql_num_rows($result);
if ($rows == 0) {
echo "sorry, I haven’t written about ".$string." yet.";
}
$count = 0;
while ($count < $rows) {
echo mysql_result($result, $count);
echo "\n\n";
$count = $count + 1;
}
mysql_close($link);
?>
I've tried the following code to replace "echo mysql_result($result, $count);", but it returns nothing at all:
echo mysql_result($result['text'], $result['date_written'], $count);
I'm hoping it's a fairly simple syntax blunder that is easily fixed. Thanks in advance!
Don't use the mysql_* functions, as they're deprecated and not safe. Use either MySQLi or PDO
You also need to fetch your results:
$query = "blah"
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
echo "{$row['text']}, {$row['date_written]}";
}
I'm pretty sure this
echo mysql_result($result['haiku_text'], $result['date_written'], $count);
should be
echo mysql_result($result['text'], $result['date_written'], $count);
You have a prefix in front of the text field but it doesn't have one when you select it.
this is only my second question so please be gentle, I am new to PHP.
I have written a statement that queries a database, then checks a file to see if the relevant is present before creating a div to put the image into. The problem is that the output creates divs for rows that have no images.
$query = "SELECT vehicle_make_logo FROM vehicle_makes";
$result = mysql_query($query);
if(!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0; $j < $rows; ++$j)
{
$row = mysql_fetch_row($result);
$image = 'images/vehicleBrands/'.$row[0];
if(file_exists($image)){
echo '<div class="component"><img class="icons" src="images/vehicleBrands/'.$row[0].'"></div>';
}
}
I have tried adding an empty else-statement, but that didn't do anything.
Any help would be greatly appreciated.
Another possibility for what is happening is that your DB table has rows in there which haven an empty field for verhicle_make_logo, at which point your if statement is checking if that folder exists, which it obviously does. If you are certain this is not the case ignore the below, if it is then this might be a solution.
<?php
$query = "SELECT vehicle_make_logo FROM vehicle_makes";
$result = mysql_query($query);
if(!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0; $j < $rows; ++$j)
{
$row = mysql_fetch_row($result);
$image = 'images/vehicleBrands/'.$row[0];
if(!empty($row[0]) && file_exists($image)){
echo '<div class="component"><img class="icons" src="images/vehicleBrands/'.$row[0].'"></div>';
}
}
A browser can never overwrite PHP code because it never sees the PHP code. A browser will only render exactly what the PHP code passes to it. In the case where IE creates extra div tags, it could be that your HTML is malformed and IE tries to normalise it and creates extra divs in the process to close off some open tags that you may have overlooked.
Try copying the view-source code of the page and run it through a HTML validator to see.
Do not ever think for a minute that, Whatever kind of Browser you are using can actaully influence the way how PHP behaves. Because, it Can not! It may seem that way to you, because sometimes, the HTML tags/codes... outputted/echo'ed by your PHP script may be rendered in a different way, according to the browser type you are using, specially by IE, because it sucks. Now, to get back to your code, try this
<?php
$query = "SELECT vehicle_make_logo FROM vehicle_makes";
$result = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($rows) > 0) {
for($j=0; $j < count($rows); ++$j){
$row = mysql_fetch_row($result);
$image = 'images/vehicleBrands/'.$row[0];
if(file_exists($image)){
echo '<div class="component">
<img class="icons" src="images/vehicleBrands/'.$row[0].'"></div>';
}
}
}else {echo 'No record found';}
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.
I have a while loop running that is returning values from a MYSQL table. It returns about 90 entries from the query. My hope is to be able to break these 90 values up and display them in groupings of 5. This may sound confusing so let me share some code samples to help clarify:
$con = mysql_connect("host", "username", "password") or die ("Unable to connect to server");
mysql_select_db("database") or die ("Unable to select database");
$sql = mysql_query("SELECT * FROM `table` WHERE column IS NOT NULL AND column <> ''");
Here I am pulling the values out that I need from the table...
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$column=$row['column'];
echo $id . '<br>';
echo $column . '<br>';
}
At this point, I have run the loop and get the display of all 90 entries. How can I pull the values out and display them in smaller chunks? If I use the looped values outside of the while loop, it just gives me the last value from the set. Is there a simple way to use the unique $id value from the column to get a specific grouping within the loop?
This will add more br's and a hr after each 5 records:
$cnt = 0;
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$column=$row['column'];
echo $id . '<br>';
echo $column . '<br>';
if($cnt % 5 == 0) echo "<br><br><hr><br><br>";
$cnt++;
}
Here is one (not very sophisticated) approach you could take:
$group_size = 5;
$tracking_variable = 0;
while ($row = function_to_fetch_row()) {
if ($tracking_variable == 0) {
// logic for the start of a grouping
}
// logic to display the row
$tracking_variable = ($tracking_variable + 1) % $group_size;
if ($tracking_variable == 0) {
// logic for the end of a grouping
}
}
if ($tracking_variable > 0) {
// logic for the end of the final grouping
}
You want to save this data in a variable, and reference it outside of the loop.
Try this:
$data = array();
while($row=mysql_fetch_array($sql))
{
$data[$row['id']] = $row['column'];
}
And now you can just display specific rows:
print $data[$someRow];