How can use foreach loop to loop through the $Result?
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$Query = mysql_query("SELECT * FROM mytable");
$Result = array( );
while ($Row = mysql_fetch_array ( $Query) ) {
$Result [ ] = $Row;
}
mysql_free_result($Query);
print_r ($Result);
?>
I just have very vague idea:
<?php
foreach ($Result )
{
echo $row[fname] . ' ' . $row[lname] . ' ' $row[email];
}
?>
Could someone help please?
Something like the following
foreach($Result as $row){
$fname=$row['fname'];
// etc...
}
why do you want to do the indirect way with that array? you could instead simpply do this:
$Query = mysql_query("SELECT * FROM mytable");
while ($Row = mysql_fetch_array ( $Query) ) {
echo $Row[fname] . ' ' . $Row[lname] . ' ' $Row[email];
}
mysql_free_result($Query);
$link = mysqli_link('host', 'user', 'pass', 'db');
$query = 'SELECT * FROM mytable';
$result = mysqli_query($link, $query)
while ($row = mysqli_fetch_assoc($result)) {
$out .= $row['fname'] . ' ' . $row['lname'] . ' ' . $row['email'];
}
echo $out;
Related
I've compiled the following PHP and HTML, what I want to do is connect my WAMP database to my webpage, it's a simple task but the output i receive is displayed in the picture below, can somebody show me where i went wrong?
<?php
//Step 1
$db = mysqli_connect('localhost', 'root', '', 'hospital') or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>
PHP connect to MySQL
</h1>
<?php
//Step 2
$query = "SELECT * FROM patients";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
while($row = mysqli_fetch_array($result)){
echo $row['id'] . ' ' . $row['patient_name']. ' ' . $row['check_in_date'] . ' ' . $row['room_number'] . ' ' . $row['bed_number'] . ' ' . $row['notes'] . '<br />';
}
?>
</body>
</html>
PHP and HTML error
I have found some errors in that code
$query = "SELECT * FROM patients";
You need to add the semicolon a the end of the query code here, so:
$query = "SELECT * FROM patients;";
Then we have this
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
while($row = mysqli_fetch_array($result)){
echo $row['id'] . ' ' . $row['patient_name']. ' ' . $row['check_in_date'] . ' ' . $row['room_number'] . ' ' . $row['bed_number'] . ' ' . $row['notes'] . '<br />';
}
This should work
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
$patientname = $row['patient_name']; //do this with every variable you have
echo "$id $patientname";
}
EDIT: Also, change this
$db = mysqli_connect('localhost', 'root', '', 'hospital') or die('Error connecting to MySQL server.');
with this
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "hospital";
$db = mysqli_connect($dbhost,$dbuser,$dbpass) or die ("dbconn");
mysql_select_db($dbname,$db) or die ("msq");
You dont need to assign
$row = mysqli_fetch_array($result); as you are assigning it inside the while loop
EDITED ANSWER
Build a sperate array from the rows and then loop over that, this way you will have more flexibility to add to or edit the results before displaying them
//Step 2
$query = "SELECT * FROM patients";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
$rows = array();
while($row = mysqli_fetch_array($result)){
$rows[] = $row;
}
foreach($rows as $r) {
echo $r['id'] . ' ' . $r['patient_name']. ': ' . $r['check_in_date'] . ' ' . $r['room_number'] . ' ' . $r['bed_number'] . ' ' . $r['notes'] . '<br />';
}
This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 12 months ago.
Below are three options to select data from a MySQL database and output it as a json/array. The queries are in mysql though ... how would they look like with new mysqli? All three options should retain.
<?php
// Connect to MySQL
$link = mysql_connect( 'host', 'user', 'password' );
if ( !$link ) {
die( 'Could not connect: ' . mysql_error() );
}
// Select the data base
$db = mysql_select_db( 'database', $link );
if ( !$db ) {
die ( 'Error selecting database \'test\' : ' . mysql_error() );
}
// Fetch the data
$query = "
SELECT category, value1, value2
FROM table
ORDER BY value1 ASC";
$result = mysql_query( $query );
// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die( $message );
}
// Print out rows (Option 1)
while ( $row = mysql_fetch_assoc( $result ) ) {
echo $row['category'] . ' | ' . $row['value1'] . ' | ' .$row['value2'] . "\n";
}
// Print out rows (Option 2)
$prefix = '';
echo "[\n";
while ( $row = mysql_fetch_assoc( $result ) ) {
echo $prefix . " {\n";
echo ' "category": "' . $row['category'] . '",' . "\n";
echo ' "value1": ' . $row['value1'] . ',' . "\n";
echo ' "value2": ' . $row['value2'] . '' . "\n";
echo " }";
$prefix = ",\n";
}
echo "\n]";
// Print out rows (Option 3)
$data = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
$data[] = $row;
}
echo json_encode( $data );
// Close the connection
mysql_close($link);
You would first call the seek function.
while ($row = mysql_fetch_assoc($result)) {
// do stuff with $row
}
mysql_data_seek($result, 0);
while ($row = mysql_fetch_assoc($result)) {
// do other stuff with $row
}
Please see...
http://php.net/manual/en/function.mysql-data-seek.php
I am trying to remove a user from the mailing list right before I perform the emailing to my users. However, the code responsible for this within the second while loop is not executing.
Can somebody see why this is?
<?php
$query = "SELECT * FROM remove_request";
$result = mysqli_query($dbc,$query);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$query = "DELETE FROM mail_table WHERE first_name='" . $row["first_name"]
. "' AND last_name='" . $row["last_name"]
. "' AND email_address='" . $row["email_address"] . "'";
$result = mysqli_query($dbc,$query);
echo $row["first_name"] . ' has been removed from the mail list.';
}
}
$query = "SELECT * FROM mail_table";
$result = mysqli_query($dbc,$query) or die('Error querying database');
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
mail($row["email_address"],$subject,$message,$headers);
echo 'email sent to ' . $row["first_name"] . "\n";
}
}
mysqli_close($dbc);
?>
To clean and tidy-up my code, I want to add multiple tables with the fields:
id
title
description
keywords
link
but I also want them in sections so in MySql I want different tables with categories such as: "News", "Social Networking" and "Shopping", but how can I get that? This is my code:
<?php
if( count($terms) == 0){ // If no terms entered, stop.
echo "No Search Terms Entered.";
}else{
// connect
$connect = mysql_connect("XXX", "XXX", "YYY") or die('Couldn\'t connect to MySQL Server: ' . mysql_error());
mysql_select_db("theqlickcom_774575_db1", $connect ) or die('Couldn\'t Select the database: ' . mysql_error( $connect ));
/* Query Statement Building - Terms together */
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0){
$query .= " AND ";
}
$query .= "keywords LIKE '%{$each}%'";
}
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error( $connect ));
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo '<h2><a class="ok" href="' . $link . '">' . $title . '</a></h2>' . PHP_EOL;
echo '<p class="kk">' . $description . '<br><br><span class="keywords">' . PHP_EOL;
echo '<p><a class="okay" href="' . $link . '">' . $link . '<br><br><span class="keywords">' . PHP_EOL;
}
} else {
/* Query Statement Building - Terms Separate */
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0){
$query .= " OR ";
}
$query .= "keywords LIKE '%{$each}%'";
}
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error( $connect ));
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo '<h2><a class="ok" href="' . $link . '">' . $title . '</a></h2>' . PHP_EOL;
echo '<p class="kk">' . $description . '<br><br><span class="keywords">' . PHP_EOL;
echo '<p><a class="okay" href="' . $link . '">' . $link . '<br><br><span class="keywords">' . PHP_EOL;
}
} else {
echo "No results found for \"<b>{$k}</b>\"";
}
}
//disconnect
}
?>
If you have to search multiple table with one query
1.use mysqli
2.use UNION ALL in query
Join table
use mysql procedure
I am getting error: Invalid argument supplied for foreach()
This is my class for connecting to database:
class dbMySql {
static function Exec($query) {
// open database
$conn = mysql_connect('localhost','root','****');
if($conn == false) {
throw new Exception(mysql_connect_error());
}
mysql_select_db('data',$conn);
$result = mysql_query($query,$conn);
if(is_bool($result) && !$result) {
$error = mysql_error($conn);
mysql_close($conn);
throw new Exception($error);
}
mysql_close($conn);
return $result;
}
}
And I have this code:
echo '{ "results" : [ ';
$gettruck_result = dbMySql::Exec("SELECT id, name, lat, lng FROM data)");
$result_array = array();
foreach($gettruck_result as $row) {
$row_object = '{';
$row_object .= '"id": "' . $row['id'] . '", ';
$row_object .= '"name": "' . $row['name'] . '", ';
$row_object .= '"lat": "' . $row['lat'] . '", ';
$row_object .= '"lng": "' . $row['lng'] . '", ';
$row_object .= '}';
$result_array[] = $row_object;
}
$result_str = implode(", ", $result_array);
echo $result_str;
echo " ] }";
?>
Any idea why am I getting error in foreach loop?
You have to replace:
foreach($gettruck_result as $row) {
... with ...
while($row = mysql_fetch_assoc($gettruck_result)) {
You have checked result array is empty or not..
if(mysql_num_rows($gettruck_result)>0)
{
foreach($gettruck_result as $row) {
.
.
}
}