empty result from mysql with “\” and “-” in query - php

i have SQL query :
SELECT count(art),art,art_manufacturer,group_manufacturer
FROM goods
WHERE art_manufacturer = 'ГКБ-44/150'
when i using phpMyAdmin, result of query is:
1, 950000258, ГКБ-44/150, Интерскол
my php file contain:
$art="ГКБ-44/150";\\debug
$query = "SELECT art,art_manufacturer,group_manufacturer FROM goods WHERE art_manufacturer = '".$art."'";
$sql = mysql_query($query);
while ($recResult = mysql_fetch_array($sql))
{ \*do somting*\ }
where is my mistake? why the result of query in php is empty?
my solution
i had mysql_query("SET NAMES cp1251"); in my code
when i start use mysqli i commented mysql_query("SET NAMES cp1251");
mistakenly i thought mysqli is solution, after i discommented mysql_query("SET NAMES cp1251"); i got problem again.
So what's happend?
my PHP file in UTF-8 and when i use mysql_query("SET NAMES cp1251"); i had SELECT art,art_manufacturer,group_manufacturer FROM goods WHERE art_manufacturer = "ГКБ-44/150"; query to mysql DB

It's empty because these are specially reserved characters interpreted by PHP/SQL. I would suggest you take a look at parameterised queries or PDO, they will escape strings for you as part of their function.
EDIT: Also it could be that the encoding of your server doesn't accept Unicode characters. I would ensure your site is using UTF-8.

You should stop using mysql_* functions they are deprecated for a long time.
Use mysqli or PDO and bind parameters to the query not concatenate the query string with some not prepared php variables.
So just to help you pass over the issue this time you can:
$query = "SELECT art,art_manufacturer,group_manufacturer
FROM goods
WHERE art_manufacturer = '".mysql_real_escape_string($art)."'";

Related

writing data into mysql with mysqli_real_escape_string() but without &

iam using this code below, but the character "&" will not be inserted into the db, also when i copy/paste some text from other pages and put it into the db the text ends for example in the middle of the text, dont know why, i tried also addslashes() and htmlspecialchars() or htmlentities().
i read mysqli_real_escape_string() is againt SQL injection attacks and htmlspecialchars() against XSS attachs, should i also combine them ?
$beschreibung = mysqli_real_escape_string($db, $_POST['beschreibung']);
SQL Injection is merely just improperly formatted queries. What you're doing is not enough, stop now. Get into the practice of using prepared statements..
$Connection = new mysqli("server","user","password","db");
$Query = $Connection->prepare("SELECT Email FROM test_tbl WHERE username=?");
$Query->bind_param('s',$_POST['ObjectContainingUsernameFromPost']);
$Query->execute();
$Query->bind_result($Email);
$Query->fetch();
$Query->close();
Above is a very basic example of using prepared statements. It will quickly and easily format your query.
My best guess to what is happening, I'm assuming you're just using the standard:
$Query = mysqli_query("SELECT * FROM test_tbl WHERE Username=".$_POST['User']);
As this query is not properly formatted you may have the quotes in your chunk of text which close the query string. PHP will then interpret everything as a command to send to the SQL server
If you know what you are doing, you can escape indata yourself and add the escaped data to the query as long as you surround the data with single quotes in the sql. An example:
$db = mysqli_connect("localhost","my_user","my_password","my_db");
$beschreibung = mysqli_real_escape_string($db, $_POST['beschreibung']);
$results = mysqli_query(
$db,
sprintf("INSERT INTO foo (beschreibung) VALUES ('%s')", $beschreibung)
);
To get predictable results, I advise you to use the very same character encoding, e,g, UTF-8, consistently through your application.

MySQL DB query compare to PHP variable

I am very new to PHP and only have a class from a year ago where I touched MySQL.
I am trying to add a check in some existing code to query a db table for a value, and if that value is = to 1, change a variable in the code. Seems simple enough but it's not working out. I am getting 0 results from my query, even though the query works as expected in Sequel Pro.
I am modeling my syntax after the existing query even though I don't fully understand the prepare and execute functions, because I don't want to create a new db connection to make it easier on myself. I'll give the snippets that matter, I think.
My question: Why is this not returning results, when it works fine in the database directly? The query should return 2 results, in the form of Integers, which I want to compare to another integer, $friend_uid.
$dbObj = new sdb("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USERNAME, DB_PASSWORD);
$dbObj->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$newStatus = 'REQUEST_PENDING';
$botquery = "SELECT `KAP_USER_MAIN.UID` FROM `KAP_USER_MAIN` WHERE `KAP_USER_MAIN.IS_BOT` = 1";
$botstatement = $dbObj->prepare($botquery, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$botstatement->execute();
$posts[]= "sql error " . mysql_error();
if(!$botstatement){
$posts[] = "failed bot query: " . mysql_error();
}
$num_rows = mysql_num_rows($botstatement);
if ($num_rows == false) {
$num_rows = 0;
}
$posts[] = "$num_rows rows";
while($row = mysql_fetch_array($botstatement)) {
if($row[0]['UID'] == $friend_uid){
$newStatus = 'FRIENDS';
}
}
$statement->execute(array(':uid'=>$uid,':friend_uid'=>$friend_uid,':status'=>$newStatus));
Here is an example of a query from the existing code that works just fine, which I am modeling after:
$query = "SELECT kits.TOTAL_UNIT,kum.ENERGY,kum.NAME,kum.LEVEL FROM KAP_USER_MAIN kum,KNP_INVENTORY_TRANSACTION_SUMMARY kits WHERE kits.UID = :uid AND kits.INV_ID = '10004' and kum.UID = :uid";
$statement = $dbObj->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$statement->execute(array(':uid'=>$uid));
$res = $statement->fetchAll(PDO::FETCH_ASSOC);
$sender_name = $res[0]['NAME'];
DON'T MIX PDO AND MYSQL FUNCTIONS
Looking more closely at the code, it looks like you are mixing PDO and mysql functions.
That's not valid. Don't mix calls to the two separate interface libraries.
The mysql_fetch_array function cannot be used to fetch from a PDO statement. Use the appropriate PDO fetch functions/methods.
There are three separate and distinct MySQL interface libraries in PHP.
There's the older (and now deprecated) mysql interface, all the functions from that interface start with mysql_.
There's the improved mysqli interface. The procedural style functions all begin with mysqli_.
And thirdly, there's the more database independent PDO interface.
Do not mix calls of these three separate interface libraries, because mixing calls won't work.
It looks like you're getting a connection with PDO, preparing a statement with PDO... but you are calling the msyql_error, mysql_num_rows and mysql_fetch_array functions. Replace those calls to the mysql_ functions with the appropriate PDO functions.
DOT CHARACTER IN COLUMN NAME?
It's very strange to include a dot character in a column name. (It's not invalid to do that, but something like that wouldn't fly in our shop.)
SELECT `KAP_USER_MAIN.UID` FROM `KAP_USER_MAIN` WHERE `KAP_USER_MAIN.IS_BOT` = 1
^ ^
But I'm suspicious that the column names are actually UID and IS_BOT, and that what you intended was:
SELECT `KAP_USER_MAIN`.`UID` FROM `KAP_USER_MAIN` WHERE `KAP_USER_MAIN`.`IS_BOT` = 1
^ ^ ^ ^
Each identifier (the column name and the table name) can be escaped separately. The dot character between the table name and the column name should not be escaped, because that's part of the SQL text, not part of the identifier.
We typically use a short table alias in our queries, so a typical query would look like this:
SELECT m.UID FROM `KAP_USER_MAIN` m WHERE m.IS_BOT` = 1
Or, for a query equivalent to the original query (with the dot character as part of the column name), like this:
SELECT m.`KAP_USER_MAIN.UID` FROM `KAP_USER_MAIN` m WHERE m.`KAP_USER_MAIN.IS_BOT` = 1
(That's not invalid, to include a dot character in a column name, but it is an unusual pattern, one that we don't see very often. I think that's because that pattern leads to more potential problems than whatever problem it was intended to solve.)
If the query works the way it is in your code, then that dot character must be part of the column name.

Apostrophe does not work in mysql/PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
apostrophes are breaking my mysql query in PHP
My Android App is sending a message to my server (PHP script)
The PHP script is writing the message into MySQL.
It works fine, but all messages containing an apostrophe ' (e.g. he's going to school) are not written into the database.
Here the php script:
function deq($s)
{
if($s == null)
return null;
return
get_magic_quotes_gpc() ?
stripslashes($s) : $s;
}
if(md5(deq($_REQUEST['blub']).deq($_REQUEST['blub'])."blabla") == $_REQUEST['hash']){
mysql_connect("localhost", "blub", "blub") or die(mysql_error());
mysql_select_db("blub") or die(mysql_error());
// mysql_set_charset('UTF8'); // does not work as too old php
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET COLLATION_CONNECTION = 'utf8_unicode_ci'");
$mysqldate = gmdate( 'Y-m-d H:i:s');
$language = (int) $_REQUEST['language'];
$device = $_REQUEST['device'];
$ipaddress = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO test(username, text, language, rating, checked, date)
VALUES('".$_REQUEST['username']."', '".$_REQUEST['text']."', '".$language."', '0' , 'false', '".$mysqldate."') ")
or die(mysql_error());
mysql_close();
All you need to escape ' like below
$_REQUEST['text'] = mysql_real_escape_string($_REQUEST['text']);
Don't use magic quotes.
use mysqli_real_escape_string or mysql_real_escape_string if you don't want to use mysqli.
You have discovered SQL injections: The apostrophe in the input "gets out" of the apostrophe you put in the query. This causes some of the input to be considered part of the query. You can use mysql_real_escape_string to secure the input before you use it in a query. But in general, there are better solutions for this (e.g. prepared statements).
You are, by the way, using the outdated mysql_ functions in PHP (see the big red warning on http://php.net/mysql_query)
Looking at the description above you need to escape input data with slashes using mysql_real_escape_string function
Apostrophe in input data when utilized in sql query will break the sql query resulting into sql injection
So always sanitize input data with mysql_real_escape_string() function before utilizing into sql query
For more documentation about mysql_real_escape_string() function please refer the documentation mentioned in below url
http://php.net/manual/en/function.mysql-real-escape-string.php

SQL and PHP problems

What is wrong with this query?
$query3 = "INSERT INTO Users
('Token','Long','Lat')
VALUES
('".$token."','".$lon1."','".$lat."')";
You have several issues with this.
Column names should be backtick escaped, not quoted (also LONG is a datatype in MySQL hence it's reserved and must be backtick-escaped).
You have SQL injection problems if those arguments aren't escaped.
You should provide us with the result of mysql_error() if it's not working.
Try running this code:
$token = mysql_real_escape_string($token);
$lon1 = mysql_real_escape_string($lon1);
$lat = mysql_real_escape_string($lat);
$query3 = "INSERT INTO `Users` (`Token`, `Long`, `Lat`)
VALUES ('{$token}', '{$lon1}', '{$lat}')";
$result3 = mysql_query($query3) or die("Query Error: " . mysql_error());
If that still doesn't work, give us the error message that's produced.
Long is the mysql reserved word and reserved words needs to be enclosed in backticks
$query3 = "INSERT INTO Users
(`Token`,`Long`,`Lat`)
VALUES
('".$token."','".$lon1."','".$lat."')";
You're using single quotes around your field names. This isn't valid in any SQL variant I know of. Either get rid of them or quote the field names in the correct way for your SQL flavor.
Your code likely has an SQL injection vulnerability, unless you left out the code that escapes $token etc
You shouldn't be putting values into the SQL string like that. This isn't the 1990s - we have parametrized queries now.
The mysql_ functions make it a bit difficult to do queries properly. Switch to either mysqli or PDO.

PHP syntax for postgresql Mixed-case table names

I have a code below:
<?php
require "institution.php"
/* in this portion, query for database connection is executed, and */
$institution= $_POST['institutionname'];
$sCampID = 'SELECT ins_id FROM institution where ins_name= '$institution' ';
$qcampID = pg_query($sCampID) or die("Error in query: $query." . pg_last_error($connection));
/* this portion outputs the ins_id */
?>
My database before has no mixed-case table names, that's why when I run this query, it shows no error at all. But because I've changed my database for some reasons, and it contains now mixed-case table names, i have to change the code above into this one:
$sCampID = 'SELECT ins_id FROM "Institution" where ins_name= '$institution' ';
where the Institution has to be double quoted. The query returned parse error.
When i removed this portion: where ins_name= '$institution', no error occured.
My question is how do I solve this problem where the table name which contains a mixed-case letter and a value stored in a variable ($institution in this case) will be combined in a single select statement?
Your answers and suggestions will be very much appreciated.
You can use the double quote instead
$sCampID = "SELECT ins_id FROM \"Institution\" where ins_name= '$institution'";
<?php
require "institution.php"
/* in this portion, query for database connection is executed, and */
$institution= pg_escape_string($_POST['institutionname']);
$sQuery = "SELECT ins_id FROM \"Institution\" where ins_name= '$institution'";
$qcampID = pg_query($sQuery)
or trigger_error("Error in query: $sQuery." . pg_last_error($connection));
/* this portion outputs the ins_id */
?>
Note
pg_escape_string as it ought to be used, not to protect from any injections but as just a part of the syntax.
trigger_error which should be used instead of echo (and note proper variable name)
and double quotes or your variable won't be extrapolated ( http://php.net/types.string for ref)
and slashes at double quotes (same ref)
$sCampID = 'SELECT ins_id FROM "Institution" where ins_name= \''.$institution.'\'';
String escaping.
As another commenter posted, read about SQL injection. What I have is not injection safe, consider using something with prepared statements, preferably PDO.
To add to other answers (quote the table name, and use prepared statements to gain security and performance), read about PG and tables case sensitivity. If you have the option, you might consider to change your db schema, so that tables names (and columns and identifiers in general) are all lowercase. That would simplify a little your queries - (but require you to check all your actual quoted queries and unquote them).
What happens if $institution contains the following string: ' or 1 = 1; --
That's what we call an SQL injection attack, and it's a super-easy way for hackers to steal your data -- and get you into big trouble with your customers.
You need to escape that string using pg_escape_string() before putting it into an SQL query. I like to use sprintf() to build my queries:
$sql = sprintf("SELECT ins_id FROM \"Institution\" where ins_name= '%s'", pg_escape_string($conn, $institution));
In the above example, $conn is the connection identifier, created by calling pg_connect().

Categories