I am attempting to use a drop-down list to pull Pokémon info back from a database that I've uploaded, and I keep getting the following error:
No Pokemon was requestedDatabase access failed: You have an error in
your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'WHERE pokemon_name =
SELECT * FROM pokemon_info' at line 1
I have a database currently with the headings:
id | pokemon_name | height | weight | gif
I literally can't figure out why... My processing code is as follows;
// CODE TO QUERY DATABASE TO GO HERE
// Capture form data, if anything was submitted
if (isset($_POST['pokemon_submit'])) {
$pokemon_submit = clean_string($db_server, $_POST['submit']);
// create the SQL query
$query = "SELECT * FROM pokemon_info where pokemon_info=$pokemon_submit";
// query the database
mysqli_select_db($db_server, $db_database);
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
// if there are any rows, print out the contents
if ($row = mysqli_fetch_array($result)) {
$output .= "Pokemon: " . $row['pokemon_name'] . ", Gif: " .
$row['gif'] . "<br />";
}
else {
$output = 'Well, you must have invented a new Pokémon, cause it is not on this website!';
}
mysqli_free_result($result);
}
else {
$output = 'No Pokemon was requested';
}
// CODE TO QUERY END
}
// Close connection!
// YOUR CODE HERE BIT end
echo $output;
$output = '';
mysqli_select_db($db_server, $db_database);
$query = "WHERE pokemon_name = $pokemon_submit SELECT * FROM pokemon_info";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$output .= "Pokemon: " . $row['pokemon_name'] . ", Gif: " .
$row['gif'] . "<br />";
}
mysqli_free_result($result);
echo $output;
I have now amended thanks to your help, and it's saying that no Pokémon was requested.
The basic idea of this is to have a main page with a drop-down list of pokemon. When a user selects from the list, the information stored in my database about that specific pokemon is displayed.
The drop-down list is linked directly to the pokemon_name column in my database. I don't understand why it's coming back as though nothing is selected?
Thank you all SO much for your help, I'm learning much more here than trawling through forums.
There are more than one issue(s)
$query = "SELECT * FROM pokemon_info where pokemon_name=$pokemon_submit";
if pokemon_submit is a number - it is ok. If it is a string then you need
$query = "SELECT * FROM pokemon_info where pokemon_name='$pokemon_submit'";
notice the single quotes.
$query = "WHERE pokemon_name = $pokemon_submit SELECT * FROM pokemon_info";
$result = mysqli_query($db_server, $query);
I have no clue what you're trying here? I know of no SQL statements begin with "WHERE"
WHERE pokemon_name = $pokemon_submit SELECT * FROM pokemon_info
is not a valid query.
If you want to select the pokemon $pokemon_submit from pokemon_info, what you do is this;
SELECT * FROM `pokemon_info` WHERE `pokemon_name` = '$pokemon_submit'
The WHERE comes after SELECT. More on the doc page.
I'd also look into verifying data before putting it into the query, OOP approach to MySQLi and general SQL syntax.
I urge you to look at the other comments. Your querying looks fundamentally unsafe. However, I believe that your actual issue is here:
if (isset($_POST['pokemon_submit'])) {
$pokemon_submit = clean_string($db_server, $_POST['submit']);
First, you look for $_POST['pokemon_submit'], but when you clean the string, you use $_POST['submit'].
Insted of WHERE pokemon_name = $pokemon_submit SELECT * FROM pokemon_info try altering your query to something like ...
WHERE pokemon_name in $pokemon_submit SELECT pokemon_name FROM pokemon_info
The second part of your query is returning multiple results. ie..... Select * from pokemon_info.
So we refine that to get only the pokemon names back ie..
select pokemon_name from pokemon_info
And the first part of the query will only want names where the name matches any of the results from the second part of the query
Your full query should look something like
select * from pokemon_info WHERE pokemon_name in $pokemon_submit SELECT pokemon_name FROM pokemon_info
or in short
select * from pokemon_info where pokemon_name = $pokemon_submit
Related
I have a SQL query in my PHP file that makes use of some variables in it. I want to print the query itself on the localhost to check as to whether the entire query is been executed or not.
My query is like this:
$result = mysql_query("SELECT * FROM sample WHERE col01 LIKE '%$abc%',$db);
I am trying to print the query using echo $result but get Resource id #25 on localhost. I want to print Select * FROM ... as the output. Is there any way?
First of all: You are missing a double quote: $result = mysql_query("SELECT * FROM sample WHERE col01 LIKE '%$abc%'",$db).
That said, what stops you from
$sql="SELECT * FROM sample WHERE col01 LIKE '%$abc%'";
$result = mysql_query($sql,$db);
echo $sql;
If you were using PDO (and you should, the old mysql_ functions are deprecated and insecure) you could just use PDOStatement->queryString property to view the query at a later time.
Store as a variable $sql
Its normal, first you need to fetch that resource obj
And anyway you missing a double quote,
example.
$sql = "SELECT * FROM sample WHERE col01 LIKE '%$abc%'";
$result = mysql_query($sql);
while ($line = mysql_fetch_object($result)) {
echo $line->colname ."\n";
}
echo "\n" . ' query: ' . $sql
And from PHP 5.5.0 and beyond use mysqli
$sql = "SELECT * FROM sample WHERE col01 LIKE '%$abc%'";
if ($result = $mysqliobj->query($sql)) {
while($line= $result->fetch_object()){
echo = $line->colname ."\n";
}
}
echo "\n" . ' query: ' . $sql
or print_r($mysqliobj->info); # store las query
I'm trying to count entries in a database based on 2 basic criteria. It is returning a blank result, even though there are results to be found. Anyone have any idea what I am doing wrong here? I have tried it so many different ways and they all return no result. (If I enter the query directly in phpmyadmin it returns a result.)
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
$numericalResult = mysql_query($sql, $con);
$row = mysql_fetch_object($numericalResult);
$totalOrders1 = $row->total_count;
echo "My orders:" . $totalOrders1;
As others stated, make sure you sanitize variables before they go into query.
$sql = "SELECT * FROM orderOption3Detail WHERE orderDate = '" . $orderDate . "' AND studentID = '" . $studentID . "'";
$sql_request_data = mysql_query($sql) or die(mysql_error());
$sql_request_data_count = mysql_num_rows($sql_request_data);
echo "Number of rows found: " . $sql_request_data_count;
That's all you need.
Edited: providing full code corrected:
$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(); } //global option 1
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
//echo $sql;
$numericalResult = $con->query($sql);
$row = mysqli_fetch_object($numericalResult);
echo $row->total_count; //echo (int) $row->total_count;
Please test this and let me know. Good luck!
----- End Editing ----
Have you tested assigning values directly as a test in your SQL string, like:
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='05/23/2012' AND studentID='17'";
Also, did you check if the date's format is correct, reading that $orderdate variable and testing it in PHPMyAdmin?
Did you read the $sql with values inserted and test in PHPMyAdmin and worked?
Also, check the connection to assure there is no problem there.
One more thing, sorry. You seem to be using the wrong syntax in your mysql_query statement. That way works for mysqli_query, and the parameters would be inverted. Try only:
$numericalResult = mysql_query($sql);
Provided you made the connection and database selection previously, like in:
$connection=mysql_connect($db_host, $db_username, $db_password);
if (!$connection)
{
$result=FALSE;
die('Error connecting to database: ' . mysql_error());
}
// Selects database
mysql_select_db($db_database, $connection);
Best wishes,
I am trying to learn php and came across a task which i have need help with.
Background information - I have a postgresql database which has
multiple tables.
What I need - When I enter anything in the form on my HTML page, i
need to extract all information from all the tables that contain
information related to what I have entered.
Example - Suppose I enter food poisoning in the form. I need to access
all the tables and extract the different information related to food
poisoning.
My code: (the connection part is not being posted as it works fine)
<?php
$result = pg_prepare($dbh, "Query1", 'SELECT * FROM Project.bacteria WHERE disease = $1');
// if (pg_numrows($result) == 0) {
// $result = pg_prepare($dbh, "Query1", 'SELECT * FROM Project.virus WHERE disease = $1');
// }
//$sql = "SELECT * FROM Project.bacteria WHERE disease=";
//$result = pg_query($dbh, $sql);
$result = pg_execute($dbh, "Query1", array($disease));
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
//$rows = pg_fetch_all($result)
/*// iterate over result set
// print each row*/
while ($row = pg_fetch_array($result)) {
echo $row[0]." ".$row[1]. "<br />";
}
?>
For the above code, when I enter food poisoning it searches just one table i.e bacteria and returns the related information ( here as a test i have taken just information at row position 1 and row position 2.)
Since there are multiple tables, like a table drugs that stores information of drugs used to cure food poisoning, i would want to extract that information from the respective table.
Any help would be appreciated.
try this one
SELECT * FROM bacteria WHERE disease = ''
UNION ALL
SELECT * FROM drugs where desease = ''
but i think the best way is to normalize you tables. :)
I am trying to print out some topic information, but it is not going so well. This is my query:
SELECT * FROM topics WHERE id='$read'
This doesn't work. I've echo'ed the $read variable, it says 1. So then if I do like this:
SELECT * FROM topics WHERE id='1'
It works perfectly. I don't get what is the problem. There's no hidden characters in $read or anything else like that.
Try like this:
$query = "SELECT * FROM topics WHERE id='" . $read . "'"
ID is normally a numeric field, it should be
$id = 1;
$query = "SELECT * FROM topics1 WHERE id = {id}"
If you are using strings for some reason, fire a query like
$id = '1';
$query = "SELECT * FROM topics1 WHERE id = '{$id}'"
SELECT * FROM topics WHERE id=$read
it consider it as string if you put i single quotes
I wonder why all the participants didn't read the question that clearly says that query with quotes
SELECT * FROM topics WHERE id='1'
works all right.
As for the question itself, it's likely some typo. Probably in some other code, not directly connected to $read variable
try
$query = sprintf("SELECT * FROM topics WHERE id='%s';",$read);
Also remember to escape the variable if needed.
Looks like you might have an issue with the query generation as everyone else is pointing to as well. As Akash pointed out it's always good to build your query in to a string first and then feed that string to the MySQL API. This gives you easy access to handy debugging techniques. If you are still having problems try this.
$id = 1;
$query = "SELECT * FROM `topics1` WHERE `id`={$id}";
echo ": Attempting Query -> {$query}<br />";
$res = mysql_query($query, $dblink);
if($res <= 0)
die("The query failed!<br />" . mysql_error($dblink) . "<br />");
$cnt = mysql_num_rows($res);
if($cnt <= 0)
{
$query = "SELECT `id` FROM `topics1`";
echo "No records where found? Make sure this id exists...<br />{$query}<br /><br />";
$res = mysql_query($query, $dblink);
if($res <= 0)
die("The id listing query failed!<br />" . mysql_error($dblink) . "<br />");
while($row = mysql_fetch_assoc($res))
echo "ID: " . $row['id'] . "<br />";
}
This will at least let you monitor between calls, see what your query actually looks like, what mysql says about it and if all else fails make sure that the ID you are looking for actually exists.
try with this : SELECT * FROM topics WHERE id=$read
I am trying to create a php script that selects one row from my table by using the WHERE clause. The problem is the mysql query returns no rows. I know the variable is correct (its user submitted).
$title = mysql_real_escape_string($_REQUEST["title"]);
$query = mysql_query("SELECT * FROM links WHERE title ='$title'", $con)
or die ("Error: " . mysql_error());
I'm looking for any ideas that could fix my problem. I know the mysql is working properly because other queries execute fine. The title variable is correct; it is passed from a mysql on another page.
ps - I posted a similar question earlier, but worded it poorly and got results that didn't address the problem
Try this:
$query = mysql_query("SELECT * FROM links WHERE title ='$title' limit 1")
or die ("Error: " . mysql_error());
Sorry, I'm new here and I couldn't find the button to comment on the original question.
But you mentioned the request was user submitted. Are they typing it or is it a selection like from a select box or radio button? I'm asking because does the requested title even exist in the DB?
Anyway, what is your result if you use the following?:
$query = mysql_query("SELECT * FROM links WHERE title LIKE '%".$title."%'")
or die ("Error: " . mysql_error());
If not, then there's definitely no match in the DB.
try this query
mysql_query("SELECT * FROM links WHERE title like '$title%'", $con)
Try this query:
$query = mysql_query("SELECT * FROM links WHERE title LIKE '%{$title}%'");
or maybe this to check formatting:
$sql = sprintf("SELECT * FROM links WHERE title LIKE '%%%s%%'", $title);
$query = mysql_query($sql);
In my case I had empty space before and after the variable name, like this
$query = "select * from user where user_name = ' $user_name ' ";
and this results in comparing userName with [empty_space userName empty_space ] which doesn't exist in the database.
your query should be like this
$query = "select * from user where user_name = '$user_name' ";