Max Njoroge Max Njoroge - 1 year ago 79
PHP Question

Iterate through fetched SQL data

I am adding a database to my event website with the webpages mon-sun each with its own SQL table. Each page can have any number of events. The table has 6 columns (ID,name,club,location,host,description). Currently I am using a tiresome method to call the data. I'm looking for an addition to my code so that calling the data is a bit more automated. My code so far.

$dbhost = 'localhost';
$dbname = 'events';
$dbuser = 'max';
$dbpass = '';
$appname = "Dundaah";

$connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) die($connection->connect_error);

function queryMysql($query)
global $connection;
$result = $connection->query($query);
if (!$result) die($connection->error);
return $result;
$row = queryMysql("SELECT * FROM monday WHERE ID=1");
$one = $row->fetch_array(MYSQLI_ASSOC);
$row2 = queryMysql("SELECT * FROM monday WHERE ID=2");
$two = $row2->fetch_array(MYSQLI_ASSOC);


Then to call for the first event I use.

<?php echo ucwords(strtolower($one['name']));?>
<?php echo ucwords(strtolower($one['club']));?>
<?php echo ucwords(strtolower($one['location']));?>
<?php echo ucwords(strtolower($one['host']));?>
<?php echo ucwords(strtolower($one['description']));?>

For the second event I use the same method but I'm looking for a way to loop through instead of declaring a new fetch array every time. Thank you.

Answer Source

Got it.

$query = "SELECT * FROM events WHERE day='mon'";

$result = $conn->query($query);
if (!$result) die($conn->error);

$rows = $result->num_rows;
$j = 0;


while ($j < $rows )
$row = $result->fetch_array(MYSQLI_ASSOC);

$event_name = $row['name'];
$event_club = $row['club'];
$event_location = $row['location'];
$event_host = $row['host'];
$event_description = $row['description'];



echo $name_array[0];
echo $club_array[0];
echo $location_array[0];
echo $host_array[0];
echo $description_array[0];

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download