Escaping SQL queries in Codeigniter - php

I am inserting some data into a MySQL table using CodeIgniter. Because I am using INSERT IGNORE INTO and do not want to edit the active records class to enable this feature, I am generating the SQL query manually.
$this->db->query("INSERT IGNORE INTO my_table(lat, lng, date, type)
VALUES ('" . $data['lat'] . "', '" . $data['lng'] . "', '" . $data['date'] . "', '" . $data['type'] . "')");
Problem: The query failed when the string in $data['type'] contained a single quote. How can I make it such that these characters that need to be escaped gets escaped automatically, like when using Active records?

Another way is to use Query Binding which automatically escapes all the values:
$sql = "INSERT IGNORE INTO my_table(lat, lng, date, type) VALUES (?,?,?,?);";
$this->db->query($sql, array($data['lat'], $data['lng'], $data['date'], $data['type']));

use $this->db->escape(); it will escape the string automatically
This function determines the data type so that it can escape only
string data. It also automatically adds single quotes around the data
so you don't have to:
$this->db->query("INSERT IGNORE INTO my_table(lat, lng, date, type)
VALUES ('" . $this->db->escape($data['lat']) . "', '" . $this->db->escape($data['lng']) . "', '" . $this->db->escape($data['date']$this->db->escape . "', '" . $this->db->escape($data['type']) . "')");
Here is the reference Click Here

Related

Can't insert now() in PHP

I am a beginner programmer trying to insert the the now() value into my field date. I have achieved this before and copied the structure word by word but still does not work. I have also viewed other stackoverflow questions and I think that my database structure is correct. Here is INSERT php code:
try{
$conn = new mysqli("xxxxx", "xxxxx", "xxxxxxxx", "xxxxxxx");
$userid = $_GET['userid'];
$title = $_GET['title'];
$comment = $_GET['comment'];
$query = "INSERT into enquiries (userid, title, comment, Resolved, date)
values ('" . addslashes($userid) . "','" . addslashes($title) . "','" . addslashes($comment) . "', N, now() )";
$result = $conn->query($query);
if (!$result){
$json_out = "[" . json_encode(array("result"=>0)) . "]";
}
else {
$json_out = "[" . json_encode(array("result"=>1)) . "]";
}
echo $json_out;
$conn->close();
}
This set of codes worked and inserted values before I added now()
Here is my table structure:
Here is my other table structure that inserted now() just fine:
Your "Resolved" value needs to be in quotes, because you have it defined as a varchar. This would be the case for any of the "char" family of datatypes.
$query = "INSERT into enquiries (userid, title, comment, Resolved, date)
values ('" . addslashes($userid) . "','" . addslashes($title) . "','" . addslashes($comment) . "', 'N', now() )";
Hope this helps!
Sometimes database has some restrictions.. So try using like this NOW() than now() or else use CURDATE().

MySQL inserts values into wrong columns

Problem
With a php website, I have a form to collect information which will then be inserted into the MySQL database, but there are these three columns that have the wrong values inserted into them. The rest are all in the correct order.
Values inserted as php variables via MySQL transaction.
Thank you for your time.
phpmyadmin display (first row is manually corrected)
Code:
<?php
function registerPatient($ptUsername, $ptPassword, $ptFirstName, $ptLastName, $ptSalutation, $ptEmail, $ptDOB, $ptPostCode, $ptHouseNo, $ptTelNo, $link)
{
$accType = "Patient";
$dtID = $_COOKIE["ID"];
$errors = "";
$SQL_patientInsert =
"START TRANSACTION;
INSERT INTO accDetails (`username`, `hashPassword`, `accType`)
VALUES ('" . $ptUsername . "',
'" . $ptPassword . "',
'" . $accType . "');
INSERT INTO ptProfile (`firstName`, `lastName`, `salutation`, `email`, `DOB`, `postCode`, `houseNo`, `telephoneNo`, `dtID`, `ptID`)
VALUES ('" . $ptFirstName . "',
'" . $ptLastName . "',
'" . $ptSalutation . "',
'" . $ptEmail . "',
'" . $ptDOB . "',
'" . $ptPostCode . "',
'" . $ptHouseNo . "',
'" . $ptTelNo . "',
'" . $dtID . "',
LAST_INSERT_ID());
COMMIT;";
if (mysqli_multi_query($link, $SQL_patientInsert)) {
$errors .= "";
} else {
$errors .= "MYSQL Error: ". mysqli_error($link);
}
return $errors;
}
?>
Var_Dump of $SQL_patientInsert
string(495) "START TRANSACTION; INSERT INTO accDetails (`username`, `hashPassword`, `accType`) VALUES ('bingbong', '$2y$10$WDvSHSxzIxaYB8dPGLRIWOFyIdPXxSw5JDXagOxeYuJUtnvFhI.lO', 'Patient'); INSERT INTO ptProfile (`firstName`, `lastName`, `salutation`, `email`, `DOB`, `postCode`, `houseNo`, `telephoneNo`, `dtID`, `ptID`) VALUES ('Dr', 'Bing', 'Bong', 'EMAIL REMOVED FOR SO', '1996-08-02', 'POSTCODE REMOVED FOR SO', '7', '83824', '1256', LAST_INSERT_ID()); COMMIT;"
Table Structure
Table Structure in PHPMyAdmin, no autoincrements, all values allowed to be null
Your are calling your function with wrong parameters order.
Change this line ($ptFirstName <-> $ptSalutation);
function registerPatient($ptUsername, $ptPassword, $ptFirstName, $ptLastName, $ptSalutation, $ptEmail, $ptDOB, $ptPostCode, $ptHouseNo, $ptTelNo, $link)
with
function registerPatient($ptUsername, $ptPassword, $ptSalutation, $ptFirstName, $ptLastName, $ptEmail, $ptDOB, $ptPostCode, $ptHouseNo, $ptTelNo, $link)
I think you just mixed up your variables somewhere. Have you checked the form? Try printing out all the variables right before you build the query and check if they correspond correctly.

Is there a prob with my MySQLi/PHP code?

I am new to all this MySQLi, and I can't seem to find any useful information that works for me.. I've tried the following code, but to no avail:
if(isset($_GET['submit']))
{
$stamp = date("D M d, Y G:i a");
$mysqli->query("INSERT INTO down (timestamp, username) VALUES ('" . $stamp . "', '" . USER_NAME . "')");
}
I am unaware as to what I'm doing wrong, so maybe some insight? Or it would be great if someone could reference me to some websites? Hence nothing seems to work for me!
HTML is:
<form method="post">
<b>Submit a downtime report*</b>: <input type="submit" name="submit" value="Report">
</form>
You don't have to use date() function in PHP. You can use NOW() or CURRENT_TIMESTAMP() in MySQL
$mysqli->query("INSERT INTO down (`timestamp`, `username`) VALUES (NOW(), '" . USER_NAME . "')");
More date functions you can find here
I guess USER_NAME is a constant and it's set.
As for useful resources, have you tried the official documentation ?
http://php.net/manual/en/book.mysqli.php
It seems to be pretty comprehensive.
Change this to
$mysqli->query("INSERT INTO down (timestamp, username) VALUES ('" . $stamp . "', '" . USER_NAME . "')");
to
$mysqli->query("INSERT INTO down (`timestamp`, `username`) VALUES ('" . $stamp . "', '" . USER_NAME . "')");
Reason: timestamp is also a type in SQL hence you should use it like that.
"timestamp" is a MySQL keyword and so is interpreted as a data type rather than a column name and then the syntax doesn't make any sense. You can solve this by escaping the column name using back ticks. This is a good practice for all table and column names by the way, regardless of whether they are keywords or not. So changing the query as follows should work:
$mysqli->query("INSERT INTO `down` (`timestamp`, `username`) VALUES ('" . $stamp . "', '" . USER_NAME . "')");

mysql insert query in a php script is not working

I have a php script that take data from a table and then try to insert the obtained data in a second table copy of the first one:
function copy_data($id,$mysql_conn){
if($res=mysql_query("SELECT * from table1 WHERE id='".$id."'", $mysql_conn)){
if($row=mysql_fetch_array($res)){
$sql ="INSERT INTO table2 (id, Field1, Field2) values('" . $row['id'] . "', '" . $row['Field1'] . "', '" . $row['Field2'] . "')";
mysql_query($sql,$mysql_conn);
}
}
}
copy_data($id,$mysql_conn);// $id is id of the element I want to add
The insert query works fine but there is one case that makes an exception :one of the field contains a ' character, exp of a query that failed:
INSERT INTO table2 (id, Field1, Field2) values ('12','Company', 'Kurt's Reifen-Shop') the exception comes from the ' character how to insert php variables that do contain this character.
You have to escape the data before insert them into $sql:
function copy_data($id,$mysql_conn){
if($res=mssql_query("SELECT * from table1 WHERE id='".$id."'", $mysql_conn)){
if($row=mysql_fetch_array($res)){
$row['Field1'] = mysql_real_escape_string($row['Field1']);
$row['Field2'] = mysql_real_escape_string($row['Field2']);
$sql ="INSERT INTO table2 (id, Field1, Field2) values('" . $row['id'] . "', '" . $row['Field1'] . "', '" . $row['Field2'] . "')";
mysql_query($sql,$mysql_conn);
}
}
}
copy_data($id,$mysql_conn);// $id is id of the element I want to add
You can do it with a single statement:
$id = mysql_real_escape_string($id);
INSERT INTO table2 (id, Field1, Field2) SELECT id, Field1, Field2 FROM table1 WHERE id='".$id."'"
i dont understand how you managed to put that ' in to the first table but you should use
mysql_real_escape_string
like $field1 = mysql_real_escape_string($row['Field1']);
than put the $field1 as it will be safe now

SELECT LAST_INSERT_ID() *updated

I'm looking to use SELECT LAST_INSERT_ID()
Am using a form to have a user input values. With the first insert I need to get the last inserted id for the next insert... I have not figured out how to get the last selected id and then pass it into my 2nd insert statement
I have updated my code though I still can not get the id to post into the table
include("config.inc.php");
$link = mysql_connect($db_host,$db_user,$db_pass);
if(!$link) die ('Could not connect to database: '.mysql_error());
mysql_select_db($db_name,$link);
$query = "INSERT into `".$db_table."` (producer_id,series_id,lang_id,title_name,title_public_access) VALUES ('" . $_POST['producer_id'] . "','" . $_POST['series_id'] . "','" . $_POST['lang_id'] . "','" . $_POST['title_name'] . "','" . $_POST['title_public_access'] . "')";
$last_id = mysql_insert_id();
$query = "INSERT into `".$db_table2."` (seg_id, file_video_UNC,file_video_URL) VALUES ('" . '$last_id' . "','" . $_POST['file_video_UNC'] . "','" . $_POST['file_video_URL'] . "')";
mysql_query($query);
mysql_close($link);
There's a function for that, called mysql_insert_id().
... first query here ...
$last_id = mysql_insert_id();
$sql = "INSERT INTO $db_table SET
file_video = " . $_POST['file_video_UNC'].",
file_video_URL = " . $_POST['file_video_URL'] . ",
insert_id_of_first_query = $last_id";
...
Your updated code doesn't send the query to database - as a result no INSERT, so no LAST_INSERT_ID
$query = "INSERT into ".$db_table."
(producer_id,series_id,lang_id,title_name,title_public_access) VALUES
('" . $_POST['producer_id'] . "','"
. $_POST['series_id'] . "','"
. $_POST['lang_id'] . "','" . $_POST['title_name'] . "','"
. $_POST['title_public_access'] . "')";
mysql_query($query); /* YOU FORGOT THIS PART */
$last_id = mysql_insert_id();
You can't just dump a query into a string on its own in a line of PHP. You should have used LAST_INSERT_ID() inside your second query or, better, use PHP's mysql_insert_id() function which wraps this for you in the API.
In the line:
$query = "INSERT into `".$db_table2."` (seg_id, file_video_UNC,file_video_URL) VALUES ('" . '$last_id' . "','" . $_POST['file_video_UNC'] . "','" . $_POST['file_video_URL'] . "')";
I think VALUES ('" . '$last_id' . "', should just be VALUES ('" . $last_id . "', without the single quotes around the variable.

Categories