php with SQL query - php

i have a problem with php in the following:
$sql = 'SELECT name FROM chiled WHERE `im` LIKE $id ';
$query = mysql_query( $sql );
$a=mysql_fetch_row($query);
echo $a[0];
there is error in mysql_fetch_row($query);
but if i do the following :
$sql = 'SELECT name FROM chiled WHERE `im` LIKE 1111 ';
$query = mysql_query( $sql );
$a=mysql_fetch_row($query);
echo $a[0];
it is working and prints the name
can you please tell me what is wrong?

Single quotes in PHP doesn't evaluate embedded variables - you need to use double quotes to do that. (See the "Single quoted" section of the PHP Strings manual page for more info..)
i.e.: $sql = "SELECT name FROM chiled WHERE 'im' LIKE $id ";
Or better still...
$sql = 'SELECT name FROM chiled WHERE im="' . mysql_real_escape_string($id) . '"';
(As you're not using the % in your like, you're presumably not attempting to do any form of pattern matching.)
Additionally, I'd recommend a read of the existing Best way to stop SQL Injection in PHP question/answers.

Are you sure you want to be using LIKE? It looks more to me like you want to see if im = $id. Also, make sure you're escaping your variables before using them in the query.
Edit
If you DO want to us LIKE, you probably want something like this:
$sql = "SELECT name FROM chiled WHERE `im` LIKE '%$id%' ";
which will find anywhere that the string $id is found in the im column.

You need to quote the variable after LIKE, like this:
$sql = "SELECT name FROM chiled WHERE im LIKE '$id'";
$query = mysql_query($sql);
$a = mysql_fetch_row($query);
echo $a[0];
// ....
Beside, you are using single quotes, Therefore, $id is not replaced for its value. Your query look like this:
SELECT name FROM chiled WHERE im LIKE $id;

$sql = "SELECT name FROM chiled WHERE `im` LIKE '$id' ";
change to double quotes - http://php.net/manual/en/language.types.string.php

Related

How to Concatenate table name with with a variable value in mySQL

I'm trying to create a dynamic code that would ready from any table with the certain name but the difference between each table name is a number that is generated by a variable: for example :
//that's how I get my variable the value for example is = 3
$pid = $GLOBALS["localid"];
//the table name for example is tablename_3
$strTable = "tablename_" .$pid;
//here's how the query should look like
$query = "SELECT * FROM . $strTable . where .....;
I'm making a mistake somewhere but can't figure it out and would appreciate a little help please
Remove the dots and also make sure you have single quotes aroung where
$query = "SELECT * FROM $strTable where '.....';
Besides the comments about do or don't build your queries like this...
You're not closing the quotes properly.
$query = "SELECT * FROM . $strTable . where .....; //Double quote not closed.
should be:
$query = 'SELECT * FROM' . $strTable . 'where .....'; //Single quoted strings concatenated with variable.
or
$query = "SELECT * FROM $strTable where ....."; //Variable inside double quoted string.

How to make query that ignores undefined variables?

How make mysql search defined just by what is written in html form, by user, and if some form box is stayed empty, mysql should ignore it. For example:
$sql = "SELECT * FROM catalog WHERE name= '".$name."' AND publisher = '".$publisher."' ";
mysql_query($sql);
This query will display all rows where name and publisher are together. Now, what if user insert just name, and left publisher box empty. The idea is that php/mysql ignore empty form box, and display every row with inserted name. But it will not do that because $publisher will be undefined, and error emerges. How to tell musql to ignore $publisher? More generally, the question is: how to generate query that make searching defined by certain criteria if they exists, and if they don't how to just ignore it?
You can build up the sql programmatically. I am assuming you have escaped the values properly.
$sql = "SELECT * FROM catalog";
$wheres = array();
if (!empty($name)) {
$wheres[] = " name = '$name'";
}
if (!empty($publisher)) {
$wheres[] = " publisher = '$publisher'";
}
if (count($wheres)) {
$sql .= " WHERE " . implode (' AND ', $wheres);
}
//RUN SQL
Also have a read through this, you are using a deprecated mysql library.
This will allow either the name or the publisher to be NULL.
<?php
$sql = "SELECT * FROM catalog WHERE (name= '".$name."' OR name IS NULL) AND (publisher = '".$publisher."' OR publisher IS NULL)";
mysql_query($sql);
Try like
$my_var = " ";
if($publisher) //if(!empty($publisher))
$my_var = " AND publisher = '".$publisher."' ";
$sql = "SELECT * FROM catalog WHERE name= '".$name."' ".$my_var;
if the publisher is empty then you need to pass the NULL value and PLZ note that it is a bad practise.It will causes many sql injection issues.Try to put validations for the things

PHP not displaying results from MySQL database

I am trying to display an entry from a MySql database which is selected by GET data.
if (isset($_GET["id"])){
$id=$_GET["id"];
$result = getSelectedBlog($id);
while($row = mysqli_fetch_array($result))
{
extract($row);
?>
<div class="headline"><?php echo $headline ?></div>
<div class="subtitle"><?php echo $subTitle ?></div>
<div class="content"><?php echo $content ?></div>
<?php
}
Here is the SQL statement:
function getSelectedBlog($id){
$con = mysqli_connect('localhost', 'root', '', 'michaelWebsite') or die('could not connect');
$sql = 'SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE "$id"';
$result = mysqli_query($con, $sql) or die('entry does not exist.:' . mysqli_error($con));
return $result;
}
As you can see, I am passing the get data as $id to the method that returns the result. However nothing is being returned. There are three entries at the moment, if I change $id in the SQL statement to either 1, 2 or 3 it will show the corresponding data but it just will not work with the $id variable.
The URL does end with the correct info ?id=1.
Please excuse me if it is something stupid, I have just been stuck on this for hours now!!
All of these answers will solve your problem, but none have mentioned or prevented SQL Injection.
In your case I recommend (assuming articleID is an integer field).
$sql = 'SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE "' . (int)$id . '"';
I'm also curious why you are using LIKE for an id field.
Note: Since you are using MySQLi, I'd encourage you to look at prepared statements.
$sql = 'SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE "'.$id.'"';
escape your var in simple quote
Try with this:
$sql = "SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE '$id'";
or with
$sql = 'SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE "' . $id . '"';
You need to use double quotes in order for php to correctly expand your variables :) so change your query to
$sql = "SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE '$id'";
Change
'SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE "$id"'
to
"SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE '$id'"
Variables will be evaluated only if they're between double quotes "

I tried to use this php scipt to remove html tags from a table row (select data and update the row)

I tried to use this php scipt to remove html tags from a table row.
(select the data, strip_tags the string and update the row)
I would be more than thankful for help to find whats wrong.
The "select" is working and i can "echo" or "print" the result and the "strip_tags" is also working.
But, the data is not updated to the table row ? Somthing wrong with the "update" lines?
<?php
include_once ("classes/config.php");
$sql = "SELECT * FROM group_profile WHERE indexer = 4300741";
$query = mysql_query($sql);
$result = #mysql_fetch_array($query);
$group_name = $result['group_description'];
$group_description = strip_tags($group_description, '<p>');
$sql1 = "UPDATE group_profile SET group_name = $group_description WHERE indexer = 4300741";
mysql_query($sql1);
#mysql_close();
?>
did you try this:
$sql1 = "UPDATE group_profile SET group_name = \'" . mysql_real_escape_string($group_description) . "\' WHERE indexer = 4300741";
The problem is here:
$group_name = $result['group_description'];
$group_description = strip_tags($group_description, '<p>');
You are using strip_tags on an undefined variable.
I am guessing you want something like:
$group_description = strip_tags($result['group_description'], '<p>');
And the you need to quote the variable in the sql statement:
$sql1 = "UPDATE group_profile SET group_name = '$group_description' WHERE indexer = 4300741";
Edit: It seems that escaped data comes back un-escaped from the database, so the correct line would be:
$group_description = mysql_real_escape_string(strip_tags($result['group_description'], '<p>'));
But prepared statements all the way is the way to go....
$group_description = strip_tags($result['group_description'], '<p>');
$sql1 = "UPDATE group_profile SET group_name = \"" . mysql_real_escape_string($group_description) . "\" WHERE indexer = 4300741";
This way, we strip tags from the right variable, and escape it before inserting into the DB.
It would be even better to use a prepared query. See a tutorial here: http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html
$group_description=mysql_real_escape_string($group_description);
$sql1 = "UPDATE group_profile SET group_name = '$group_description' WHERE indexer = '4300741'";
Another point to add to the UPDATE query not working, for debugging only add this to your query line to get a descriptive error message if their is a problem with the query:
mysql_query($query) or die(mysql_error());
Remove the or die after debugging the issue, it could help you resolve the problem, or at least confirm the update is failing because of a syntax error in the query. IE like people said the missing quotes.
$group_description is not in quotes, so it would be throwing an error and not updating. I would try this:
$group_description = addslashes(strip_tags($group_description, '<p>'));
$sql1 = "UPDATE group_profile SET group_name = '$group_description' WHERE indexer = 4300741";
Looks like you're missing quotes:
$group_description=mysql_real_escape_string($group_description);
$sql1 = "UPDATE group_profile SET group_name = '$group_description' WHERE indexer = 4300741";

MYSQL WHERE clause is wrong value

Whenever I try to perform my query, It gives me an unknown column error, because it is using my variable as the column name.
essentially
$search="lname";
$term="asdas";
(both of those are variables from a form on another page)
I run this:
if (isset($term))
{
$query = "SELECT * FROM test
WHERE $search = $term ";
}
else
{
$query = "SELECT * FROM test";
}
echo $query;
$result=mysql_query($query) or die(mysql_error());
and then I get this as my error:
Unknown column 'asdas' in 'where clause'
You need to enclose the search term in single quotes(also use mysql_real_escape_string to avoid any issues with quotes in the search string.).
i.e:
if (isset($term))
{
$query = "SELECT * FROM test WHERE $search = '" . mysql_real_escape_string($term) . "' ";
}
You need to quote it.
if (isset($term))
{
$query = "SELECT * FROM test
WHERE $search = '$term' ";
}
else
{
$query = "SELECT * FROM test";
}
echo $query;
$result=mysql_query($query) or die(mysql_error());
Other comments
It is always better to use parameterized queries if the driver supports it. It will prevent SQL injection. As it stands, someone could send in a string "' or ''='" and the query turns out to be
SELECT * FROM test WHERE col1 = '' or ''=''
which is really benign but unexpected behaviour. If the string contains single quotes, it also breaks your query (input is "o'neil")
SELECT * FROM test WHERE col1 = 'o'neil' # << unmatched quotes
So, at the very least use mysql_real_escape_string if you cannot use parameters, i.e.
$query = "SELECT * FROM test
WHERE $search = '" . mysql_real_escape_string($term) . "' ";
You need to quote your $term parameter:
// protect from trivial sql injection attacks.
$term = mysql_real_escape_string("adas");
$query = "SELECT * FROM test
WHERE $search = '$term'";
You have to surround the term value with quotes:
SELECT *
FROM test
WHERE lname='asdas'
otherwise any SQL server out there will think asdas is a field name and try to find it in the table.
Add ' around your columns
$query = "SELECT * FROM test WHERE $search = '$term' ";
you need to put single quotes around $term so that the SQL thinks it's a string
put single quote string always be quoted. Do not forgot use mysql_real_escape_sring()
$query = "SELECT * FROM test
WHERE $search = '$term' ";
Put single quotes around $term
if (isset($term))
{
$query = "SELECT * FROM test WHERE $search = '$term'";
}
else
{
$query = "SELECT * FROM test";
}
echo $query;
$result=mysql_query($query) or die(mysql_error());

Categories