Hi I'm trying to run the following query but nothing seems to be returned
All I want to is to return the job_discription for the choosen job_type from my jobs table.
Please any help would be great as I have spent hours trying to solve it.
Thank you
alan
<input type="hidden" name="JOB_TYPE" value="<?php print $_POST['JOB_TYPE'];?>"/>
<?php
$Query = " (SELECT JOB_TYPE, JOB_DISCRIPTION FROM jobs " .
"WHERE jobs.JOB_TYPE ='$_POST[JOB_TYPE]' " .
"AND jobs.JOB_DISCRIPTION = 'JOB_DISCRIPTION')";
$Result = mysqli_query($DB, $Query);
?>
<?php
$Result = mysqli_query($DB,$Query)or die(mysqli_error($DB));
while ($Row = mysqli_fetch_assoc($Result)) // Now we go through the data displaying
{
print $Row ['JOB_DISCRIPTION'] ;
}
?>
First, the code is very prone to sql injection: you shouldn't use the $_POST data directly. Second remove the last condition if you want a description for a particular type.
Remove the AND statement from the end:
AND jobs.JOB_DISCRIPTION = 'JOB_DISCRIPTION'
Also remove the parenthesis ( ) from around the query statement.
" -- quotation marks are only required at the start and end
SELECT JOB_TYPE
, JOB_DISCRIPTION -- some people spell description with an 'e'
FROM jobs
WHERE jobs.JOB_TYPE =$_POST['JOB_TYPE'] -- escape data (using modern methods) to prevent injection and note
AND jobs.JOB_DISCRIPTION = 'JOB_DISCRIPTION'; -- This is really strange
"
Related
I have a variable that is a filter for my query:
$filterString.=" AND venue = ".$venue;
And I want this variable (when called) to add the AND filter statement to my query.
My query is as follows (with the failed attempt):
mysql_query("SELECT * FROM event
WHERE city = '$city' " . $filterString . "
ORDER BY date ASC");
I think the venue needs to be surrounded by single quotes:
$filterString.=" AND venue = '".$venue.".";
However, it is better to use parameterized queries, instead of embedding queries directly in the SQL string.
You could use:
$filterString .= !empty($venue) ? " AND venue = '$venue'" : '';
Substitute whatever test you want at the start, the idea is to return a blank string if $venue doesn't apply to the filter.
To answer your other comment question:
WHERE 1
is a valid condition that works like Anything
I have a script where I would like to read from a table and list out all the "tasks" where the column check = 1. My script works fine and will list all the tasks....until I include the WHERE. Then nothing will be read into the page. What am I doing wrong?
The problem is the WHERE check="1"
$sql = mysql_query('SELECT tasks FROM tasks WHERE check="1"');
while($row = mysql_fetch_array($sql))
{
echo $row['tasks'];
echo "<br />";
}
The table name is "tasks" and the two columns are "tasks" (varchar255) and "check" (int11)
Immediate problem
Why is nothing displayed? Most likely you have an SQL error. But you don't print it anywhere.
Displaying mysql errors with PHP
//this is a bad query, this time it is intentional
$sql = mysql_query('SELECT tasks FROM tasks WHERE check="1"');
if($sql)
{
//do processing here, no error
while($row = mysql_fetch_array($sql))
{
echo $row['tasks'];
echo "<br />";
}
}
else
{
//output error, or handle it in any other way you like
echo mysql_error();
}
And your problem is most likely quotes -- UPDATE: on multiple levels:
Level 1
Double quotes " is not ok in SQL statement. Use single quote ' for string constants, and backtick ` for enclosing object names (tables, columns, etc.)
Swap quotes:
$sql = mysql_query("SELECT tasks FROM tasks WHERE check='1'");
Escape quotes:
$sql = mysql_query('SELECT tasks FROM tasks WHERE check=\'1\'');
Do you need quotes at all? this seems to be a numeric value...
Only numeric value, no type conversion whatsoever:
$sql = mysql_query('SELECT tasks FROM tasks WHERE check=1');
Level 2
The fact that the check keyword is reserved in MySQL doesn't help either. You can use it to identifz objects, but with precautions: properly enclosed in backticks (`):
$sql = mysql_query('SELECT tasks FROM tasks WHERE `check`=1');
Strongly consider
leave mysql_* behind once and for all. Deprecated! Not Safe! Here be dragons!
best would be to properly use PDO, through prepared statements
read up on SQL injection. That can be bad news any day.
best would be to properly use PDO, through prepared statements
Agreed, as ppeterka said, you don't need quotes at all:
$sql = mysql_query('SELECT tasks FROM tasks WHERE check=1');
Consider also that using quotes will prevent your query from following an eventual index on "check" column.
You really should be using mysqli
but you can try something like SELECT tasks FROM tasks WHERE check = 1,
$sql = mysql_query("SELECT tasks FROM tasks WHERE check='1'");
while($row = mysql_fetch_array($sql))
{
echo $row['tasks'];
echo "<br />";
}
I have a submission script that I wrote in PHP. It is used by multiple surveys at our organization. The surveys are created by other users. When they submit to the script, PHP puts the data into the appropriate table in MySQL. The error that I run into sometimes is that the user(s) update the form. They add a field, or rename an input and the script doesn't account for it since it expects everything to be the same. So, I am trying to find a way to make it accomodate for when a new field is added. Here is what I have:
if( mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$survey."'"))){
echo "table exists";
$sql = "SELECT * FROM " . $survey . ";";
$result = mysql_query($sql)
or die(mysql_error());
$i=0;
while($row = mysql_fetch_row($result));{
echo $row[0];
foreach($_POST as $k => $v){
$i++;
if($k != $row[$i]){
$query = "ALTER TABLE " . $survey . " ADD " . $k . " VARCHAR(100);";
mysql_query($query)
or die(mysql_error());
}
}
}
}
I am used to doing while loops in JS, so I don't know if using i works here (actually, I know it doesn't work... because it doesn't work...). What I am trying to say is that if a key doesn't match a current field name, then add it to the table. How can I return $row correctly?
When I submit to the script it says:
Duplicate column name 'V4'
I have echo $row[0] but it returns a 1. Which is the is the int used in the primary key for the for the first record.
You have a ; at the end of your while loop declaration that shouldn't be there. Not sure if that is causing the problem as you don't say what the above code does do. Update the question if the ; is not the issue.
Your while loop declaration should look like this: while($row = mysql_fetch_row($result)) {
Also, as Marc B so diplomatically put it in a comment to your question, you should be escaping any user input that goes directly into a query.
The easiest way to do this is to use $survey = mysql_real_escape_string($survey), before your first use of $survey, as a start or switch to PDO/MySQLi and use input binding (prepared statements). Here are the prepared statements docs for PDO. More can, and should, be done to protect yourself, but the above is a good start.
I am having trouble with an SQL query that I have inserted into a piece of PHP code to retrieve some data. The query itself works perfectly within SQL, but when I use it within my PHP script it says "Error in Query" then recites the entire SQL statement. If I copy and paste the SQL statement from the error message directly into MySQL it runs with no errors.
From my research I believe I am missing an apostrophe somewhere, so PHP may be confusing the clauses, but I am not experienced enough to know where to insert them.
The query is using a variable called $userid which is specified earlier in the PHP script.
$sql= <<<END
SELECT sum(final_price)
FROM (
SELECT Table_A.rated_user_id, Table_B.seller, Table_B.final_price
FROM Table_A
INNER JOIN Table_B ON Table_A.id=Table_B.id
) AS total_bought
WHERE seller != $userid
AND rated_user_id = $userid
UNION ALL
SELECT sum(final_price)
FROM (
SELECT Table_A.rated_user_id, Table_C.seller, Table_C.final_price
FROM Table_A
INNER JOIN Table_C ON Table_A.id=Table_C.id
) AS total_bought
WHERE seller != $userid
AND rated_user_id = $userid
END;
After this section the script then goes on to define the output and echo the necessary pieces as per usual. I'm happy with the last part of the code as it works elsewhere, but the problem I am having appears to be within the section above.
Can anyone spot the error?
Edited to add the following additional information:
All of the fields are numerical values, none are text. I have tried putting '$userid' but this only makes the error display the ' ' around this value within the error results. The issue remains the same. Adding parenthasis has also not helped. I had done a bit of trial and erorr before posting my question.
If it helps, the last part of the code bieng used is as follows:
$result = mysql_query($sql);
if (!$res) {
die('Error: ' . mysql_error() . ' in query ' . $sql);
}
$total_bought = 0;
while ($row = mysql_fetch_array($result)) {
$total_bought += $row[0];
}
$total_bought = number_format($total_bought, 0);
echo '<b>Your purchases: ' . $total_bought . '</b>';
echo "<b> gold</b>";
You're checking !$res, it should be !$result:
$result = mysql_query($sql);
if (!$result) {
die('Error: ' . mysql_error() . ' in query ' . $sql);
}
I suppose, you're echo()ing the query somewhere and copy-pasting it from the browser. Could it be that the $userid contains xml tags? They wouldn't be displayed in the browser, you would have to view the page source to spot them.
you should test with $userid quoted, and parentheses around the two statements.
I'm assuming that rated_user_id is a numeric field, but what type is seller? If it's a character field, then $userid would have to be quoted as streetpc suggests.
Another thing to check is that you have at least one space after the end of your lines for each line of the query. That has tripped me up before. Sometimes when going from your editor/IDE to the database tool those problems are silently taken care of.
I have this bit of code:
//Restrict the SQL query with an AND clause if a member has been selected
if ($form_member_id != 0) {
$query .= "AND photos.member_id = '$form_member_id' ";
}
It is meant to refine a search query down to only the selected user, so the whole query together reads:
SELECT
photos.photo_id, members.member_name, photos.photo_title, photos.photo_film, photos.photo_height, photos.photo_width
FROM members, photos
WHERE members.member_id = photos.member_id
AND photos.member_id = '$form_member_id'
For some reason this does not work, ive tested the query and it works fine, but for some reason it wont work with the code ive written. I've checked for difference in the names of the variables but they are all the same....anyone know why its not working!!!
I think that you need a space before your AND otherwise it will be:
WHERE members.member_id = photos.member_idAND photos.member_id = '$form_member_id'
instead of
WHERE members.member_id = photos.member_id AND photos.member_id = '$form_member_id'
Ditto what #Matthew says about using parameterized queries, but I still think the above is the issue.
Obvious step is to print the full query before running it, then run it manually and see what happens. Also, you should be using prepared statements.
debug the script using
if ($form_member_id != 0) {
$query .= "AND photos.member_id = '$form_member_id' ";
die($query);
}
copy and paste the query and run it in phymyadmin or etc to figure out the source of bug
for better security, you may want it to be like this
if ($form_member_id != 0) {
$query .= "AND photos.member_id = '" . mysql_real_escape_string($form_member_id) . "' ";
}
You should echo the query if its now working for you to see what seems to be the problem :)
One other thing, and I'm not experienced with php, but your code looks prime-target for SQL-Injection attacks...
Someone could stuff the buffer for your "$form_member_id" and put in a value like
'; truncate members; '
where the leading and trailing quote are part of the submitted string... the first '; will terminate your string, ; to end a statement, and then truncate your table and ignore the rest...
Again, I'm not a PHP person, but so many other historical security postings talk about PARAMETERIZING your queries to prevent such injection attacks