Cant seem to figure out whats wrong, the query should be correct, and it works in phpMyAdmin but when I introduce a wildcard into the php string "%", every query fails.
This works:
$query = sprintf("SELECT `id`FROM `table`WHERE `name` LIKE '".$resources[1]."'",
mysql_real_escape_string($resources[1]));
This does not:
$query = sprintf("SELECT `id`FROM `table`WHERE `name` LIKE '%".$resources[1]."%'",
mysql_real_escape_string($resources[1]));
The query Im obviously trying to generate is
SELECT `id` FROM `table`WHERE `name` LIKE '%someName%'
Read the sprintf man page: http://php.net/sprintf
$sql = sprintf('..... '%%%s%%', $var);
^^--- turns into %
^-- %s -> $var
^^-- turns into %
Your code, as written, does NOTHING to prevent sql injection, since you're not using sprintf() properly.
Related
I wrote a SQL query to find the desired output for my project. I was working fine with the correct output. But suddenly it started to give error and in the SQL query, there is some additional apoatrophe in. How to resolve it?
I tried to add the query to $this->db->query(); but still no use.
public function getStudentConut($id) {
$this->db->select('students.id')
->from('students')
->join('bp','students.pbp = bp.id','left')
->where(condition 1)
->where(condition 2);
$query1 = $this->db->get_compiled_select();
$this->db->select('students.id')
->from('students')
->join('bp','students.dbp = bp.id','left')
->where(condition 1)
->where(condition 2);
$query2 = $this->db->get_compiled_select();
$this->db->select('COUNT(id) as stud_count')
->from('('.$query1." UNION ALL ".$query2.') X')
->group_by('X.id');
$results = $this->db->get();
return $results->num_rows();
}
It was giving correct count earlier. But without any new changes, it started to give the error.
Now I get 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 '.id`` WHERE ``bp.some_value`` IS NULL AND ``students.`schoo' at line 2
SELECT COUNT(id) as stud_count FROM (SELECT students.id`` FROM ``students`` LEFT JOIN ``bp`` ON ``students.pbp`` = ``bp.id`` WHERE ``bp..Some other condition.. UNION ALL SELECT students.idFROMstudentsLEFT JOINbpONstudents.dbp=bp.id..some other condition....) X GROUP BYX.id`
I think the issue (at least with the double `) is that CodeIgniter isn't very good with subqueries and such. Basically every time you get the compiled select statement it already has the escape identifiers and then you are putting it in the from statement at the end which will add additional escape identifiers on top of that.
`->from('('.$query1." UNION ALL ".$query2.') X')`
Unfortunately, unlike other methods like set, from doesn't have a 2nd parameter that allows you to set escaping to false (which is what I think you need).
I suggest trying this:
$this->db->_protect_identifiers = FALSE;
$this->db->select('COUNT(id) as stud_count')
->from('('.$query1." UNION ALL ".$query2.') X')
->group_by('X.id');
$results = $this->db->get();
$this->db->_protect_identifiers = TRUE;
and also look in to this: ->where(condition 2); which I'm pretty sure shouldn't compile due to lack of quotes. You probably don't want this escaped so you can do ->where('condition 2', '', false); as per: https://www.codeigniter.com/user_guide/database/query_builder.html#CI_DB_query_builder::where
When all else fails, just know that CodeIgniter has some limitations with "advanced" queries and that maybe you should write it out manually as a string utilizing $this->db->escape_str(...) for escaping user input vars, and $this->db->query(...) to run the SQL.
how to display count() sql function using php
$results = "SELECT count(votesnumber) FROM `votes` WHERE `candidate_id` = '$candidate_id'";
$queryresults = mysqli_query($connect, $results);
if($queryresults) {
$rowresults = mysqli_fetch_assoc($queryresults);
echo $rowresults['votesnumber'];
} else {
echo "error";
}
i want to display the results of sql count() function using php. am counting specific columns WHERE ID = "some value" in phpmyadmin its working but with php its giving me headache . any ideas on how to solve this?
Try this:
$results = "SELECT count(votesnumber) AS VoteNum FROM `votes` WHERE `candidate_id` = '$candidate_id'";
$queryresults = mysqli_query($connect, $results);
if($queryresults) {
$rowresults = mysqli_fetch_assoc($queryresults);
echo $rowresults['VoteNum'];
} else {
echo "error";
}
First, if you want to refer to the column name by a reference, then you need to give it a better name using an alias:
SELECT COUNT(votesnumber) as votesnumber
ROM `votes`
WHERE `candidate_id` = '$candidate_id';
Second, you should not be munging query strings with parameter values. Instead of '$candidate_id', learn to use parameters. This prevents unexpected syntax errors and SQL injection accounts.
Third, if votesnumber is actually a number of votes, then you probably want SUM() rather than COUNT().
You need to add "AS" instruction to your SQL if you want to get this data as a specific index from array (like $rowresults['votes']):
$results = "SELECT count(votesnumber) AS votes FROM `votes` WHERE `candidate_id` = '$candidate_id'";
Remember that you can always print_r() (for arrays) or var_dump() your variable to check if it contains data you want to have.
I want to find text in a MySql database
$result = mysqli_query($con,"SELECT * FROM blog
WHERE text_post LIKE = 't%';
")
or die(mysqli_error());
while($row = mysqli_fetch_array($result)) {
echo $row['titol_post'] . "<br>";
}
It gives me the error:
mysqli_error() expects exactly 1 parameter, 0 given...
If I substitute
WHERE text_post LIKE = 't%';
by
WHERE text_post = 'test';
It works well. I do not undestand. Why the LIKE does not work?
Here like after = is probelm please replace
with
WHERE text_post LIKE = 't%';
to
WHERE text_post LIKE 't%';
mysqli_error(), like all other mysqli_xx() functions, requires that you pass the connection variable to it, so that it knows which DB connection you want to know the last error for.
...
or die(mysqli_error($con));
...
Once you've done this, you will get a more useful error message that will help you diagnose the problem with your SQL code.
When you do get the real SQL error message, you will find that the problem is with the = sign.
The reason for this is that LIKE is an operator in the same way as =. You can only use one operator here, so if you're using LIKE, then you don't need = as well.
Your SQL code would therefore change to look like this:
SELECT * FROM blog
WHERE text_post LIKE 't%
I just changed like = to like and it works
SELECT * FROM blog WHERE text_post LIKE 't%'"
Try to pass conn in the error function:
or die(mysqli_error($con));
The MySQL syntax says:
string mysqli_error(mysqli link);
Returns the last error message for the most recent MySQLi function
call that can succeed or fail.
Also you need to remove the = sign after the LIKE keyword
$result = mysqli_query($con,"SELECT * FROM blog
WHERE text_post LIKE 't%';
")
or die(mysqli_error($con));
This is the right way to write sql query in mysql. Please replace your query with this.
$result = mysqli_query($con,"SELECT * FROM blog
WHERE text_post LIKE 't%';
")
This is an addition to my solved question here:
how to get array of zip codes within x miles in perl
OK, I have the array #zips. Now I am trying to use it in a query like this:
SELECT `club_name`,`city` FROM `table` WHERE `public_gig` = 'y' AND `zip` IN (#zips)
#I also tried syntax "IN ("#zips"), IN #zips and IN ('#zips')"
But, I cannot get it to work. (I am using placeholders and such as you see in my link above.)
I was able to get this to work:
$fzip=shift(#Zips);
$lzip=pop(#Zips);
SELECT `club_name`,`city` FROM `table` WHERE `public_gig` = 'y' AND `zip` BETWEEN $fzip AND $lzip
ZIP | public_gig | start_time | fin_time | city | club_name | and so on
33416 | y | 9pm | 2am | clearwater | beach bar | yada
But, for obvious reasons and some resemblance of accuracy, that is not really what I want. Just wanted to see if I could get SOMETHING working on my own.
Why can't I get the query to work with the zips in the array using IN?? Nothing is returned and there is no error.
There is actually a lot more in that query but, I left it all out to keep it short here.
I tried to figure it out by myself. Obviously, my learning capacity for the day is near peak.
Thanks for any help.
All of the examples posted here will screw up if any of your values contain single-quotes, don't use them.
Instead (assuming $dbh is the database handle for your mysql connection):
my $zip_string = join q{,}, map $dbh->quote($_), #zips;
and interpolate that.
Or, for something nice, but not half as outlandish as DBIx::Perlish: SQL::Abstract.
my $sqla = SQL::Abstract->new;
my ($sql, #bind) = $sqla->select(
'table',
['club_name', 'city'],
{
public_gig => y',
zip => { -in => \#zips },
}
);
$dbh->prepare($sql);
$dbh->execute(#bind);
# fetchrow etc.
This can be done using placeholders, you just have to work around the limitation that each placeholder can only accept a single value. WHERE zip IN (?) won't work because you're (presumably) looking for more than one value (otherwise, why use IN?).
You can, however, easily build a statement on the fly with the correct number of placeholders:
#!/usr/bin/env perl
use strict;
use warnings;
my #zips = (12345, 54321, 90210);
my $stmt = "SELECT `club_name`,`city`
FROM `table`
WHERE `public_gig` = 'y' AND `zip` IN ("
. join(', ', ('?') x #zips) . ')';
print "$stmt\n";
# Now just:
# my $sth = $dbh->prepare($stmt);
# $sth->execute(#zips);
Alternatively, if you don't mind using weird CPAN modules,
with DBIx::Perlish you can just say:
my #results = db_fetch {
my $t: table;
$t->public_gig eq "y";
$t->zip <- #zips;
};
and it will do the right thing.
Full disclosure: I am the author of DBIx::Perlish.
I don't know perl too much, but this looks like a simple SQL problem: why don't you just build the SQL IN clause from your array? You should get something like
AND zip IN ('zip 1', 'zip 2', '...')
I doubt just adding an array in perl will create the right strings for the SQL string ...
You need to turn the array into a string of values seperated by commas.
Try this :
my $zipcodes = join('\',\'',#zips);
SELECT `club_name`,`city` FROM `table` WHERE `public_gig` = 'y' AND `zip` IN ('".$zipcodes."');
If I type
'
into my search bar I get a mysql error as the "sting" has not been escaped- it think.
But the reason why I cant escape it is because I dont think it currently is a string.
the search box generates search results dynamically with ajax it is as I type and it finds the results that I get the 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 '%' OR Location
LIKE '%'%' OR Map LIKE '%'%' LIMIT 0, 16' at line 2
This is the mysql query:
<?php
if($_POST['q']!=""){
include $_SERVER['DOCUMENT_ROOT'] . "/include/datebasecon.php";
$result = mysql_query("
SELECT id, Name, Location, Map
FROM Accommodation WHERE Name LIKE '%".$_POST['q']."%' OR Location LIKE '%".$_POST['q']."%' OR Map LIKE '%".$_POST['q']."%' LIMIT 0, 16")
or die(mysql_error());
$output = "";
while($row = mysql_fetch_array($result)){
$N = preg_replace("/(".$_POST['q'].")/i","<span>$1</span>",$row['Name']);
$L = preg_replace("/(".$_POST['q'].")/i","<span>$1</span>",$row['Location']);
$M = preg_replace("/(".$_POST['q'].")/i","<span>$1</span>",$row['Map']);
$output .= "<p>".$N." - ".$L."</p>";
}
print $output;
}
?>
Is there anyway i can fix this after its post the query maybe?
When magic_quotes_gpc is off (as it should be!), $_POST['q'] is simply the string ', as just one character. That's why it's appearing in your SQL code like this:
%' OR Location LIKE '%'%' OR Map LIKE '%'%' LIMIT 0, 16
The error takes place at '%'%' because the LIKE string is being prematurely terminated.
You can just use mysql_real_escape_string() on $_POST['q'] and it'll be escaped:
$q = mysql_real_escape_string($_POST['q']);
$result = mysql_query("
SELECT id, Name, Location, Map
FROM Accommodation WHERE Name LIKE '%".$q."%' OR Location LIKE '%".$q."%' OR Map LIKE '%".$q."%' LIMIT 0, 16")
or die(mysql_error());
You wrote "I dont think it currently is a string"... it is a string. You can pass it to mysql_real_escape_string() and use the result to make your query secure and reliable. Everything your script receives by the $_POST, $_GET, $_REQUEST and $_COOKIE params can be used as string, except it is an array.
To make you understand.
Look at your query:
LIKE '%search string%'
note apostrophes you have used to delimit search string.
These apostrophes does mean that data inside IS a string.
Everything you put in quotes into query is a string.
Everything you put in quotes into query must be escaped.
No need to think, consider or estimate. The rule is simple and unambiguous: quoted text should be always escaped.