Displaying results in a search table (PHP) - php

This has probably been asked before, please feel free to link me or whatever, I just couldn't find exactly what I'm after.
It's pretty simple, I need to display the results of a search form. That part is easy and I can get that to work. What I'm having trouble with is when no results match what the user searched.
I'm fairly certain I need to just use an IF statement but I'm not very experienced with PHP and cannot figure out how to correctly display the code.
This is what I have so far:
$query = "SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'";
if (!$query)
{
echo "No results found in the database. Please go back and search again.";
}
My question is: How do I get the 'No results found...' message to display when the users search doesn't match anything in the database?
NOTE - I get very confused very quickly when it comes to trying to understand certain terms within PHP and SQL so please try to explain your answer like you would to an absolute beginner.
Many thanks in advance.

You want to show the "No results found"-message when no rows are found in the database table.
To do this, you can use below PHP and SQL code:
$sql = "SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'";
$query = $db->prepare($sql);
$query->execute();
$rows = $query->fetch(PDO::FETCH_NUM);
if($rows[0]) {
// Row exists
} else {
echo "No results found in the database. Please go back and search again.";
}
Note that the above answer is vulnerable to SQL injection attacks.
To prevent SQL injection attacks, it is recommended that you prepare and bind all user-submitted data, here is a better example that shows how SQL injection attacks can be prevented: (full example, including database connection)
$db = new PDO($dsn);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $db->prepare("SELECT * FROM search WHERE isbn=:isbn OR bookname=:bookname OR author=:author OR category=:category");
$query->execute([ ':isbn'=>$isbn, ':bookname'=>$bookname, ':author'=>$author, ':category'=>$category ]);
$rows = $query->fetch(PDO::FETCH_NUM);
if($rows[0]) {
// Row exists
} else {
echo "No results found in the database. Please go back and search again.";
}

Assuming you are using Mysqli ,
//connect with mysql
$conn = mysqli_connect("localhost", "user", "password", "db");
//here is the query
if($result = mysqli_query($conn,"SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'")){
if(mysqli_num_rows($result) > 0){
//mysqli_num_rows() returns the number of rows in a result .
//when it is greater than zero, it has some results
}
else{
echo "No results found in the database. Please go back and search again.";
//Do something if no results returned
}
}
//finally free the results
mysqli_free_result($result);
mysqli_close($conn);

Related

MySQL Row Isn't Found But It's There

I'm using PHP to try and select a single row from a table in my MySQL database. I've run the query manually inside phpMyAdmin4 and it returned the expected results. However, when I run the EXACT same query in PHP, it's returning nothing.
$query = "SELECT * FROM characters WHERE username=".$username." and charactername=".$characterName."";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_row())
{
echo $row[0];
}
$result->close();
}
else
echo "No results for username ".$username." for character ".$characterName.".";
And when I test this in browser I get the "No results..." echoed back. Am I doing something wrong?
This isn't a duplicate question because I'm not asking when to use certain quotes and backticks. I'm asking for help on why my query isn't working. Quotes just happened to be incorrect, but even when corrected the problem isn't solved. Below is the edited code as well as the rest of it. I have removed my server information for obvious reasons.
<?PHP
$username = $_GET['username'];
$characterName = $_GET['characterName'];
$mysqli = new mysqli("REDACTED","REDACTED","REDACTED");
if(mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM `characters` WHERE `username`='".$username."' and `charactername`='".$characterName."'";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_row())
{
echo $row[0];
}
$result->close();
}
else
echo "No results for username ".$username." for character ".$characterName.".";
$mysqli->close();
?>
It's failing: $mysqli = new mysqli("REDACTED","REDACTED","REDACTED"); because you didn't choose a database.
Connecting to a database using the MySQLi API requires 4 parameters:
http://php.net/manual/en/function.mysqli-connect.php
If your password isn't required, you still need an (empty) parameter for it.
I.e.: $mysqli = new mysqli("host","user", "", "db");
Plus, as noted.
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
Footnotes:
As stated in the original post. Strings require to be quoted in values.
You need to add quotes to the strings in your query:
$query = "SELECT *
FROM characters
WHERE username='".$username."' and charactername='".$characterName."'";

MYSQL & PHP News System [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have this news system but I can't figure out how to do it like this: news.php?id=1 then it will output the news id 1. Please help.
I have this so far:
<?php
include_once('includes/config.php');
if($id != "") {
$id = mysql_real_escape_string($id);
$sql = mysql_query("SELECT * FROM news WHERE id = '$id'");
}
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)){
if(isset($_GET['id']));
echo $res['body'];
}
?>
It connects to the database (details are stored in the config).
the parameters after the ? in the URL are GET items. Use this:
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
// Rest of your code
}
<?php
include_once('includes/config.php');
// see if the id is set in the URL (news.php?id=)
if(isset($_GET['id'])) {
// get the ID from the URL
// to make it safer: strip any tags (if it's a number we could cast it to an integer)
$id = strip_tags($_GET['id']);
// don't use SELECT *, select only the fields you need
$sql = mysql_query("SELECT body FROM news WHERE id=".mysql_real_escape_string($id));
while($row = mysql_fetch_assoc($sql)) {
echo $res['body'];
}
} else {
echo 'please select an article';
}
I would recommend you get away from using the mysql functions and use mysqli instead, as mysql is depreciated and you'll have to learn mysqli or PDO anyway.
Edit: updated code per comments
Firstly lets dissect your current code, to see where your going wrong.
<?php
include_once('includes/config.php');
/*
$id is not set anywhere before its used so this if statement will not fire,
if you are attempting to get this $id from a url parameter then you need
to set it first from $_GET['id'] global
*/
if($id != "") {
$id = mysql_real_escape_string($id);
$sql = mysql_query("SELECT * FROM news WHERE id = '$id'");
}
/*
This piece of code will fire but where is $sql set?
The mysql_query() function expects a string containing your sql query
so the subsequent lines of code will fail because of this
*/
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)){
//this block is in the wrong place
if(isset($_GET['id']));
echo $res['body'];
}
?>
The idea is to get the user input E.G the $_GET['id'] from the url first, check the value is what your looking for, and then build your query.
As the mysql_* functions are deprecated I will show you an example using PDO. Though you can use mysqli, BUT you must always use prepared query's whenever user values come into contact with your database. This is to stop nasty/accidental sql injections.
<?php
// make the connection to the database using PDO
try {
$db = new PDO('mysql:host=127.0.0.1;dbname=the_awsome_db', 'yourusername', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->exec("SET CHARACTER SET utf8");
} catch(PDOException $e) {
exit('Sorry there is a problem with the database connection :' . $e->getMessage());
}
// sanitize user input - expecting an int
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
if (is_numeric($id)) {
// now lets query the database with the param id from the user
// prepare the query, using a placeholder
$stmt = $db->prepare('SELECT body,
some_other_column
FROM news
WHERE id = :placeholder_id');
// bind the placeholder with the value from the user
$stmt->bindParam(':placeholder_id', $id);
// execute the prepared query
$stmt->execute();
// fetch the result
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// result not empty - display
if (!empty($result)) {
// display your result, use print_r($result) to view the whole result set if unsure
echo $result['body'];
} else {
// no matching id found in the db, do something
echo 'No results found';
}
} else {
// do something as user input is not a number
exit(header('Location: ./index.php'));
}
?>
Hope it helps, if your unsure of getting parameters from the user you may need to look up some more tutorials and get the hang of that first before dabbling with databases and all that good stuff.

Basic MySQL help? - submitting data

I've been getting better at PHP - but I have NO idea what I'm doing when it comes to MySQL.
I have a code
<IMG>
I need to grab the "for", "affi" and "reff" and input them into a database
//Start the DB Call
$mysqli = mysqli_init();
//Log in to the DB
if (!$mysqli) {
die('mysqli_init failed');
}
if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!$mysqli->real_connect('localhost', 'USERNAME', 'PASSWORD', 'DATABASE')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
That's what I'm using to create a connection. It works. I've also got a table created, call it "table", with rows for "for", "affi", and "reff".
So my question is... someone gets directed to http://www.example.com/test.php?for=abcde&affi=12345&reff=foo
Now that I've got a DB connection open - how do I SEND that data to the DB before redirecting them to their destination site? They click - pass across this page - get redirected to destination.
BONUS KARMA - I also need a separate PHP file that I can create that PULLS from that data base. If you could point me at some instructions or show me a simple "how to pull this rows values from this table" I would be greatly appreciative :)
If I understand correctly, you'll want to use $_GET to get the URL parameters.
Then you want to run an insert query on the db with the values you got, which should be something like:
INSERT INTO table VALUES(x, y, z)
Then you need to change the page using a location header.
For the bonus question you just need the code you have now with a select query like:
SELECT * FROM table WHERE 1;
and then fetch the query results.
If this does not answer your questions please provide some clarifications.
Mysqli is the deprecated function and now PDO is recommended to connect to database. You could do following.
<?php
$conn = new PDO('dblib:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
?>
Read more here.

How to show SQL errors in SQLite?

Using SQLite in PHP (thus using PDO), I have this code:
try {
$db = new PDO("sqlite:C:\Program Files\Spiceworks\db\spiceworks_prod.db");
echo "Done.<br /><b>";
$query = "SELECT id FROM Devices LIMIT 5";
echo "Results: ";
$result = $db->query($query);
while ($row = $result->fetchArray()) {
print_r($row)."|";
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
But that does not print out any data from the SQL. I know the database has data in it and the connection is valid. If I change the query to say:
$query = "SELECT BLAHid FROM FakeDevices LIMIT 5";
Nothing changes. Nothing from SQL gets printed out again, and I see no errors even though this is clearly an invalid SQL query.
In both situations, the "Done" and "Results" gets printed out okay. How can I print out SQL errors, like if the query is invalid?
You need to tell PDO to throw exceptions. You can do that by adding the following line after you connect to the database:
$db = new PDO("sqlite:C:\Program Files\Spiceworks\db\spiceworks_prod.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
That way you can catch all exceptions except for a possible problem with the first line, the database connection itself.

How to get notified when a PHP/SQL query is notworking or invalid?

I am facing a problem. So I thought I should post my question here. I want to know that if my query is invalid how can I code the query so that the PHP controller notify me about the query error. Here is my PHP query code.
//assuming that the link $link to sql db has been already made
$Result = mysqli_query($link, 'SELECT * FROM books-table');
Is it possible to get notified whenever the query is wrong? please help
There is a simple way to do it. You can add an if condition to your code and use mysqli_error function to notify you about the invalid queries. Also you should save the query in a variable if you want to echo it easily so that you can also see the query. Here is your code with changes:
$yourquery = 'SELECT * FROM books-table';
$Result = mysqli_query($link, $yourquery);
if(!$Result)
{
echo 'There is an error in your query. Error='. mysqli_error($link);//to display error
echo '</br> the query is: '. $yourquery; //to display the query
}
Hope it will help you.
To capture if the query generates an error, you can code it like this:
/* OO-style */
if (!$link->query('SELECT * FROM books-table')) {
echo "Error: ".$link->error;
}
/* procedural style */
if (!mysqli_query($link, 'SELECT * FROM books-table')) {
echo "Error: ".mysqli_error($link);
}
(see the description of mysqli-query here in the php manual)
You can use something as simple as:
<?php
$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);
if (!$mysqli->error) {
printf("Errormessage: %s\n", $mysqli->error);
}
?>
Courtesy - http://php.net/manual/en/mysqli.error.php
if(mysql_query("SOME_QUERY"))
{
//working do some action
}
else
{
//not working do some action
}

Categories