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 "
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 am getting the below error:
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 'testing order by id'
Here is the main page..
echo "<div ><a href='secondpage.php?title=".urlencode($row['title'])."'>".wordwrap($row['title'], 35, "<br />\n", true)."</a></div>";
and here is the second page the error appearing on. the address bar reads http://localhost/secondpage.php?title=more+testing
<?php
$mydb = new mysqli('localhost', 'root', '', 'test');
$sql = "SELECT * FROM test where urlencode(title) =".$_GET['title']" order by id ";
$result = $mydb->query($sql);
if (!$result) {
echo $mydb->error;
}
?>
<div>
<?php
while( $row = $result->fetch_assoc() ){
echo $row['firstname'];
}
$mydb->close ();
?>
</div>
You want to use urldecode to decode the encoded string in your query:
$title = urldecode($_GET['title']);
$sql = "SELECT * FROM test where title = '$title' order by id";
I'm assuming you have a column named title in your test table. I don't think MySQL has urlencode function unless you have a procedure by that name which functions exactly like PHP's urlencode.
Update:
Thanks to #GeorgeLund, who pointed out the point of SQL Injection. Important topic which I missed earlier during answering your question. Please have a look at: https://www.owasp.org/index.php/SQL_Injection
For the very least please update your code to following:
$title = urldecode($_GET['title']);
$title = mysqli_real_escape_string($title); // Addition
$sql = "SELECT * FROM test where title = '$title' order by id";
$sql = "SELECT * FROM test where urlencode(title) ='".$_GET['title']."' order by id ";
Try like
$sql = "SELECT * FROM test WHERE urlencode(title) = ".$_GET['title']." ORDER BY id ";
You missed . leads syntax go away.
As far as I know SQL does not have function urlencode and why would you even want to urlencode the column name?
Also to store the encoded title string which is received from the last page you should decode the encoded title
So here is what I think you meant to do.
$sql = "SELECT * FROM test WHERE title = ".urldecode($_GET['title'])." order by id ";
Please try this code using urldecode
$sql = "SELECT * FROM test where title =".urldecode($_GET['title'])" order by id ";
I am using this code for fetching data from database , I am getting $data fetched properly but i am not getting data properly in this variable $seldata why is it so
<?php
include_once("includes/connection.php");
include_once("includes/session.php");
//echo $_SESSION['uid'];
$sql="SELECT * FROM employee WHERE eid = '{$_GET['id']}'";
$result=mysql_query($sql);
$data=mysql_fetch_array($result);
echo "data".$data;
$sel_valsql="select * FROM selected_candidate WHERE eid = '{$_GET['id']}'";
$sresult=mysql_query($sel_valsql);
$seldata=mysql_fetch_array($sresult);
echo "seledata".$seldata;
?>
<?php
include_once("includes/connection.php");
include_once("includes/session.php");
//echo $_SESSION['uid'];
$sql="SELECT * FROM employee WHERE eid = '".$_GET['id']."'";
$result=mysql_query($sql);
$data=mysql_fetch_array($result);
echo "data".$data;
$sel_valsql="select * FROM selected_candidate WHERE eid = '".$_GET['id']."'";
$sresult=mysql_query($sel_valsql);
$seldata=mysql_fetch_array($sresult);
echo "seledata".$seldata;
?>
Note: mysql_fetch_array() returns an array of results so you need to do print_r($seldata) in order to view the results.
try this,
$sql = "SELECT * FROM employee WHERE eid = '" . $_GET['id'] . "'";
As a sidenote, the query is vulnerable with SQL Injection if the value(s) came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
Remove the single quote form the where condition i.e.
$sql="SELECT * FROM employee WHERE eid = {$_GET['id']}";
or do like this:
$sql = "SELECT * FROM employee WHERE eid = '" . $_GET['id'] . "'";
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
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());