Multiple PHP variables in MYSQL query with AND condition - mysql

This is my first code-question! I'm a beginner at both MySQL and PHP, so this might be really simple! Here is my code:
This is a file included in my Index.php...:
<?php
$query="SELECT * FROM wines WHERE Type='$type' AND Country='$country'";
$products=mysql_query($query);
?>
And these are the variables set with the $_GET function:
<?php
$type=$_GET['type'];
$fruit=$_GET['fruit'];
$country=$_GET['country'];
?>
And then later I'll fetch the array and work with it.
The problem is that my $query works fine with just the '$type'-variable, but not with the $country -variable - - - - or any other variable I've tried.
I use Microsoft Webmatrix and it tells me that the issue arises the very moment I type in the $-sign in the second variable...
So confused! Hope you can help a newcomer :)
EDIT: I found out the problem was with the "ticks" around my variables. The correct way to do it is with backticks ( `` ). Also, I started using PDO and MySQLi instead of mysql. For beginners, MySQLi is probably the easiest. Started sanitizing too.

Just a couple of (important) points to note...
You should probably be using the mysqli_* functions in the place of the mysql_ functions, as they are going to be deprecated in a following release.
start sanitizing your input before making DB queries. It's a good habit to get into early, and will save you a lot of headaches in the long run!
a good habit it to use sprintf and mysqli_real_escape_string to build your SQL before executing it on the db:
$sql = sprintf("SELECT * FROM wines WHERE Type='%s' AND Country='%s'" ,
mysqli_real_escape_string($db_object, $type),
mysqli_real_escape_string($db_object, $country));
$results = mysqli_query($db_object, $sql);
ps. in my example $db_object is coming from the call to mysqli_connect()
EDIT:
Using the (soon-to-be-defunct) mysql_ functions would be something like the following for the above example:
$sql = sprintf("SELECT * FROM wines WHERE Type='%s' AND Country='%s'" ,
mysql_real_escape_string($type),
mysql_real_escape_string($country));
$results = mysql_query($sql);

If you don't send a $type in your query string, the query is
SELECT * FROM wines WHERE Type='' AND [other stuff];
which will give back only wines with type = '';
Try:
<?php
$wheres=array();
if (isset($type)){$wheres['Type']=$type;}
if (isset($type)){$wheres['Country']=$country;}
// and so forth for each parameter
$query="SELECT * FROM wines";
if (count($wheres) != 0){
$query.=" WHERE ";
foreach ($wheres as $k => $v){$query.="$k='$v' AND ";}
$query.=" 1=1;"
}
$products=mysql_query($query);
?>

Related

How to give single quotes in SQL Query using yii frameowrk?

I'm trying to execute following SQL query using YII frameowrk
Query= select * from table where name='Bachelor''s degree'
By executing the above query I'm getting empty results. But I have content in tables.
From my perspective I think Yii framework not accepts query with single quotes in its contents.
So could you please suggest some other idea to resolve this issue ?
Thanks in advance.
Try query with parameter.
$name = "Bachelor's degree";
Yii::app()->db->createCommand()
->select()
->from('table_name')
->where('name = :name', array(':name' => "{$name}"))
->queryAll();
In YII way, bind your value to the statement.
$name = "Bachelor's degree";
$command=Yii::app()->db->createCommand();
$command->select('table_column1,table_column2,table_column3');
$command->from('table');
$command->where('name=:name', array(':name'=>$name));
echo $command->queryAll();

Get content of first 5 rows and echo them

Here I have written query for this. Query is correct but dont know why it does not echo anything:
$sql3= mysqli_query($con,"select post from facebook_posts where p_id > (select MAX(p_id) - 5 from facebook_posts);");
while ($row = #mysql_fetch_array($sql3))
{
echo $row['post'];
echo '<br/>';
}
Table has data already. When I test query in mysql it gives 5 row content;
First you use mysqli library for query and then you try to use mysql to fetch a row.
mysql and mysqli are different libraries. You should use only one of them. Since mysql is deprecated, you should use mysqli from these two.
You are mixing up the mysqli_* and mysql_* functions. The mysql_fetch_array function cannot fetch any results when you executed the query with mysqli_query. You shouldn't be using the mysql_* functions anymore since they are deprecated.
Also, if you want to limit your results in MySQL, you can use the LIMIT-clause instead of calculating a maximum/minimum id.
If you change your code into the following, it should work.
$result = mysqli_query($con,"select post from facebook_posts where p_id > (select MAX(p_id) - 5 from facebook_posts)");
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo $row['post'];
echo '<br/>';
}
For more information about fetching results using mysqli, you can look here.

Perl, HTML and MySQL where did my program break? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Yes I am a student, yes this is an assignment but I just need some help clearing things up. I don't intend for someone to do my homework for me.
So I have a database with 5 books in it with 6 different columns of data. I'm trying to make a perl program that can search that database and return the results in tables. I have to add a way to add them to a cart but that will come later.
The problem with Perl is I have no idea how to check why I'm getting "Internal Server Error." The application makes it to the Perl page so I'm guessing its not that.
#!/usr/bin/perl
use warnings; # allow for warnings to be sent if error's occur
use CGI qw( :standard ); # not a 100% sure what the rest of these mean but they are like #includs in C++, libraries for reference in the code
use DBI;
use DBD::mysql; #database data will come from mysql
my $dbh = DBI->connect( "DBI:mysql:DATABASE NAME", "USERNAME", "PASS REMOVED" ) or
die( "Could not make connection to database: $DBI::errstr" ); # connect to the database with address and pass or return error
$term = $SEARCHTERM[]; #set the search char to $term
$term =~ tr/A-Z/a-z/; #set all characters to lowercase for convenience of search
$sql = "SELECT * FROM Books WHERE Title LIKE %$term% OR Description LIKE %$term% OR Author LIKE %$term%" or die ("$term may have not worked"); #set the query string to search the database
$sth = $dbh->prepare($sql); # prepare to connect to the database
$sth->execute # connect to the database
or die "SQL Error: $DBI::errstr\n"; #or return an error
while (#data = $sth->fetchrow_array) { #while we are grabbing he queried data do a table setup and set variables for table
print "<table width=\"100%\" border=\"0\"> ";
$title = $data[0];
$desc = $data[1];
$author = $data[2];
$pub = $data[3];
$isbn = $data[4];
$photo = $data[5];
print "<tr> <td width=50%>Title: $title</td> <td width=50% rowspan=5>$photo</td></tr><tr><td>Discreption Tags: $desc</td></tr><tr><td></td></tr><tr><td>Author: $author</td></tr><tr><td>ISBN: $isbn</td>
</tr></table> \n";
}
Please help!
Earlier, someone suggested,
my $sql = "
SELECT *
FROM Books
WHERE Title LIKE '%$term%'
OR Description LIKE '%$term%'
OR Author LIKE '%$term%'
";
my $sth = $dbh->prepare($sql);
$sth->execute();
Assuming he's right about your problem, that's incorrect. Consider what happens if someone is search for the title "Foo's Bar"...
Option 1:
my $sql = '
SELECT *
FROM Books
WHERE Title LIKE '.$dbh->quote("%$term%").'
OR Description LIKE '.$dbh->quote("%$term%").'
OR Author LIKE '.$dbh->quote("%$term%").'
';
my $sth = $dbh->prepare($sql);
$sth->execute();
Option 2:
my $sql = '
SELECT *
FROM Books
WHERE Title LIKE ?
OR Description LIKE ?
OR Author LIKE ?
';
my $sth = $dbh->prepare($sql);
$sth->execute("%$term%", "%$term%", "%$term%");
First, may I also HIGHLY recommend adding use strict; to the top of the script and then fix the errors you will get, mostly declaring your variables with my.
Also may I suggest using a modern framework, like say Mojolicious rather than using the very outdated CGI module. They all can run under CGI-like environment and are FAR easier to use!
Finally, you should avoid interpolating variables into SQL strings since its a huge security risk! Try this site for more on the topic: http://bobby-tables.com/
Your select is invalid. Change
$sql = "SELECT * FROM Books WHERE Title LIKE %$term% OR Description LIKE %$term% OR Author LIKE %$term%"
to
$sql = "SELECT * FROM Books WHERE Title LIKE '%$term%' OR Description LIKE '%$term%' OR Author LIKE '%$term%"'
Pattern literals for LIKE should be quoted.

mysql_real_escape_string with variables extracted from an array

original post:
My script is not working (it's not recording the data). It was working before I added the mysql_real_escape_string, so I'm wondering if maybe I have not implemented it correctly:
$array = json_decode($downstream,TRUE);
$name = $array["status"]["name"];
$title = $array["status"]["title"];
$table = "mrTable";
$insert = "INSERT INTO $table (name, title) VALUES ('".mysql_real_escape_string($name)."', '".mysql_real_escape_string($title)."')";
Does that implementation at INSERT look correct to you?
UPDATE:
Here is the entire code, hopefully this will help. It is still not working though. When the real_escape_string function is used, NONE of the data elements get recorded in the database. As soon as I remove the escape function, data is written fine (unless of course an apostrophe shows up).
Here we go:
//read contents of this file:
$json_data = file_get_contents('../list.txt');
//json to a php array
$array = json_decode($json_data,TRUE));
//store in mysql table
$table = "table1";
$name = mysql_real_escape_string($array["current"]["name"]);
$code = mysql_real_escape_string($array["current"]["code"]);
$insert="INSERT INTO $table (name, code) VALUES ('$name', '$code')";
$con = mysql_connect($db, $user, $pass);
if (!$con)
{
die ('Could not connect: ' . mysql_error());
};
mysql_select_db($yup, $con);
mysql_query($insert) OR die(mysql_error());
mysql_close($con);
UPDATE 2
Fixed! You need to connect to the database before first mentioning mysql_real_escape_string. Everything is working now...no blank data.
You need to be connected to a database to use mysql_real_escape_string. You don't seem to be. Make sure mysql_connect is over your line where you define $insert
Never insert values directly into a query string! Even if they are escaped, it's not a smart idea. Instead, use parametrised statements as such, which will render attacks like ' OR 1 = 1-- useless. You don't need to escape values for parametrised statements either...
PREPARE statement FROM
'INSERT INTO table (col1, col2)
VALUES
(?, ?)'
EXECUTE statement USING ('val1', 'val2')
DEALLOCATE statement
Deallocate only when you're done. You can re-execute as many times as you'd like with different values. If you are going to re-execute anyways, there is a gain in performance as well from doing it this way! (Because the statement is only prepared once for an infinite number of executions.) I advise you to implement this method and then come back if you are still having problems.
Please don't try to escape your parameters. Use bind variables. See http://bobby-tables.com/php.html for examples.

Query only working on PHPMyAdmin

I'm trying this query:
//connect;
$site = mysql_real_escape_string($_GET['site']);
$data = mysql_query("SELECT * FROM Items WHERE Site = '$site'");
while($row = mysql_fetch_array( $data ))
{
print $row['type'];
}
doesn't print anything, running SELECT * FROM Items WHERE Site = 'http://rollingstone.com/' from PHPMyAdmin returns one row.
I'm sure it must be something really basic, since I haven't got much experience with MySQL.
I'm trying it here btw: http://www.chusmix.com/game/insert/get-items.php?site=http://rollingstone.com/
What am I doing wrong?
Make sure $site actually contains something; doing a quick echo $site before your mysql_query() should tell you this. If it's empty, try print_r($_GET) to see if it's in the $_GET array. It should be, but it might not for some other reason; check any code above this snippet for stuff that modifies $_GET or $_REQUEST in any way.
To request data from a MySQL table, you need to connect to the server using mysql_connect(), then select the database with mysql_select_db(). PHP should throw errors, but to be sure put these lines at the top of your script:
error_reporting(E_ALL);
ini_set('display_errors', '1');
All errors will now be shown.
In addition, you can also test for how many rows that were returned using mysql_num_rows(). For example:
if(mysql_num_rows($data) !== false)
{
while(...)
{
...
}
}
else
{
echo "No rows";
}
Will echo No rows if there weren't any results from the query. This is all error detection code; the cause of your error isn't obvious, so a little investigation is necessary, using the above methods (and any more you can think of).
Have you called mysql_select_db('your_database_name'); on the connection first? Have you tried echoing out the SQL before it's executed to confirm that Site is what you expect it to be?
$query = sprintf("SELECT * FROM Items WHERE Site ='%s'",
mysql_real_escape_string($site));
$result = mysql_query($query);
Just to be on the safe side (avoid SQL Injections).