MySQL always overwrite existing database entry (UPDATE, REPLACE, INSERT ????) - php

I would like to always replace the same existing database entry.
The following code always creates a new entry, How do I have to modify that it always overwrites "version"?
$sql = "REPLACE INTO `traumprojekt`
(`version`, `geschlecht`, `alter`, `fuehrerschein`)
VALUES(
'" .mysql_real_escape_string( $version ). "',
'" .mysql_real_escape_string( $geschlecht ). "',
" .$alter. ",
" .$fuehrerschein. "
)";
mysql_query( $sql );

REPLACE is just an insert, that will "delete" the old row before adding a new.
It can only determine an "old" row if there are constraints that mark the new row as "existing".
Your replace statement is OK, but you should add a UNIQUE INDEX on geschlecht, alter, fuehrerschein so it can just change the version.
An alternative can be INSERT ... ON DUPLICATE KEY UPDATE, but you also need a unique key there. The difference is that REPLACE does a DELETE, then INSERT; while INSERT ... ON DUPLICATE KEY UPDATE does an UPDATE instead of the INSERT. It matters with for example triggers...

Personally, I would use UPDATE instead. For example:
REPLACE INTO `traumprojekt`
(`version`, `geschlecht`, `alter`, `fuehrerschein`)
VALUES(
'" .mysql_real_escape_string( $version ). "',
'" .mysql_real_escape_string( $geschlecht ). "',
" .$alter. ",
" .$fuehrerschein. "
)
WHERE
/* Your condition here */;

Create a unique key on some of the columns. This way the script will insert once when there is no data and then will update when the column key duplicates. Lets say you create an unique index on the version column:
$sql = "INSERT INTO `traumprojekt`
(`version`, `geschlecht`, `alter`, `fuehrerschein`)
VALUES(
'" .mysql_real_escape_string( $version ). "',
'" .mysql_real_escape_string( $geschlecht ). "',
" .$alter. ",
" .$fuehrerschein. "
) ON DUPLICATE KEY UPDATE
`geschlecht`='" .mysql_real_escape_string( $geschlecht ). "',
`alter`=" .$alter. ", `fuehrerschein`= " .$fuehrerschein;
Or, if you want to have only one record in your table, then you can create an unique column called Id as TinyINT and base your logic on it:
$sql = "INSERT INTO `traumprojekt`
(`id`,`version`, `geschlecht`, `alter`, `fuehrerschein`)
VALUES(1,
'" .mysql_real_escape_string( $version ). "',
'" .mysql_real_escape_string( $geschlecht ). "',
" .$alter. ",
" .$fuehrerschein. "
) ON DUPLICATE KEY UPDATE
`version`='" .mysql_real_escape_string( $version ). "',
`geschlecht`='" .mysql_real_escape_string( $geschlecht ). "',
`alter`=" .$alter. ", `fuehrerschein`= " .$fuehrerschein;
MySQL docs here:
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

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.

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 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

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