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.
Related
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.';
}
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 have a table with a unique column 'a'. I want to add a row to it.
If the row I want to add has a 'a' value that is already in the table, then of course, due to the uniqueness of the column, it will not be added, else, it will be added. I need to check if the new row was added, which will then tell me if the 'a' value was already in the table or not.
Whats the most efficient way to check if the new entry has been added to the table or not?
EDIT - For measure, the worst case scenario so far is a count before and a count after...
I always use ON DUPLICATE KEY UPDATE for that (but I normally want to update rows when the unique key already exits...).
In PDO you can then get a return code with something like $stmt->rowCount() that gives a 1 for a new record and a 2 for an updated record.
I meant something like this (silly example)
$conn = mysql_connect('bla bla bla');
if (!mysql_query("insert into my_table values ('b')")) {
echo mysql_errno($conn) . ': ' . mysql_error($conn) . "\n";
}
else {
echo 'ok!';
}
I am trying to implement a function that will insert a new entry in a database if a field with same name (as the one given) doesn't already exist. In particular I want to restrict duplicate usernames in a table.
The only way I could think was to run a select query and then if that doesn't return anything run the insert query. For some reason though I cant get it to work...
My db select Function
function getAllUsers($user)
{
$stmt = $this->db->stmt_init();
$stmt->prepare('SELECT username from users where username=? ');
$stmt->bind_param("s", $user);
$stmt->bind_result($username);
$stmt->execute();
$results = array();
while($stmt->fetch())
{
$results[] = array('username' => $username);
}
$stmt->close();
return $results;
}
My php code (this is in a different page)
foreach ($GLOBALS['db']->getAllUsers($_POST['username']) as $i)
{
$results = "".$i['username']."";
break;
}
if(strcmp($results, "")==0)
{
if($GLOBALS['db']->addUser($_POST['username'],$_POST['password']))
{
session_destroy();
echo "registerSucces";
}
else
{
session_destroy();
echo "registerError";
}
}
else
{
echo "userNameExists";
}
Can you see whats wrong with this???
Thanks
Mike
Still cant find how to make the above code work but just in case someone needs this: A temporary simple solution is not to compare strings at all and instead have a counter in the foreach loop and then check that upon a desired number(0 in my case)...
SQLite supports the UNIQUE constraint. Simply declare a UNIQUE index on the column and check whether an INSERT fails.
If you're using the username as the primary key in your tables, you can use the INSERT OR IGNORE command instead of checking to see if the username already exists.
If SQLite finds that an INSERT OR IGNORE command will conflict with an existing row in your table, it will simply ignore the command.
You can find out more stuff in the SQLite documentation for the INSERT command
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.