PHP SQL query to print results in webpage - php

I am trying to get my PHP script to print all rows i have in my database in a neat order. Currently Im not getting anything. My table has 4 columns, Name, Address, Long and Lat, and 2 rows with data. The table is called Locations. I am using the following code but im not getting to to work:
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>

Here is a simple example using pdo instead of mysqli
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS); // create connection
$stmt = $pdo->prepare("SELECT Name, Address, Long, Lat FROM Locations");
//you should never use *, just call each field name you are going to use
$stmt->execute(); // run the statement
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC); // fetch the rows and put into associative array
print_r($arr); // print all array items, unformatted
and you can echo out the data and format it yourself using a for loop like so
for($i=0; $i<sizeof($arr); $i++) { // this will loop through each row in the database. i prefer this method over while loops as testing has shown this is much faster for large scale tables
echo 'Name: ' . $arr[$i]['Name'] . '<br />'; // $arr is the array name, $i is the number of the array item, or iterator, ['Name'] is the field name
echo 'Address: ' . $arr[$i]['Address'] . '<br>';
echo 'Long: ' . $arr[$i]['Long'] . '<br>';
echo 'Lat: ' . $arr[$i]['Lat'] . '<br>';
}
If the names are correct, this would echo out your row ID and row CITY. Just change the names to your field names. If you want further assistance, feel free to ask.
However, if you want to stick with mysqli, give the following code a wirl.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$mysqli = mysqli_connect($dbHOST, $dbUSER, $dbPASS, $dbNAME);
$query = "SELECT Name, Address, Long, Lat FROM Locations";
$result = mysqli_query($mysqli, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
echo 'Name: ' . $row['Name'] . '<br />';
echo 'Address: ' . $row['Address'] . '<br>';
echo 'Long: ' . $row['Long'] . '<br>';
echo 'Lat: ' . $row['Lat'] . '<br>';
}
}
change fieldname to the field you want to display
EDIT: Paste the following code. It will echo out the number of rows. This will tell you if the query statement is correct.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS);
$stmt = $pdo->query("SELECT Name, Address, Long, Lat FROM Locations");
echo $stmt->rowCount();

Fetch query result as associative array and use for each to print all results
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
while($rows = mysqli_fetch_assoc($result)) {
foreach($rows as $key => $val)
{
echo $val;
}
}
}
mysqli_close($con);
?>

Related

PHP Fetch row data from Mysql via ID

I am new to php. I have the following code that auto fetches all the rows and columns from the db. I want to make the script to fetch a particular row using its ID column. for example: www.site.com/view.php?id=22
I am trying to get it work with the $_GET['link']; variable like this:
if (isset($_GET['id'])) {
$result = mysqli_query($connection,"SELECT * FROM $_GET['link']");
} else {
$result = mysqli_query($connection,"SELECT * FROM reservations");
}
But I am unable to get it work.
The complete code is as below:
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT * FROM reservations");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
?>
Any help would be appreciated..
You can do this
Add
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
and change this
mysqli_query($connection,"SELECT * FROM reservations");
to this
$result = mysqli_query($connection, $query);
In the above code I added a bit of security so that if $_GET['id'] is not a valid integer it will revert to query where it fetches all the data. I added that because you should never put $_GET directly into your query.
Here is a your code I have modified it to your requirements
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
//get results from database
$result = mysqli_query($connection, $query);
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
if(isset($_GET['id'])) {
$id = $_GET['id'];
} else {
$id=NULL;
}
$sql = "SELECT * FROM reservations WHERE id = '".$id."'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) == 1) {
dd($row);
} else {
echo "no records found with this id";
}
Hope this script meets your answer

PHP Array ForEach SQL Query

I am trying to use a FOREACH loop to query a database based on each value in the $userid array below. I am also looping through the $grade array as I need the corresponding value for the sql query to then put into a HTML table.
//Decode JSON file to an Object
$json_d = json_decode(file_get_contents("results.json"));
//Provisional Array Setup for Grades
$grade = array();
$userid = array();
foreach($json_d->assignments[0]->grades as $gradeInfo) {
$grade[] = $gradeInfo->grade;
$userid[] = $gradeInfo->userid;
}
//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<table><tr><th>First Name </th><th>Last Name </th><th>Grade </th></tr>";
foreach($userid as $id) {
foreach($grade as $grd) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row["firstname"]. "</td><td>" . $row["lastname"]. "</td><td> " . $grd . "</td></tr>";
}
} else {
echo "ERROR!";
}
}
}
echo "</table>";
mysqli_close($conn);
I have checked the $grade and $userid array and they do contain the correct values however running the PHP file I only get the first record outputted in the table. E.G.
FirstName LastName Grade
Student 1 85
Whereas I need the other 2 records that are supposed to appear.

Insert multiple results into database PHP

This part is for gathering my data through an API.
foreach($result['List'] as $feedback)
{
$date = date_create();
$date_entered = $feedback['DateEntered'];
$time = preg_replace('/[^0-9]/','',$date_entered);
//$comment = $feedback['Text'];
$ListingId = $feedback['ListingId'];
$BuyNowPrice = $feedback['BuyNowPrice'];
$max_bid = $feedback['MaximumBidAmount'];
$SellerId = $feedback['SellerId'];
echo '<div>' . "Seller ID: $SellerId" . " has sold one $ListingId for " . '$' . "$BuyNowPrice" . '</div>';
echo "<div>Feedback created at " . $time . "</div>";
echo '<br>';
}
This part is the code that I used to insert into my results directly after retrieving them.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO tmfeedback '.
'(SellerId,ListingId,BuyNowPrice) '.
'VALUES ('.$SellerId.', '.$ListingId.', '.$BuyNowPrice.'))';
mysql_select_db('dctdb3');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
Only one data is being inserted into the database and it is the last data displayed.
I was wondering how I can change my code so that I can insert all the data at the same time and not repetitive?
Thank you for your help.
Put the insertion inside the loop. Otherwise, the variables just have the last values that were set in the last iteration of the loop.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dctdb3');
foreach($result['List'] as $feedback) {
$date = date_create();
$date_entered = $feedback['DateEntered'];
$time = preg_replace('/[^0-9]/','',$date_entered);
//$comment = $feedback['Text'];
$ListingId = $feedback['ListingId'];
$BuyNowPrice = $feedback['BuyNowPrice'];
$max_bid = $feedback['MaximumBidAmount'];
$SellerId = $feedback['SellerId'];
echo '<div>' . "Seller ID: $SellerId" . " has sold one $ListingId for " . '$' . "$BuyNowPrice" . '</div>';
echo "<div>Feedback created at " . $time . "</div>";
echo '<br>';
$sql = 'INSERT INTO tmfeedback '.
'(SellerId,ListingId,BuyNowPrice) '.
'VALUES ('.$SellerId.', '.$ListingId.', '.$BuyNowPrice.'))';
$retval = mysql_query($sql);
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
}
echo "Entered data successfully<br>";
mysql_close($conn);
Make sure your second block of code is inside your first block of code (place your second block above the right-curly-brace). Then it will occur for each iteration of the foreach loop (each result) and insert a record for each one.
You cannot insert array into database hence place the query inside a loop. This thread may help you alot.

PHP loop through array returned by MySQL function

The code below works fine. However I would like to output the results using a loop. I can do it by going through each key individually or as $post[0] for example but not using a loop to go through all the returned fields. All I get is one value of "Array". It looks like the entire array is inserted into a variable I'm not sure what's going on. I have tried http://www.hackingwithphp.com/5/3/0/the-two-ways-of-iterating-through-arrays. Any suggestions appreciated and also if anyone could explain what is going on that would be great. Thanks.
$ID = $_POST['ID'];
function query($ID){
$servername = "x.x.x.x";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT ID, NAME, POSITION, TELEPHONE_NUMBER, EMAIL FROM GROUP WHERE ID = '$ID'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)){
$resArr[] = $row;
}
return $resArr;
}
$person = query($ID);
foreach($person as $post) {
echo $post['ID'] . "<br>";
echo $post['NAME'] . "<br>";
echo $post['POSITION'] . "<br>";
echo $post['TELEPHONE_NUMBER'] . "<br>";
echo $post['EMAIL'] . "<br>";
}
?>
Its not totally clear what you are asking but I assume you want to loop through the individual fields of the selected rows. As you built an array containing the query results each result itself being an array mysqli_fetch_array($result) then you can just add an inner loop to process the individual row array like so :-
$persons = query($ID);
foreach($persons as $person) {
foreach ( $person as $fieldname => $value ) {
echo $fieldname . '-' . $value . "<br>";
}
}
Group is reserved word of mysql you can use it in backtics ``
$query = "SELECT ID, NAME, POSITION, TELEPHONE_NUMBER, EMAIL FROM `GROUP` WHERE ID = '$ID'";
$result = mysqli_query($conn, $sql);

MYSQL foreach Row Echo Data

How do I echo out every column's data of a row from MYSQL results?
I do not know what the rows are as the query is dynamically created.
Here's what I have:
$query = $_POST['query'];
// Create connection
$con=mysqli_connect($db_host, $db_user, $db_pass, $db_name);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$results = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($results)) {
}
$row is just an array. Like any other array you can do fun things like iterate over it:
while ($row = mysqli_fetch_array($results)) {
foreach ($row as $key => $value) {
echo 'Key: ' . $key . ', Value: ' . $value;
}
echo "<br><br>\n"
}

Categories