I asked that before, but couldn't figure it out.
I have this form:
<?php
if ( isset ($_REQUEST['fname']{0}, $_REQUEST['lname']{0}, $_REQUEST['mail']{0}, $_REQUEST['url']{0}) ){
$query = "INSERT INTO table1 (url, fname, lname, mail) VALUES ('".$_REQUEST[url]."', '".$_REQUEST[fname]."', '".$_REQUEST[lname]."', '".$_REQUEST[mail]."')";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
}
else{
echo "One Of The Values Not Entered Correctly. Please Press Back In Your Browser And Enter The Missing Values.";
}
?>
And I would like to know if it is possible for it to check if a url exists in the system before entering it again.
Check out MySQL INSERT ... ON DUPLICATE KEY UPDATE, which you can use if you set the URL as unique in your database.
Also, you should make sure to sanitize your inputs before inserting them: http://php.net/manual/en/function.mysql-real-escape-string.php
Replace does exactly what you need.
http://dev.mysql.com/doc/refman/5.0/en/replace.html
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted
Make sure the url column in db is PRIMARY or UNIQUE.
ALTER TABLE `table1` ADD PRIMARY KEY(`url`);
Before you can use this insert function, you must add mysql_connect(), mysql_select_db()
function insert($post = array(), $tb, $announce=true, $ignore="",$updateonduplicate=false){
foreach($post as $k => $v){
$fields[$k] = $v;
$values[] = mysql_real_escape_string($v);
}
$query = "INSERT {$ignore} INTO `{$tb}` (`".implode("`,`",array_keys($fields))."`)"." VALUES ('".implode("','",$values)."')";
if($updateonduplicate !== false){
$query .= " ON DUPLICATE KEY UPDATE ";
$countfields = 0;
foreach($fields as $field => $value){
$query .= " `".$field."`='".$value."'";
$countfields++;
if(count($fields) !== $countfields)
$query .= ",";
}
}
//mysql_connect(), mysql_select_db()
// assuming db is connected, database selected
$result = mysql_query($query)
if($announce !== true)
return;
if(!$result){
$announce = "Query Failed: " . mysql_error();
}else{
$announce = "insert_success";
}
if($updateonduplicate === true && $result === 0 && mysql_affected_rows() >=1){
$announce = "update_success";
}
return $announce;
}
$post = array();
$post['url'] = $_REQUEST[url];
$post['fname'] = $_REQUEST[fname];
$post['lname'] = $_REQUEST[lname];
$post['mail'] = $_REQUEST[mail];
insert($post,"table1",true,"",true);
If you do have a UNIQUE or PRIMARY KEY index on the url column, INSERT IGNORE will do what you want. New rows will go in and duplicates will be ignored. INSERT ... ON DUPLICATE KEY UPDATE will allow you to update if there's a duplicate, if that's what you want to do. Also, pay good attention to the SQL injection comments from the others here.
Given the description in the OP and subsequent comments (try insert, throw error if exists), I'd simply make sure the required "unique" columns had unique constraints or were part of the primary key.
Then, simply attempt the insert and catch / handle any unique constraint violation errors. This is quicker than checking for existing records.
Using PDO with the error mode set to throw exceptions means you can wrap this code nicely in a try catch block. From memory, unique constraint violations set the exception code to something you can test against.
Related
I try to write in DB table, but before I need check that the same var doesn't exist in column. But my code doesn't workd correctly for empty table. How to fix it to it start to work for empty table and later?
try
{
//$sql = "SELECT id FROM ".$table." WHERE ".$col." = :value";
$sql = "SELECT id FROM column WHERE name = :value";
$s = $pdo->prepare($sql);
$s->bindValue(':value', $value);
$relut = $s->execute();
verifyVarDump($relut, '$relut: ');
verifyVarDump($s, '$s: ');
foreach($s as $row)
{
echo ' :OK: ';
if(is_int($row['id']))
{
continue;
}
else
{
$valuesUnique[] = $value;
}
}
}
catch(PDOException $e)
{
echo 'Не удалось читать БД';
exit();
}
}
Tim's comment is what you need, but as you probably don't know what a "constraint" is, here are the steps (it's actually much simpler that what you are doing)
1) In your table definition: add either a primary key index, or a unique index. A little bit of light reading (https://dev.mysql.com/doc/refman/8.0/en/constraint-primary-key.html).
What this means is, if you try to add another entry with the same value, it will fail and throw and error. And you use this to your advantage.
2) You then add in the new row with "INSERT INTO" , and it'll fail if it the value exists in your "unique" column, or work if it doesn't. Simple. One query does it all :)
There are two other tricks you can do:
a) You can do a "REPLACE INTO" and that says "If the unique key does not exists, add in the new row; if it does exists then delete the row first and then add in my new one"
b) You can do a "INSERT INTO ..... ON DUPLICATE KEY UPDATE" and that says "If the unique key does not exists, add in the new row; if it does exists then modify the existing row with the UPDATES in the second half.
Two more single line queries that do all you need!
Good luck.
I want to make a code where if the data already exists in the database and the user insert the same input again and send to the database, the sql command will detect it and will not allow the duplicate data enter the database. Addtional information, I don`t have primary key for my table. Here is my code.
$sql="INSERT IGNORE INTO tempahan(Nama,Aktiviti,No_HP,Unit,Tempat,Tarikh_Penggunaan,Masa_Mula,Masa_Akhir,Email) VALUES('$_POST[name]','$_POST[Aktiviti]','$_POST[number]','$_POST[unit]','$_POST[tempat]','$_POST[tarikh]','$_POST[masa1]','$_POST[masa2]','$_POST[email]')";
$_POST['tempat'] = $data['Tempat'] ;
$_POST['masa1'] = $data['Masa_Mula'];
$_POST['masa2'] = $data['Masa_Akhir']; if($_POST['tempat'] != $data['Tempat'] && $_POST['masa1'] != $data['Masa_Mula'] && $_POST['masa2'] != $data['Masa_Akhir']) {
echo 'the booking was successful.';
}
else
{ echo 'the place already occupied.';}
I'm new to sql and also php. Therefore, I really need help from all of you guys. I already see the other same question. But, every solution provided I've failed.
The correct way to do this is to enforce a unique constraint on your table, across the fields that you consider to be unique. You can do that as such.
alter table tempahan
add unique (Tempat, Masa_Mula, Masa_Akhir)
Your database will then reject out of hand any attempts to insert duplicate data. No need to do a prior check before inserting.
Here is a very basic demo of what happens when you set your table up with this unique constraint, and then try and insert duplicate data. In short: it errors.
$query = $db->query( // query your table );
$array = array('name'=>$_POST['name'],
'address'=>$_POST['address']);
while ($row = mysqli_fetch_all($query)) {
$diff = in_array($array, $row);
{
if(empty($diff))
{
// insert data into table
}
else{
//data already exist
}
}
}
// first check existing recors on the database
$select = "SELECT `Tempat`, `Masa_Mula`, `Masa_Akhir`
FROM `tempahan`
WHERE `Tempat` = {$_POST['tempat']}
AND `Masa_Mula` = {$_POST['masa1']}
AND `Masa_Akhir` = {$_POST['masa2']}";
$result = mysql_query($select, $dbconnection);
// check if the have existing records
// the query fetching depends on your work
// but this is a simple way only
// but have more examples on the internet
// to make query more better and ellegant
if (mysql_num_rows($select) > 0) {
echo 'the place already occupied.';
} else {
// insert new record
$sql="INSERT IGNORE INTO tempahan(Nama,Aktiviti,No_HP,Unit,Tempat,Tarikh_Penggunaan,Masa_Mula,Masa_Akhir,Email)
VALUES(
'$_POST[name]',
'$_POST[Aktiviti]',
'$_POST[number]',
'$_POST[unit]',
'$_POST[tempat]',
'$_POST[tarikh]',
'$_POST[masa1]',
'$_POST[masa2]',
'$_POST[email]')";
echo 'the booking was successful.';
}
Here i have made a function to produce random key,
function gen_link(){
$link = '';
$s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for ($i= 0 ; $i <= 4 ; $i++)
$link = $link.$s[rand(0,63)];
return $link;
}
I dont want to repeat the key in mysql table, i have made it unique in mysql, but what i want to do is, when the key already exists i want to regenerate another random key and try to add it to table again, i tried this code below.
$con = mysqli_connect("localhost","shashi","asd123","redir");
$sql = " insert into 'links' ('link') values('$link') ";
do{
$link = gen_link();
$result = mysqli_query($con,$sql);
}while(mysqli_errno($con)==1064);
mysqli_close($con);
but it doesn't seem to work at all, it keeps looping. what can i do?
Instead of generating an actual error, use an INSERT IGNORE query like this:
$sql = "insert ignore into `links` (`link`) values ('$link')";
And check mysqli_affected_rows() to ensure something was actually inserted:
while (mysqli_affected_rows($con) == 0);
All together, that looks like this:
$con = mysqli_connect("localhost", "shashi", "asd123", "redir");
do {
$link = gen_link();
$sql = "insert ignore into `links` (`link`) values ('$link')";
$result = mysqli_query($con, $sql);
} while (mysqli_affected_rows($con) == 0);
mysqli_close($con);
Also, a couple notes about your queries:
I changed your quotes around the table and column names to backticks, which is the correct way to quote them in sql.
Because you're including the $link variable directly in the query, you need to define your query after you give the $link variable a value - so I moved that line inside the loop. This is probably the source of your original problem where you kept looping.
It's not important in this instance because you have full control of the value you're inserting (generated in gen_link()), but it's a good idea to get in the habit of properly escaping the variables you insert into a query. Alternatively, read up a bit on prepared statements, and use them instead.
Get the existing key values from the DB as array. Then search your current key with your existing keys using in_array() function. If it is true generate new key. If the condition is false , insert your new key.
http://php.net/manual/en/function.in-array.php
if(in_array($new_key,$existing))
{
//generate new key
}
else
{
//insert current key
}
I'm working with Prepared Statement an using "ON DUPLICATE KEY", to change the duplicate Value with MYSQL:
$sql = "INSERT INTO ".$this->table." ".
"(".implode(',',$fields).") VALUES
(".implode(',',$values).")
ON DUPLICATE KEY
UPDATE key_field = concat(substr(key_field,1,".($laenge_key-3)."),FORMAT(FLOOR(RAND()*999),0))
I am trying to make a database of Users. One user can have an indefinite number of phone numbers. So in the form I’ve created a js function that will give me new input fields and they put the information into a nestled array.
I am doing a double foreach loop to go through my array, and add SQL queries to it based on if the id already exists and just needs to be updated or if it's entirely new and needs to be inserted. I add these SQL queries to a variable $phoneSql . When I echo that variable, it does contain a valid SQL query which works if I try it directly in phpMyAdmin.
This is the foreach loop code:
$phoneSql = 'SELECT id FROM user WHERE id = '.$id.' INTO #id;';
foreach($_POST['phone'] as $key => $value) {
foreach($_POST['user'][$key] as $id => $number) {
if($id == 0 && !$number == ''){
$phoneSql .= 'INSERT INTO phone_number (id, user_id, number) VALUES (NULL, #id, "'.$number.'");';
} else if (!$number == '') {
$phoneSql .= 'UPDATE phone_numbers SET user_id = #id, number = "'.$number.'" WHERE id = '.$id.';';
}
}
}
I have one edit.php page with the form, which posts to update.php where I have the foreach loop from above and following code:
$db->updatePhoneNumber($phoneSql);
It also gets the $id from the user I’m editing at the moment. Then it gets sent to db.php and into this function:
public function updatePhoneNumbers($phoneSql) {
$ phoneSql = $ phoneSql;
$sth = $this->dbh->prepare($phoneSql);
$sth->execute();
if ($sth->execute()) {
return true;
} else {
return false;
}
}
But this is not working. Can I add a variable with sql queries into a function like that or do I have to do it some other way? I’m quite new to this so I’m not sure how to proceed. I’ve tried searching for a solution but haven’t found any. I’m thankful for any advice.
What you should be doing is using an INSERT ... ON DUPLICATE KEY UPDATE ... construct, saving you a lot of that logic.
e.g.
INSERT INTO phone_number (id, user_id, number) VALUES (...)
ON DUPLICATE KEY UPDATE user_id=VALUES(user_id), number=VALUES(number)
With this, no need to select, test, then insert/update. You just insert, and MySQL will transparently convert it into an update if a duplicate key error occurs.
I'm trying to add iterate through an object and add those object properties to mysql database. Using:
//This works
$sql = "CREATE TABLE $table ($ID int primary key auto_increment not null)";
mysql_query($sql);
//This works
function iterateObject($obj, $name='') {
foreach ($obj as $key=>$val) {
$myName = ($name !='') ? $name . "_" . $key : $key;
if ( is_object($val) || is_array($val) ) {
iterateObject($val, $myName);
} else {
//This works
$sql = ("ALTER TABLE home_timeline ADD COLUMN $myName VARCHAR(256);");
mysql_query($sql);
//This doesn't work
$sql2 = ("INSERT INTO home_timeline ($myName) VALUES ($val);");
mysql_query($sql2);
print "$myName - $val <br />";
}
}
}
The table is created and altered so that each iteration adds a new column to the table but when I try and add values to that column (second sql statement) everything is null and the script creates 20+ rows rather than having all the values appear on one row in the relevant column. Could someone help?
why not use functions like serialize() and unserialize() when converting objects to/from string?
second: if $val is string, then in the query put the string delimiters
"INSERT INTO home_timeline (`$myName`) VALUES ('$val');"
though inserting parameters via concatenation is a very bad practice prone to SQL injection.
If you have further problems, output the query before execution and put it here. You might be experiencing the case when you got a lot of columns which can't be nulls, and have no default values. Also output the table structure here.