mysql insert query in a php script is not working - php

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

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().

check tuple data before inserting sql query - php

I am trying to check the database tables for data before entering new data and avoiding the dublicates.
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')
SELECT " . $columnData . " FROM " . $columns . "
WHERE NOT EXISTS (SELECT '" .$columnData . "'
FROM " . $table . " WHERE '" . $columnData . "' = '" . $columnData . "')";
The query does not throw any errors, although the query is not executed as expected.
Thanks in advance
to avoid duplicate entrys just use INSERT IGNORE
If you want to update when it's a duplicate use Insert ... ON DUPLICATE KEY UPDATE...
If you want to avoid duplicates, then create a unique constraint or index on the columns you want to be unique:
create unique index idx_table_cols on table(col1, col2, . . .);
Then the database will prevent duplicates. If you want the insert to fail silently instead of generating an error, you can use insert ignore, but I would recommend insert on duplicate key update:
insert into table(col1, col2, . . .)
select <values>
from . . .
on duplicate key update col1 = values(col1);
I am giving you example with all conditions please check it
First step would be to set a unique key on the table:
ALTER TABLE thetable ADD UNIQUE INDEX(pageid, name);
Then you have to decide what you want to do when there's a duplicate. Should you:
ignore it?
INSERT IGNORE INTO thetable (pageid, name) VALUES (1, "foo"), (1, "foo");
Overwrite the previously entered record?
INSERT INTO thetable (pageid, name, somefield)
VALUES (1, "foo", "first")
ON DUPLICATE KEY UPDATE (somefield = 'first')
INSERT INTO thetable (pageid, name, somefield)
VALUES (1, "foo", "second")
ON DUPLICATE KEY UPDATE (somefield = 'second')
Update some counter?
INSERT INTO thetable (pageid, name)
VALUES (1, "foo"), (1, "foo")
ON DUPLICATE KEY UPDATE (pagecount = pagecount + 1)

MySQL Insert statement not executing

I am trying to run an mySQL insert statement like so:
function insertAppointment($connection, $id, $firstname, $lastname, $email, $phone, $date, $time){
$sql = "INSERT INTO `appointments` (firstname, lastname, email, phone, app_date, app_time) VALUES ('" . $id . "', '" . $firstname . "', '" . $lastname . "', '" . $email . "', " . $date . ", " . $time . ")";
$connection->query($sql);
}
$connection is my connection string, which is not the problem. I am able to use it for select statement like so:
function getTakenDates($connection){
$query = mysqli_query($connection, "SELECT app_date, app_time FROM `appointments`");
$results = array();
while($row = mysqli_fetch_assoc($query)){
$results[] = $row;
}
return $results;
}
You are vulnerable to SQL injection attacks, and are creating an incorrect query with your $date/$time values:
INSERT .... VALUES (..., 2014-11-10, 14:58:00)
since your date value is unquoted, you'll actually be trying to insert the result of that math operation (remember - is SUBTRACTION if it's not in a string), and 14:58:00 is a totally invalid number - mysql has no idea what those : chars are.
You want
$sql = "[..snip..] "', '" . $date . "', '" . $time . "')";
^-------------^--^-------------^----
instead. note the extra quotes. That'll produce
INSERT .... VALUES (..., '2014-11-10', '14:58:00')

Inserting 2 different array values into database does not work

I'm trying to insert 2 values from arrays into a database. There's nothing wrong with the connection, the fields where $fullArr and $thumbArr get inserted are longtexts, and when I try to insert 1 array value it works fine ($fullArr or $thumbArr). As soon as both arrays get used in the query it stops working.
The values in the arrays are data-urls.
private function submitPhoto() {
global $database;
$projectid = $_POST['projectid'];
$fullArr = $_POST['fullArr'];
$thumbArr = $_POST['thumbArr'];
$count = 0;
foreach($thumbArr as $key) {
// Insert Thumb
$database->query("INSERT INTO `photo` (photoid, projectid, dataurlfull, dataurlthumb) VALUES('', '" . $projectid . "', '" . $fullArr[$count] . "', '" . $key . "')");
$count++;
}
}
Try changing the query:
$database->query("INSERT INTO `photos` (photoid, projectid, dataurlfull, dataurlthumb) VALUES('', '$projectid', '$fullArr[$count]', '$key')");
Is it possible you are not executing the query inside the foreach() loop, so the last one will 'overwrite' any that you had before? Also, the $count is not necessary as you can use the $key. Try something like-
foreach($thumbArr as $key=>$value) {
// Insert Thumb
$database->query("INSERT INTO `photo` (photoid, projectid, dataurlfull, dataurlthumb) VALUES('', '" . $projectid . "', '" . $fullArr[$key] . "', '" . $thumbArr[$key] . "')");
$database->execute();
}
Be aware that you are open to SQL injection as you are using $_POST data without sanitizing. If you are using mysqli_ or PDO, use paramatized statements
foreach($thumbArr as $key=>$value) {
// Insert Thumb
$database->query("INSERT INTO `photo` (photoid, projectid, dataurlfull, dataurlthumb) VALUES('', ?, ?, ?)");
$database->bindParam(1,$projectid);
$database->bindParam(2,$fullArr[$key]);
$database->bindParam(3,$thumbArr[$key]);
$database->execute();
}

Escaping SQL queries in Codeigniter

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

Categories