Jump to content

Display help with php mysql


renfley

Recommended Posts

hey just curious if i could pull this off some how

<?php

$con = mysql_connect("localhost","root","");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }

 

mysql_select_db("database", $con);

 

$result = mysql_query("SELECT title FROM table1");

 

foreach($result)

{

?>

<div><?php echo title; ?> </div>

 

<?php

mysql_close($con);

?>

 

Basicly im trying to query the database and foreach result display it within divs? ive been trying to figure it out for a while and im stuck any help would be awsome

thanks

 

Link to comment
https://forums.phpfreaks.com/topic/245534-display-help-with-php-mysql/
Share on other sites

http://php.net/manual/en/function.mysql-fetch-row.php

 

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("database", $con);

$result = mysql_query("SELECT title FROM table1");

while($row = mysql_fetch_array($result)){
$title = $row['title'];

echo "<div>".$title."</div>";

}
mysql_close($con);
?> 

im trying to avoid this

 

echo <div></div>

echo <div></div>

echo <div></div>

echo <div></div>

echo <div></div>

echo <div></div>

echo <div></div>

echo <div></div>

echo <div></div>

echo <div></div>

echo <div></div>

echo <div></div>

echo <div></div>

echo <div></div>

 

lol

@renfley,

 

You were trying to use a foreach loop on the reference ID for a database result set. You need to create a loop (typically a while() loop) to extract each record one at a time and then display/process the data however you want. QuickOldCar gave you a solution in Reply #2. I *think* your reply, in Reply #5, was to prevent having to have multiple echo statemetns - one for each record rather than having empty values displayed. Unless, of course, you have empty values in your database.

 

@QuickOldCa; Why define a variable $title just to use it one time?

$title = $row['title'];

echo "<div>".$title."</div>";

 

This would be easier

$title = $row['title'];

echo "<div>{$row['title']}</div>";

 

 

Anyway, here is what I would do (based off of QuickOldCar's script)

//Connect to Database
$con = mysql_connect("localhost","root","");
if (!$con)
{
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);

//Create and run query
$query = "SELECT title FROM table1";
$result = mysql_query($query) or die("Query:<br>{$query}<br>Error:<br>" . mysql_error());

//Output results
while($row = mysql_fetch_assoc($result))
{
    echo "<div>{$row['title']}</div>\n";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.