Problems with mysql_real_escape_string - php

I have field called filter1 on a form, I would like to be able to save quoted text into mysql. So I would like to be able to save the value "foo bar"...instead its saving just /
Here is what I have:
$keyword1 = mysql_real_escape_string($_POST['filter1']);
Any help is appreciated.
Here is how I construct the query
$keyword1 = mysql_real_escape_string($_POST['filter1']);
$keyword2 = $_POST['filter2'];//."|".$_POST['filterby'];
$keyword3 = $_POST['filter3'];//."|".$_POST['filterby2'];
$urlfilter1 = $_POST['url1'];
$urlfilter2 = $_POST['url2'];//."|".$_POST['url_filter'];
$urlfilter3 = $_POST['url3'];//."|".$_POST['url_filter2'];
//echo "combo_id:".$num." <BR></br>";
//echo "status:".$status." <BR></br>";
//echo "saveQuery:".$saveQuery." <BR></br>";
//$myFilter = "save";
$insert_query = sprintf("UPDATE COMBINATION
SET STATUS_ID=%s, QUERY=\"%s\",
KEYWORD1=\"%s\", KEYWORD2=\"%s\", KEYWORD3=\"%s\",
URLFILTER1=\"%s\", URLFILTER2=\"%s\", URLFILTER3=\"%s\"
WHERE COMBINATION_ID=%s",$status,$saveQuery,
$keyword1,$keyword2,$keyword3,
$urlfilter1,$urlfilter2,$urlfilter3,
$num);
//echo "insert_query:".$insert_query." <BR></br>";
$result = mysql_query($insert_query) or die(mysql_error());
if($result)
{
echo "Saved successfully<br>";
}
}
?>

Unless you have a very old and restricted environment, use PDO. It will save you buckets of sweat and tears. With PDO it is very easy to escape input and avoid SQL injection attacks, which is illustrated in the answer that this link leads to.

Well first you need to connect to the database with mysql_connect() http://php.net/manual/en/function.mysql-connect.php
Then you need to call your INSERT query with mysql_query() http://php.net/manual/en/function.mysql-query.php
By the way, you are doing the right thing by escaping the string before putting it into a query, well done :)

For some reason you are escaping only one variable, while adding to the query several of them.
Why don't you escape them all?
However, your problem may be somewhere else.
What is $saveQuery I am curious?

Related

Update and Insert into three tables simultaneously

I have a record that needs to be updated. If the update is successful, then it should insert record into three different tables. I did it with the code below,but one of the table(tab_loan_targetsave)is not inserting.I need a third eye to looked into this, as I have had a lot of pain in fathoming where the problem lies.
Pls i need assistance.Also, I welcome better approach if possible.
<?php
if(isset($_POST["savebtn"])){
$custNo = $_POST["custid"];
$transDate = $_POST["transDate"];
$grpid = $_POST["custgrp"];
$contAmount =$_POST["amtCont"];
$amount = $_POST["amount"];
$disAmount =$_POST["disbAmt"];
$savAmount =$_POST["savAmt"];
$intAmount =$_POST["intAmt"];
$postedBy = $_SESSION["staffid"];
//$preApproved =$_POST["preAmount"];
$loanRef = $_POST["refid"];
$st = "Approved";
$appDate = date("Y-m-d H:i:s");
$appBy = $_SESSION['staffid'];
$counter = 1;
$locate = $_SESSION['location'];
$insure = $_POST["insuAmt"];
$dis = $_POST["DisAmt"];
$update = mysqli_query($connection,"UPDATE tab_loan_request SET approval_status='$st',approvalDate='$appDate',approvedBy='$appBy',loanRef='$loanRef' WHERE custid='$custNo' AND RepayStatus='1'");
if($update && mysqli_affected_rows($connection)>0){
$insertTar = mysqli_query($connection,"INSERT INTO tab_loan_targetsave(custid,grpid,transactionDate,loanRef,savingAmt,status,postedBy,location,appStatus)
VALUES('$custNo','$grpid','$transDate','$loanRef,'$savAmount','Cr','$postedBy','$locate','1')");
$insertInt = mysqli_query($connection,"INSERT INTO tab_loan_interest(custid,requestAmt,transactionDate,interestFees,postedBy,loanRef,InsuranceFees,DisasterFees)VALUES(
'$custNo','$amount','$transDate','$intAmount','$postedBy','$loanRef','$insure','$dis')");
//if($insertInt){
//}if($insertTar){
$insertSav = mysqli_query($connection,"INSERT INTO tab_loan_saving(custid,grpid,transactionDate,loanRef,loanAmount,savingAmt,status,postedBy,location,appStatus)
VALUES('$custNo','$grpid','$transDate','$loanRef','$amount','0','Cr','$postedBy','$locate','1')");
}//first if
if($insertSav){
echo "<span style='font-weight:bold;color:red;'>"." Application Approval is successful!"."</span>";
}else{
//Unable to save
echo "<span style='font-weight:bold;color:black;>"."Error! Application Approval not Successful!"."</span>";
}
}else{
$custid = "";$saving=0.00;$st="";
$transDate = "";
$grpid = "";
$amount = "";
$postedBy = "";$loanRef="";
}
?>
"#Fred: See the error generated when i used mysqli_error($connection). Could you please interprete this: ErrorMessage: 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 '1000.00','Cr','SPL002','Ojo','1')' at line 2 – Dave"
Seeing the error generated by the suggestion I've given you to check for errors.
You're missing a quote here '$loanRef
in your query:
VALUES('$custNo','$grpid','$transDate','$loanRef , '$savAmount'...
^ right there
I suggest to escape all of your incoming data.
I.e.:
$var = mysqli_real_escape_string($connection, $_POST['var']);
and apply that same logic to all your POST arrays.
Plus, as I stated; make sure you started the session, since there is no mention of that in your question and session_start(); wasn't included in your posted code.
The session needs to be started inside all pages using sessions.
Using a prepared statement will is better.
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/pdo.prepared-statements.php
which is what you really should be using.
Additional references:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting
Also make sure there aren't any constraints in your table(s).
Dude make sure you properly escape your variables http://php.net/manual/en/mysqli.prepare.php
i would check the Table Name! make sure it is case sesntive, also just wondering if you could do something to your database design? It seems a lot of duplicate data is going into your tables. Think about a better way to organise and store that data
I got where the error is emanting from . Just because I forgot to add a single quote to one of the values. ie missing the quote- near $loanRef. No closing string. Anyway, I was able to detect that through the error message stated parameter as adviced by Fred nad Mark. Correct
$insertTar = mysqli_query($connection,"INSERT INTO tab_loan_targetsave(custid,grpid,transactionDate,loanRef,savingAmt,status,postedBy,location,appStatus)
VALUES('$custNo','$grpid','$transDate','$loanRef','$savAmount','Cr','$postedBy','$locate','1')");
Thank you all.

Can't save serialized array in longtext field

I am attempting to save a serialized array to a LONGTEXT field and for some reason the data is not saving and I am not getting an error.
$serializeArray = serialize($result_arr) ;
echo "Serialized String: " . $serializeArray ."<br><br>";
$test2 = "This is a test" ;
$return = mysqli_query($con,"UPDATE mytable.exp_cartthrob_item_options_options SET data = '" . $serializeArray ."' WHERE id = '1' " );
echo "<br /><br />" ;
echo $return ;
If I replace $serializeArray with $test it works fine. Any ideas on whats wrong?
First of all, serializing data will leave in quotes and special characters, so you are likely going to be generating an invalid query with the way you are doing it. You really need to be using prepared statements to ensure you will have valid queries. Not to mention you can end up with all kinds of nasty SQL injection attacks - just use prepared statements.
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Second, storing serialized data in your database is generally a very poor practice since the data is no longer portable. You have a relational database with various datatypes - use them!
To highlight the risk posed by not using prepared statements, consider if the array to be serialized looked like this:
$resultArray = array("';DROP TABLE mytable;##");
Guess whats going to happen...
Update to help:
Here is how you would write your query using prepared statements - you will need to make sure you are validating each step to catch and handle errors.
Step 1: Write your query - the "?" is where you will bind your parameters
$query = "UPDATE mytable.exp_cartthrob_item_options_options SET data = ? WHERE id = '1'";
Step 2: Create the Prepared Statement
$stmt = $con->prepare( $query );
Step 3: Bind your paramters (the "?" in the query)
$stmt->bind_param( "s" , $serializeArray );
Step 4: Execute the Query
$stmt->execute();
You should ideally read through the entire mysqli documentation so you know what methods are available to you.

MYSQL & PHP trouble with echoing tables

So I am trying to echo out how many rows there are in a table with a COUNT command, but I purposely have no rows in the table right now to test the if statement, and it is not working, but worst, it makes the rest of the site not work(the page pops up but no text or numbers show up on it), when I added a row to the table, it worked fine, no rows = no work. Here is the piece of the code that doesn't work. Any and all help is highly appreciated.
$query1 = mysql_query("
SELECT *, COUNT(1) AS `numberofrows` FROM
`table1` WHERE `user`='$username' GROUP BY `firstname`,`lastname`
");
$numberofrowsbase = 0;
while($row = mysql_fetch_assoc($query1))
{
if(isset($row['numberofrows']))
{
$enteries1 = $enteries1;
}else{
$enteries1 = $numberofrowsbase;
}
echo enteries1;
}
Seems you have over complicated everything. Some good advise from worldofjr you should take onboard but simplest way to get total rows from a table is:
SELECT COUNT(*) as numberofrows FROM table1;
There are several other unnecessary lines here and the logic is all bonkers. There is really no need to do
$enteries1 = $enteries1;
This achieved nothing.
Do this instead:
while($row = mysql_fetch_assoc($query1))
{
if(isset($row['numberofrows']))
{
echo $row['numberofrows'];
}
}
Maybe against my better judgement, I'm going to try and give you an answer. There's so many problems with this code ...
Do Not Use mysql_
The mysql_ extension is depreciated. You should use either mysqli_ or PDO instead. I'm going to use mysqli_ here.
SQL Injection
Your code is wide open to SQL injection where others can really mess up your database. Read How can I prevent SQL injection in PHP? for more information.
The Code
You don't need to count the rows with a SQL function, especially if you want to do something else with the data you're getting with the query (which I assume you are since you're getting a count on top of all the columns.
In PHP, you can get how many rows are in a result set using a built in function.
So all those things together. You should use something like this;
// Connect to the database
$mysqli = new mysqli($host,$user,$pass,$database); // fill in your connection details
if ($mysqli->connect_errno) echo "Error - Failed to connect to database: " . $mysqli->connect_error;
if($query = $mysqli->prepare("SELECT * FROM `table1` WHERE `user`=?")) {
$query->bind_param('s',$username);
$query->execute();
$result = $query->get_result();
echo $result->num_rows;
}
else {
echo "Could not prepare query: ". $mysqli->error;
}
The number of rows in the result is now saved to the variable $result->num_rows, so you can use just echo this if you want, like I have in the code above. You can then go onto using any rows you got from the database. For example;
while($row = $result->fetch_assoc()) {
$firstname = $row['firstname'];
$lastname = $row['lastname'];
echo "$firstname $lastname";
}
Hope this helps.

SQL Table not updating in PHP

I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows

Escaping MySQL Query issue

I'm terribly bad at keeping MySQL queries straight, but that aside I have one query working for some data input, but not all. My guess is quotation marks getting escaped where they should be.
I have the entire query string get escaped at the same time. Is this bad practice or does it really matter?
Here's the query:
"INSERT INTO bio_manager_pubs(userid,category,citation,date,link,requests) VALUES ( ".
$userid.",'".
$_POST['category']."', '".
htmlentities($_POST['pub'])."',
FROM_UNIXTIME(".strtotime($_POST['date'])."),'".
$_POST['link']."',
0)"
In query:
Userid and requests are ints
Link and Category are Tiny Text (not sure if that's appropriate, but max is 255 char, so would VarChar be better?)
Date is a date (is it better to reformat with php or reformat with mysql?)
Citation is a text field
Any ideas?
Thanks
EDIT:
The answer to this question was posted four times there abouts where the issue was me escaping the entire query.
What was left out, and cause some confusion was the code surrounding the query.
It was like this
$db->query($query)
This where the function query was:
public function query($SQL)
{
$this->SQL = $this->mysqli->real_escape_string($SQL);
$this->result = $this->mysqli->query($SQL);
if ($this->result == true)
{
return true;
}
else
{
printf("<b>Problem with SQL:</b> %s\n", $this->SQL);
exit;
}
}
I just found a class that made life a bit simpler on smaller projects and stuck with it. Now, the issue I'm running into is removing $this->mysqli->real_escape_string($SQL); and adding in escapes elsewhere in the code.
I really don't see any sanitizing of your $_POST data, and there is really no need to run htmlentities before you insert into the database, that should be done when you take that data and display it on the page. Make sure to sanitize your posts!! Using mysql_real_escape_string() or preferably PDO with prepared statements.
If you are running mysql_real_escape_string() on this whole query, after you build it, than that is what is breaking it.
Use it on the individual posts, and / or cast variables that should only ever be numbers to integers.
Heres what I would change it to in your case:
$posted = $_POST;
foreach($posted as &$value)
$value = mysql_real_escape_string($value);
$date = strtotime($posted['date']);
$q = "INSERT INTO bio_manager_pubs(userid,category,citation,date,link,requests) VALUES
(
'{$userid}',
'{$posted['category']}',
'{$posted['pub'])}',
FROM_UNIXTIME({$posted['date']}),
'{$posted['link']}',
'0'
)";
I believe it is considered bad practice to build the entire query and then escape the whole thing. You should sanitize the inputs as soon as they enter the code, not after you've started using them to build your database interactions.
You'd want to sanitize each input, kind of like this:
$category = mysql_real_escape_string($_POST['category'])
And then you'd use the local variables, not the inputs, to build your SQL command(s).
Also, you may want to look into something like PDO for your data access, which manages a lot of the details for you.
I think you need to wrap each of your inputs in mysql_real_escape_string (only once!), not the whole query. Other than that it looks OK to me.
"INSERT INTO bio_manager_pubs(userid,category,citation,date,link,requests) VALUES ( ".
mysql_real_escape_string($userid).",'".
mysql_real_escape_string($_POST['category'])."', '".
mysql_real_escape_string(htmlentities($_POST['pub']))."',
FROM_UNIXTIME(".mysql_real_escape_string(strtotime($_POST['date']))."),'".
mysql_real_escape_string($_POST['link'])."',
0)"
Instead of escaping the entire SQL query (which can run the risk of breaking things), just escape the user's input:
$userid = mysql_real_escape_string($userid);
$cat = mysql_real_escape_string($_POST['category']);
$pub = mysql_real_escape_string($_POST['pub']);
$date = strtotime($_POST['date']);
$link = mysql_real_escape_string($_POST['link']);
$query = "INSERT INTO bio_manager_pubs(userid, category, citation, date, link, requests)"
." VALUES ($userid, '$cat', '$pub', $date, '$link', 0 );";
Well for a start you should avoid using data from external sources directly in a query, so I would rewrite the code so as not to use $_POST in your query. Even better if you can to use PDO or similar to escape your data. And I would avoid converting text with htmlentities before inserting it into your database. You're better off doing that after you pull it from the database as you will then be able to use that data in other (non-HTML) output contexts.
But in terms of inline code, do you have magic_quotes on?
Try something like this
if (get_magic_quotes_gpc()) {
$category = stripslashes($_POST['category']);
$pub = stripslashes($_POST['pub']);
$link = stripslashes($_POST['link']);
} else {
$category = $_POST['category'];
$category = $_POST['category'];
$category = $_POST['category'];
}
$category = mysql_escape_string( $category );
$pub = mysql_escape_string( $pub );
$link = mysql_escape_string( $link );
$sql = "
INSERT INTO bio_manager_pubs(userid,category,citation,date,link,requests) VALUES (
". $userid.",
'$category',
'$pub',
FROM_UNIXTIME(".strtotime($_POST['date'])."),
'$link',
0
)";
Turn off magic_quotes_gpc and use prepared statements.
With magic_quotes_gpc disabled, you don't end up with automatic escaping of input - and magic_quotes_gpc is deprecated anyway.
Use parameter binding prepared statements to avoid SQL injection rather than escaping characters. I personally suggest using PDO or MDB2 to talk to your db, but you can also do prepared statements with the mysqli driver. Note that the mysql driver is on the chopping block as well, so you soon will be forced to either use mysqli or an abstraction layer like MDB2.
I bet though that magic_quotes_gpc is your problem.

Categories