Echo each record of a query result - php

I'm attempting to extract some data from a database and echo each result. The code below is code that I took from a textbook and then tried to modify to fit my own website that is hosted locally. I cannot see where I'm going wrong, no error messages are shown, just a blank screen when I run the scrip.
<?php #script 9.4 view top 5 recipients
// This script exctracts data from db and then displays each record in a table
DEFINE('SYSPATH','FOO');
require '../application/config/database.php';
require 'mysqli_connect.php';
$q = "SELECT alert_recipient as NAME
FROM alert
LIMIT 5;
";
$r = mysqli_query($dbc,$q);
// $dbc database connection comes from required mysqli_connect.php
if($r)
{
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo $row['name'];
}
}
else {
echo "<p>ERROR</p>".mysqli_error($dbc);
}
?>

The code looks okay except for your echo $row['name'];, note that you are selecting NAME, uppercase.
Change your echo statement to be:
echo $row['NAME'];
because field names quoted within $row array are case sensitive.

(Can't comment yet)
Maybe the script works but there is no results to display. Check your database.

Related

$_GET doesn't work in my program and no lines beneath it are executed

I am trying to add a function to my website where it will add filters to a SQL select statement by allowing the user to enter text in some text boxes and clicking the filter button.
I haven't gotten as far as that because I'm having issues with the $_GET function.
The idea is that if the query parameters are set, it will use them in the sql statement and if not, it will just return all the rows.
Below is the displayListings function which is called every time the page is loaded.
Although I'm showing the whole function, I havent implemented most of it because nothing works past the line where I use $_GET.
<?php
function displayListings() {
global $dbConnection;
//checks if the query parameters exist
if (isset($_GET['title'])) {
echo 'got here... :F';//for debugging
var_dump($_GET['title']);//for debugging
$title_filter = $_GET('title');// THIS IS THE LINE THAT THE SCRIPT STOPS AT
var_dump($title_filter);//for debugging
}
//checks if the query parameters exist
if (isset($_GET['artist'])) {
$artist_filter = $_GET('artist');
echo $artist_filter."/n";
}
//checks if the query parameters exist
if (isset($_GET['release'])) {
$release_filter = $_GET('release');
echo $release_filter."/n";
}
echo 'here!';
// connect to the database
if (!connectToDb('musiconline')) {
$_SESSION['errorMsg'] = "Sorry, we could not connect to the database.";
header('location:listItem.php');
exit();
}
// after this point we have an open DB connection
// gets the current highest ID so we know what the next should be.
$sqlQuery = "SELECT listingid, recordtitle, artist FROM vinyl";
$result = $dbConnection->query($sqlQuery);
if (!$result) {
$_SESSION['errorMsg'] = "There was a problem with the database: " . $dbConnection->error;
closeConnection();
header('location:listItem.php');
exit();
}
//gets the results and puts them in a rows array
while($row = $result->fetch_array()){
$rows[] = $row;
}
//iterates through each row of the results (each vinyl)
foreach($rows as $row){
$listingID = $row['listingid'];
$recordTitle = $row['recordtitle'];
$artist = $row['artist'];
echo '
<div class="listing">
<table class="tableception">
<tr><td><img src="uploads/vinyl'.$listingID.'.png" alt="img1" ></td><td>
<table class="listing-table">
<tr><td>Album title: </td><td>'.$recordTitle.'</td></tr>
<tr><td>Artist name: </td><td>'.$artist.'</td></tr>
</table>
</td></tr>
</table>
</div>
' . "\n";
}//END OF FOREACH
/* free result set */
$result->close();
/* close connection */
closeConnection();
}
?>
When I debug the page in my IDE, everything works fine, probably because there are no query parameters in the URL.
The page stops loading after the $_GET line, as seen below.shows screenshot of browser when query parameters exist in URL.
I just cant figure out what I'm doing wrong.
Thanks in advance.
I used curly brackets instead of square brackets in the line.
I had $title_filter = $_GET('title');
instead of $title_filter = $_GET['title'];
Thanks #AymDev for pointing this out to me!

Use PHP to generate from an existing database for each row a new specific HTML that i already made

First I'm hitting on a wall here and I really could use your help. I coded the database so I have it all up and working plus all the data inside. I worked the HTML and the CSS media print query and I have it how I want it to look exactly. All I have to do now is:
for every row of the mysql select table I have to fill every specific input form
of the html page I made and print it
Can someone give me a hint of how I can do that?
Assuming you want to connect to your database and simply fetch the id you can do the following.
Ensure you change my_host, my_user, my-password, my_databse,my_tablewith your configuration settings. Then if you want to fetch anything else thanid` just change it to the column name you are looking for.
Be aware we are using PHP here.
// Open Connection
$con = #mysqli_connect('my_host', 'my_user', 'my-password', 'my_databse');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
// Some Query
$sql = 'SELECT * FROM my_table';
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
echo $row['id'];
}
// Close connection
mysqli_close ($con);
Check this link to get a in-depth explanation.
You can do this with two pages. One page gives you the overview and the other page gives you a print preview of your invoice.
The overview:
// DB select stuff here
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n";
echo " <td>".htmlspecialchars($row['what'])."</td>\n";
echo " <td>".htmlspecialchars($row['ever'])."</td>\n";
echo " <td>Detail</td>\n";
echo "</tr>\n";
}
The detail page:
$sql = 'SELECT your, columns FROM tab WHERE id = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo "There is no data for the given Id\n";
return;
}
echo "What: ".htmlspecialchars($row['what'])."<br />\n";
echo "Ever: ".htmlspecialchars($row['ever'])."<br />\n";

My array won't echo a value for some reason

I have a database that holds thousands of structures. The structures are searchable by choosing the "area" first, then selecting the "block_number". My first page allows the user to select the area, the area is then passed through the url to the next page. The next page uses php to pull up the blocks in that area. I'm trying to echo the "area" and "block_number" in the results. The my query works just fine but, for some reason I can't display the "area" in the results. See the code below.
<?
include("conn.php");
include("pl_header.php");
$area = mysql_real_escape_string($_GET['area']);
$wtf = '$area';
?>
<h3>Choose A Block Number in<br> <?=$area?></h3><br>
<center>
<?php
$tblWidth = 1;
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
$i = 1;
// Check to see if any results were returned
if(mysql_num_rows($sql) > 0){
echo '<div class="redBox extraIndent">';
// Loop through the results
while($row = mysql_fetch_array($sql)){
echo ''. $row['area'] .''. $row['block_number'] .'';
if($i == $tblWidth){
echo '';
$i = 0;
}
$i++;
}
echo '';
}else{
echo '<br>Sorry No Results';
}
?>
</div>
</body>
</html>
My issue is where you see '. $row['area'] .' displays nothing, but the '. $row['block_number'] .' works just fine.
Your query is only selecting block_number.
Try changing:
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
To:
$sql = mysql_query("SELECT DISTINCT block_number, area FROM platform_locations WHERE area='$area'");
Edit: If you have this issue in the future try var_dump($row); to see what the array contains. This would show you that you only have access to the block_number and not the area.
Double edit: I didn't notice, but the other answer is right about the $area var- you've already got the $area saved, use that variable instead of the return from the DB as it's already in memory. If this could change per record, it'd be prudent to use the record's area variable to make your code more reusable. However, in this particular case, your SQL statement has the area in the where clause, so it wont vary unless you attempt to use portions of this code elsewhere.
Your SQL query is only selecting block_number, so that's the only field that will be in the $row array. You've already got area as a variable $area so use that, not $row['area'].

How to select certain fields from table in mySQL using PHP

I'm trying out my hand at php at the moment - I'm very new to it!
I was wondering how you would go about selecting all items from a mySQL table (Using a SELECT * FROM .... query) to put all data into an array but then not displaying the data in a table form. Instead, using the extracted data in different areas of a web page.
For example:
I would like the name, DOB and favorite fruit to appear in one area where there is already say 'SAINSBURYS' section hardcoded into the page. Then further down the next row that is applicable to 'ASDA' to appear below that.
I searched both here and google and cant seem to find an answer to my strange questions! Would this involve running the query multiple times filtering out the sainsburies data and the asda data where ever I wanted to place the relevant
echo $row['name']." ";
echo $row['DOB']." "; etc etc
next to where it should go?
I have got php to include data into an array (I think?!)
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['DOB']." ";
echo $row['Fruit']." ";
}
?>
Just place this (or whatever your trying to display):
echo $row['name']." ";
Anywhere you want the info to appear. You can place it within HTML if you want, just open new php tags.
<h1>This is a the name <?php echo $row['name']." ";?></h1>
If you want to access your data later outside the while-loop, you have to store it elsewhere.
You could for example create a class + array and store the data in there.
class User {
public $name, $DOB, $Fruit;
}
$users = new array();
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$user = new User;
$user->name = $row["name"];
$user->DOB = $row["DOB"];
$user->Fruit = $row["Fruit"];
$users[$row["name"]] = $user;
}
Now you can access the user-data this way:
$users["USERNAME"]->name
$users["USERNAME"]->DOB
$users["USERNAME"]->Fruit

PHP get some data from database then echo it out into a JS file

MYSQL table structure:
id , name , status , color
how can i use PHP to get some data from my database(mysql) ,the php script will look for table rows that have "good" in the "status" column. Then echo those rows which have good in status(P/S out into a JS file. It also get the color from each row (with status=good) and ptu it into javascript(jQUery)
I did a little research on how to use php to generate javascript.
Here's a php script, it's not working btw:
<?php
header("content-type: application/x-javascript");
include 'connect.php';
$sql = "SELECT * FROM users WHERE status ='good'";
$query = mysql_query($sql)or die(mysql_error());
$rows = array();
while($row = mysql_fetch_array( $query )){
$rows[] = $row;
echo "$('a[href*=\"row[username]\"]').css('color', 'row[color]');\n";
}
?>
The out put is (which wont work):
$('a[href*="row[username]"]').css('color', 'row[color]');
The connect.php is working(connects to database) , just the script is not working.
(BTW: The file name of this is usercolor.js.php , is it correct?)
I hope someone could guide me.
Thanks and have a wonderful day.
echo "$('a[href*=\"row[username]\"]').css('color', 'row[color]');\n";
won't work. Try
$username = $row['username'];
$color = $row['color'];
echo "$('a[href*=\"$username\"]').css('color', '$color');\n";
or
echo "$('a[href*=\"{$row['username']}\"]').css('color', '{$row['color']}');\n";
see the manual for an explanation. Also, according to your mysql table structure, the column is called name and not username.

Categories