This question already has answers here:
How can I do 'insert if not exists' in MySQL?
(11 answers)
Closed 7 years ago.
What is the correct format for UPDATE if exists else insert in this situation - I have managed to do update and insert separately but need them together?.
What I want is that - if the date exists then it gets updated to fullday, and if it doesn't exist then a new row with the new details gets inserted.
$date = (isset($_POST['date']) ? $_POST['date'] : null);
$reservationType = (isset($_POST['reservation-type']) ? $_POST['reservation-type'] : null);
$connect = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($connect->connect_error) {
die("connection failed: ". $connect->connect_error);
}
$sql = "SELECT * FROM reservations";
$result = $connect->query($sql);
if ($result -> num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($date == $row['date_of_reservation']) {
"UPDATE reservations SET reservationType = 'FULLDAY' WHERE date_of_reservation='$date'";
}
else {
"INSERT INTO reservations (date_of_reservation, reservationType) VALUES ('$date', '$reservationType')";
}
}
}
From the manual:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
Related
This question already has answers here:
Insert into a MySQL table or update if exists
(12 answers)
Closed 6 years ago.
In my PHP script I save data to database (hash, sala).
I want to update hash if sala is exists (update hash in same row).
How to change in my script?
$sala = $_POST['sala'];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
echo "Polaczono";
}
$sql = "INSERT INTO instructions (hash, sala)
VALUES ('$newfilename', '$sala')";
if ($conn->query($sql) === TRUE) {
echo "Dane dodano prawidłowo";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
You can use INSERT ... ON DUPLICATE KEY syntax to update the value if key already exists, e.g.:
INSERT INTO instructions (hash, sala) VALUES("A", "B") ON DUPLICATE KEY UPDATE
hash = "C";
Here is the documentation.
Use this query instead:
$sql = "INSERT INTO instructions (hash, sala)
VALUES ('$newfilename', '$sala')
ON DUPLICATE KEY UPDATE hash='$newfilename'";
Also you need to create UNIQUE KEY on column sala.
And don't forget about SQL injection attack as you been told before.
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 6 years ago.
I'm a beginner with PHP and I'm stucked with a simple request that returns nothing.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM order";
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
echo "something";
}
$conn->close();
This table is not empty.
I'm clueless...
Your code looks alright.
To get errors that may have occured you can change the following:
$result = $conn->query($sql);
if(!$result) {
die($conn->error);
}
echo "Result rows: "+ $result->num_rows;
You might find an error this way.
This question already has answers here:
How can I check if a MySQL table exists with PHP?
(12 answers)
Closed 7 years ago.
I'm trying to see if a table already exists and then act accordingly. I was unable to solve my problem from viewing previous posts.I'm aware of a secondary problem where the sql throws an error but I don't know why it throws. When I replace $thisTable with the actual string, it works. But my primary problem is not being able to detect if the table exists.
$thisTable = "testX";
$thisTable = preg_replace("/[^A-Z,a-z,0-9]/", '', $thisTable);
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SHOW TABLES LIKE ".$thisTable;
//I get an SQL error here?
$stmt = $conn->prepare($sql);
$stmt->execute();
$isThere = $stmt->num_rows;
if ($isThere > 0){
echo "Already exists."
} else {
echo "Doesn't exist."
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage() . "<br/>WITH QUERY: " . $sql;
}
You need quotes around the table name in the query.
$sql = "SHOW TABLES LIKE '$thisTable'";
This question already has answers here:
How do I get the last inserted ID of a MySQL table in PHP?
(16 answers)
Closed 7 years ago.
I'm inserting a row in the following way:
require("localhost_credentials.php");
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
if($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$q_title = $fixed_title;
$q_tags = $_POST['tag_input'];
$q_mod = "n";
$q_t_create = date("m/d/Y # G:i:s");
$q_t_modified = date("m/d/Y # G:i:s");
$querystr = "INSERT INTO mytable (title, tags, moderator, time_created, time_last_modified) ";
$querystr .= "VALUES (?, ?, ?, ?, ?);";
$statement = $conn->prepare($querystr);
$statement->bind_param("sssss", $q_title, $q_tags, $q_mod, $q_t_create, $q_t_modified);
$statement->execute();
I would like to get the id of the row I just inserted without having to do a second query. I've seen a few methods to do this on SO, but every time there's a debate as to which way it should and should not be done and I'm kind of confused.
Using prepared statements, how do I get the id of a newly inserted row using only one query?
As long as you do not execute multi insert, you can use
$conn->insert_id
It is populated automatically when a statement created from that connection executes INSERT query.
you can use something like this :
$last_id = $statement->insert_id($conn);
this will return the last inserted row id .
This question already has answers here:
How to test if a MySQL query was successful in modifying database table data?
(5 answers)
Closed 1 year ago.
I'm going to insert about 500 records in a table using one query :
$sql = "INSERT IGNORE INTO `table_name` (`field1`,`field2`)
VALUES ('val1','val2') ('val3','val4') ... ";
// php_mysql_insert_function
How can I find out haw many rows are inserted in after executing query ?
The answer is affected_rows
$db = new mysqli('127.0.0.1','...','...','...');
$sql = "INSERT IGNORE INTO Test (id,test) VALUES (1,2),(1,3),(2,2),(3,4)";
$ins_test = $db->prepare($sql);
$ins_test->execute();
echo $db->affected_rows;
In this example Test has 2 columns id and test (both integer) and id is the primary key. The table is empty before this insert.
The programm echos 3.
Try this:
Procedural style of coding:
<?php
$host = '';
$user = '';
$password = '';
$database = '';
$link = mysqli_connect($host, $user, $password, $database);
if(!$link)
{
echo('Unable to connect to the database!');
}
ELSE {
$sql = "INSERT IGNORE INTO `table_name` (`field1`,`field2`) VALUES ('val1','val2'), ('val3','val4')";
$result = mysqli_query($link, $sql);
echo mysqli_affected_rows($link);
}
mysqli_close($link);
?>
mysqli_affeccted_rows counts the number of inserts. I think that #wikunia's answer will probably yield the same result. I was in the process of answering you question, before wikunia beat me to it. I place it anyway.