Insert data into database if value doesn't exists in specific column - php

I've tried to follow several answers on this question but can't seem to get it to work for my specific problem.
I want to insert data but only if the flight_number doesn't exists already. How can I do that?
$sql = mysqli_query($con,
"INSERT INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`)
VALUES ('".$flight_number."', '".$mission_name."', '".$core_serial."', '".$payload_id."')"
);

Rob since you saying flight_number is a unique then you can use INSERT IGNORE
<?php
$sql = "INSERT IGNORE INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`) VALUES (?,?,?,?)";
$stmt = $con->prepare($sql);
$stmt->bind_param('isss',$flight_number,$mission_name,$core_serial,$payload_id);
if($stmt->execute()){
echo 'data inserted';
// INSERT YOUR DATA
}else{
echo $con->error;
}
?>
OR you could select any row from your database that equal to the provided flight number then if u getting results don't insert.
$sql = "SELECT mission_name WHERE flight_number = ? ";
$stmt = $con->prepare($sql);
$stmt->bind_param('i',$flight_number);
if(mysqli_num_rows($stmt) === 0){
// INSERT YOUR DATA
}

A unique index on flight number should do the trick.
CREATE UNIQUE INDEX flight_number_index
ON space (flight_number);
If you want to replace the existing row with the new one use the following:
$sql = mysqli_query($con,
"REPLACE INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`)
VALUES ('".$flight_number."', '".$mission_name."', '".$core_serial."', '".$payload_id."')"
);
Make note that I just copied your code and changed INSERT to REPLACE to make it easy to understand. PLEASE PLEASE PLEASE do not use this code in production because it is vulnerable to injection.
If you don't want to replace the existing row, run an insert and check for errors. If there is an error related to the index, the row already exists.
Disclaimer: I haven't tested any of this code, so there may be typos.

Related

How to compare input from a user php post to a MySQL

I am teaching myself php and MySQL, and right now I have a problem with MySQL.
I want to compare the phone number that the user put in with the phone number in MYSQL, and if it is in MYSQL to not register it again.
My code:
<?php
require_once 'connection/connection.php';
// Variables from HTML to php
$worker_Name = $_POST['workerNameFromHtml']; // worker Name
$worker_City = $_POST['workerCityFromHtml']; // workerCity
$worker_career = $_POST['workerCareerFromHtml']; // worker career
$worker_PhoneNumber = $_POST['workerPhonNumberFromHtml']; // worker Phone Number
$worker_SecondPhoneNumber = $_POST['workerSecondPhoneNumberFromHtml']; // worker Second Phone Number
$submt=$_POST['submitFromHtml'];
if($submt){
$qry = ( "SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'") or die(mysql_error());
$result = $connect->query($qry);
$num = $result->num_rows;
if ($num == 1) {
$here = "INSERT INTO workersTable VALUES('','$worker_Name','$worker_City','$worker_career','$worker_PhoneNumber','$worker_SecondPhoneNumber')";
$query = $connect->query($here);
print "Successfully added!";
}
else {print "This number has already been entered Thank you for your cooperation!";}}
$connect->close();
So far I have not found a solution to this problem.
your biggest problem here is that you are trying to include variables inside of a string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'"
If you want to do it this way, you need to concatenate your variables with your string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '".$worker_PhoneNumber."'"
Keep in mind if you do this you will want to sanitize your variables first to prevent SQL injections. Also, when you INSERT variables, you will actually want to use a prepared statement like this:
"INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)"
where the 1st set of values are the names of your columns in the database and the second set are your PHP variables you are putting into it.

When i inserting data into mysql it insert two datas, and i dont know why

When i inserting using this code it insert two datas and i downt know how to fix it
$sql = "SELECT Version_id FROM versions ORDER BY Version_id DESC LIMIT 1;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$lastVersion =$row["Version_id"];
}
}
echo($lastVersion);
$lastVersion++;
$sql = "INSERT INTO versions (version)
VALUES ('v$lastVersion')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
While I don't exactly understand what you mean with "two datas", I do see multiple issues with your code.
First of all it is horribly inefficient and prone to race conditions. It's also quite wrong, in that it doesn't do what you want it. Not to mention should be replaced with native database functionality.
Most of these can be fixed by simply changing the version_id field to a AUTO_INCREMENT. This will automatically give the new record the next available ID in the set, exactly as what you're trying to do. Then you can retrieve this ID by using "lastInsertId()"
That'll make all of the code in your post superflous, and only require you do do something like this when actually inserting data:
$sql = "INSERT INTO `version`(`setting`, `date`) VALUES (:setting, :date)";
$stmt = $db->prepare ($sql);
$res = $stmt->execute ($data);
$newID = $db->lastInsertId ();
After this the new version ID is stored in the $newID variable.
Of course, if you want to UPDATE the version ID for some reason, then INSERT is the wrong command to use. Also, why use an entire table for what's basically a simple version number? In short, your whole table doesn't make a whole lot of sense for me.
I recommend explaining the rationale behind it, so that we can possibly come up with some better solutions you can use.

Inserting a variable with a comma in it to SQL database?

I've been trying to insert a variable that has a comma in it to a SQL database for 30 minutes or so. I've echoed the variable, and the comma is there, but when it inserts, there's no comma!
Example (some code like mine):
$variable1 = "test";
$variable2 = "$variable1,";
$sql1 = "INSERT INTO table (`column`) VALUES ('$variable2')";
$query1 = mysqli_query($con,$sql1); //I dont think I need to put a con variable up there for an example code
And when I do:
echo $variable2;
The result is test, with the comma, but the data in the column is just test WITH NO COMMA.
Help please.
Thanks.
Edit:
Your Common Sense fixed it, apparently I needed brackets around '$variable2' so it's like:
$sql1 = "INSERT INTO table (`column`) VALUES (('$variable2'))";
Thanks Your Common Sense and everyone else who tried!
Well, the answer is simple.
It's your own code does remove this comma, either before insert or after fetch.
If you care to write a reproduceable test case, you will see that noone is taking your comma.
Test case means code that involves the behavior in question and nothing else. Not a single line of code beside insert and fetch:
$variable1 = "test";
$variable2 = "$variable1,";
$sql1 = "INSERT INTO users (username) VALUES ('$variable2')";
mysqli_query($db,$sql1);
$sql2 = "SELECT username FROM users WHERE username ='$variable2'";
$res = mysqli_query($db,$sql2);
$row = mysqli_fetch_row($res);
var_dump($variable1, $variable2, $sql1, $sql2, $row[0]);
run it, see it all with comma in place, and then search your own code for the comma trimming code
or may be you have just test without comma in your table, ans select this one all the time, instead of one with comma.
or whatever silly error of the like
Try it like this:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("INSERT INTO table ('column') VALUES (?)");
$stmt->bind_param($variable2);
/* execute prepared statement */
$stmt->execute();
This is more safe and will not trigger such strangeties. (Is that a word?)
What happens here is, that the query is send to the sql database and this returns a statement. The statement has some holes, these are the ?, in it.
When using bind_param you fill the holes and then you can execute.
This has a couple of advantages:
It is safe
You can reuse your statement
It is easier than string interpolation stuff
Try "INSERT INTO table ('column') VALUES ('" . $variable2 . "');"

Insert result into multiple tables

EDIT:
Im trying to submit a form with a title and body but i want the title to go to one table and body to go to another table, this in itself i can do but i need the ID generated from the title being inserted into its table to then be inserted into a field in the table the body is inserted so as to keep them linked.
What i have so far: I know its not pretty and its not safe, i will be reworking them once i learn how to do it properly.
if (#$_POST['post'])
{
$body = #$_POST['body'];
$title = #$_POST['title'];
$BoardID = #$_POST['BoardID'];
$MemberID = #$_POST['MemberID'];
$date = date("Y-m-d H:i:s");
include ('connect.php');
$insert = mysql_query("INSERT INTO threads VALUES ('','$BoardID','$title','$date','$MemberID','','')");
if($insert) {
header("location: ?p=posts&thread=$Thread_ID");
exit();
}
}
I need to somehow get $Thread_ID which has been generated in the insert and add that to a second insert for adding body to the post table, if that makes sense.
I tried getting the latest $Thread_ID and adding +1 but if multiple threads are posted at once they might get crossed over.
How would i go about fixing this?
The PHP manual tell us:
This extension Mysql is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used.
(see ref.)
You must use mysqli or PDO, to make a connection between PHP and a MySQL database.
mysqli
If you want the id of the inserted row, you can use $mysqli->insert_id (ref)
Example:
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
PDO
If you want the id of the inserted row, you can use $dbh->lastInsertId(); (ref)
And don't forget to sanatize all your inputs.
You need to execute both insert queries separately.
$insert = "INSERT INTO threads VALUES ('','$BoardID','$title','$date','$MemberID','','')";
$result = #mysql_query($insert);
$Thread_ID=#mysql_insert_id();
$insert = "INSERT INTO posts VALUES ('','$BoardID',$Thread_ID','$body','$date','$MemberID')";
$result = #mysql_query($insert);
Thanks,

Adding duplicate row when insert else update

I was using the code below, when user_id wasnt set as unique and it entered the same data twice with the same user_id. So I have set it to unique and now just get Error, query failed.
All help is greatly appreciated :(
if (empty($err)) {
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
// insert into the database
$the_query ="SELECT * FROM thesis WHERE user_id='$_SESSION[user_id]'";
$testResult = mysql_query($the_query) or die('Error, query failed');
if(mysql_fetch_array($testResult) == NULL){
//insert...
$the_query ="INSERT INTO thesis (`user_id`,`thesis_Name`,`abstract`)
VALUES ($user_id, $thesis_Name, $abstract)";
$result = mysql_query($the_query) or die('Error, query failed') ;
}
else{
//update...
$the_query = "UPDATE thesis
SET thesis_Name='$thesis_Name', abstract='$abstract'
WHERE user_id='$_SESSION[user_id]'";
$result = mysql_query($the_query)or die('Error, query failed');
}
// query is ok?
if (mysql_query($the_query, $link) ){
// redirect to user profile
header('Location: myaccount.php?id=' . $user_id);
}
I have also tried
$the_query = "INSERT INTO thesis (`user_id`,`thesis_Name`,`abstract`)
VALUES ($user_id, $thesis_Name, $abstract)
ON DUPLICATE KEY UPDATE thesis_Name=VALUES(thesis_Name), abstract=VALUES(abstract)";
Use ON DUPLICATE KEY UPDATE.
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Example:
INSERT INTO thesis (`user_id`,`thesis_Name`,`abstract`)
VALUES ($user_id, $thesis_Name, $abstract)
ON DUPLICATE KEY UPDATE thesis_Name=VALUES(thesis_Name), abstract=VALUES(abstract)
This basically handles the duplicate checking and choosing between INSERT and UPDATE all on the MySQL side, which is much faster (by about a factor of 2). As a bonus, the VALUES() function allows you to retrieve values from the row being inserted, so that you don't have to provide the values twice and multi-row inserts work properly.
In response to an edit to the OP:
You have to specify the individual columns to change in the UPDATE clause. If you want to update thesis_Name and abstract, then you have to specify those. If you specify only the unique key that caused the update in the first place, then it will update only that, which will most likely do nothing!
What I think you are looking for is: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html which will update the row if the insert query encounters a duplicate key.

Categories