MySQL Show Message If ID Entries Not Found - php

My original question was not clear enough. SO I'll attempt to give more information. I have a page that pulls data from a database using PHP (default.php). I built this page so that, based on the 'ID' - the content will change on the page. This is because I will have 100+ entries. I don't want to create 100 individual pages since the only the content will be changing.
Example:
https://mywebsite.com/default.php?id=xxxxx1
https://mywebsite.com/default.php?id=xxxxx2
https://mywebsite.com/default.php?id=xxxxx3
etc...
My table have columns for each row including:
'id'
'name'
'image'
'nominations'
etc...
The 'default.php' page is a template that has the following code:
In the header:
<?php
include_once '../dbh.php';
$id = $_GET['id'];
?>
And in the body for each of the columns above:
<?php
$sql = "SELECT nominations FROM channel_info";
$result = mysqli_query($conn, "SELECT nominations FROM channel_info WHERE id='$id'");
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0){
while ($row = mysqli_fetch_assoc($result)) {
echo $row['nominations'];
}
} else {
echo "<p>Sorry. No nominations listed. </p>";
}
?>
etc..
Currently the messages does NOT show when columns in the same row of the table is empty. How can I make this message show so that if it's empty it will display a message? This happens to all the data entries.
Empty column: [screenshot] prnt.sc/tkcw80
Page displa: [screenshot] http://prntscr.com/tk54iv

I'll try to help you but first, could you please tell me what $id is referring to ? $_GET ? $_POST ? ...
it could be a security issue.
So, if you would like to connect to your database I would suggest you to use PHP PDO like so :
define('user', "HERE_YOUR_USER");
define('password', "HERE_YOUR_PASSWORD");
define('DB_name', "HERE_YOUR_DATABASE_NAME");
// REPLACE "localhost:8889" WITH YOUR SERVER:PORT
define('DB_server', "localhost:8889");
try {
$connect = new PDO("mysql:host=".DB_server.";dbname=".DB_name, user, password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
var_dump($e->getMessage());
}
Then, you would like to make a request :
$results = $connect->prepare("SELECT nominations FROM channel_info WHERE id='$id'");
if ($results->execute()) {
while ($r = $results->fetch(PDO::FETCH_ASSOC)) {
echo $r['nominations'];
}
} else {
echo "<p>Sorry. No nominations listed. </p>";
}
Let me know if you have any question about it :)

Related

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";

Select data from MySQL DB based on the URL example (www.example.co.uk/essex.php)

I am very new to php and I am looking to create dynamic pages.
Basically If a person lands on www.example.co.uk/essex.php I would like to be able to add something like <h1>Company In <?php echo $row['County']; ?> so that it would show
Company In Essex when Live and save time if I need to duplicate the page for another county or town.
So far I have setup a database in phpmyadmin
Picture of Table
My code so far to grab the table is;
$dbconnect = mysqli_connect("HOST", "USER", "PASSWORD", "DB");
if(mysqli_connect_errno()) {
echo "Connection Failed:".mysqli_connect_error();
exit;
}
$count_sql="SELECT * FROM areas";
$count_query=mysqli_query($dbconnect, $count_sql);
$count_rs=mysqli_fetch_assoc($count_query);
and then on www.example.co.uk/essex.php
<?php
do {
echo $count_rs['County'];
} while ($count_rs=mysqli_fetch_assoc($count_query))
?>
But where I have gone wrong is it pulls all the data from the table for County where I only wish it to pull the county of Essex.
Please forgive me for explaining this badly.
UPDATE -
$row = url2content();
extract($row);
function url2content($url = NULL){
if(is_null($url)){
if(isset($_SERVER["REQUEST_URI"]) && $_SERVER["REQUEST_URI"]){
$url = $_SERVER["REQUEST_URI"];
}elseif(isset($_SERVER["PATH_INFO"]) && $_SERVER["PATH_INFO"]){
$url = $_SERVER["PATH_INFO"];
}
if (substr($url,0,1) == '/'){
$url = substr($url,1);
}
}
if (DEBUG_MODE){
echo ('URL requested: "'.$url.'"<br>');
}
function get_towns($county){
$query = sprintf("select townName from " . AREAS_TABLE . " where countyName = '%s' order by rand() LIMIT 0,24" ,mysql_real_escape_string($county));
$res = mysql_query($query);
if(!$res){
printf("Unable to query ".AREAS_TABLE." table: %s \n", mysql_error());
}
$html="";
while($row = mysql_fetch_assoc($res)){
$html.="<li>".stripslashes($row["townName"])."</li>\n";
}
return $html;
}}
You have to use WHERE clause in your query in order to select a specific country from your db
SELECT * from table WHERE felid_country=$count_rs['County'];
You can use strpos() to match the County (eg.essex) with url $_SERVER['REQUEST_URI'] (eg.www.example.co.uk/essex.php) in your case.
Just like this
<?php
do {
if(strpos($_SERVER['REQUEST_URI'],$count_rs['County'])!=false)
echo $count_rs['County'];
} while ($count_rs=mysqli_fetch_assoc($count_query))

How to use names instead of id's in dynamic webpages

I just started learning php and mysql and i might already be way ahead of myself. The thing i would like to create is a webpage where ppl can sign up for an event, so far so good, the form to submit their first name, last name, age and email adress is working and its actually sending te information to the database.
Next thing i want to create is a page where i can display all the database records submitted (except for the email adress). This is also working, but I wanted to play around with dynamic urls.
When i visit my page http://www.example.com/ppl.php?id=1 i get the information of the first database record displayed but i also wanted to see if i could get this to work with names instead of ids so i tried to edit my code and use http://www.example.com/ppl.php?name=john this does only return an error and however there are a few people called john in the database no records are displayed.
So i would like to know if what i want is actually possible and how do i get this to work with my current code.
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "event";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_GET['id'];
$firstname = 'firstname';
$lastname = 'lastname';
$age = 'age';
$sql = "SELECT * FROM people WHERE id = $id";
$result = $conn->query($sql);
echo "<table id='display' width='600' align='center'>";
echo"<tr><td> Firstname</td> <td> Lastname</td> <td> Age</td>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo"<tr><td width='33%'> $row[$firstname]</td> <td width='33%'> $row[$lastname]</td> <td width='33%'> $row[$age] cm</td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Try to change the query:
$sql = "SELECT * FROM people WHERE id = $id";
To:
$name = $_GET['name'];
$sql = "SELECT * FROM people WHERE name LIKE '%$name%'";
Then echo for each one John you find.
Also consider using CSS like this.
<style>
#display {
width: 600px;
}
#display td {
width: 33%;
}
</style>
You should be looking for two separate $_GET keys: id OR name.
<?php
if (isset($_GET['id'])) {
// logic to get row by ID
} elseif (isset($_GET['name'])) {
// logic to get row by Name
} else {
// logic if no $_GET keys are set
}
I would recommend not using the name field for a find because it's not a primary key in your database - it may not be unique. Your query may return multiple results depending on what data is being stored.
Edit: To answer the question of where to place this in the code sample above, consider placing it where the query string is declared.
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM people WHERE id = $id";
} elseif (isset($_GET['name'])) {
$name = $_GET['name'];
$sql = "SELECT * FROM people WHERE name = '$name'";
}
From there you can keep the same query execution logic. But as I stated, I'd advise against using the name field as a key because it may not be unique.

How can I SELECT field FROM table WHERE id=variable?

I have a variable of the logged in user ($steamid) that I need to use to select and echo specific fields from the database. I am using the following code, but it is working incorrectly. All database info is correct, the tables, columns, and variables are not misspelled. Not sure what I'm doing wrong.
<?php
$con=mysqli_connect("private","private","private","private");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT `bananas` FROM `es_player` WHERE `steamid` = '$steamID'";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
printf("bananas: %n",$fieldinfo->bananas);
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
No errors are shown, it simply returns "bananas:" with nothing after it. I feel like I didn't to it correctly, does anyone know what I might've done wrong? Here is a screenshot of my database table so you know what it looks like http://puu.sh/gCY3d/983b738458.png.
Try this:
$query = Mysqli_Query($con, "SELECT * FROM `es_player` WHERE `steamid`='$steamID'") or die(mysql_error());
if( ! mysqli_num_rows($query) )
{
echo 'No results found.';
}
else
{
$bananas_array = mysqli_fetch_assoc($query);
$bananas = $bananas_array['bananas'];
echo 'Number of bananas: '. $bananas;
}
If this doesn't work, there is a problem with STEAM_ID format. You could try triming the IDs to be JUST a number, and add the STEAM_x:x: to it later.

Echo each record of a query result

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.

Categories