When inserting a new record into a table with an auto-incrementing ID column, it is normally enough to give the ID field the value NULL or omit it from the INSERT query, as explained at How to insert new auto increment ID
INSERT INTO `database`.`table` (`id`, `user`, `result`) VALUES (NULL, 'Alice', 'green')");
or
INSERT INTO `database`.`table` (`user`, `result`) VALUES ('Alice', 'green')");
My question is - how do you do the same thing when using prepared statements. I have tried the following, using NULL:
$stmt = $db->prepare("INSERT INTO `db` (id, name, password, text) VALUES (NULL, ?, ?, ?)");
$stmt->bind_param('sss', $name, $password, $text);
$stmt->execute();
and the fowllowing, omitting the ID field:
$stmt = $db->prepare("INSERT INTO `test_db` (name, password, text) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $name, $password, $text);
$stmt->execute();
When I run this I get nothing inserted and no error message in the browser. I think it is because it is trying to insert a duplicate value for the ID field (stackoverflow.com/questions/12179770/…) - but why it should do that when this seems equivalent to the non-prepared-statement way of inserting data, and then give no message, I'm not sure.
Any ideas most welcome!
Related
I am inserting data that has VARCHAR, TIMESTAMP and DECIMAL kinds using prepare.
The data is already in the format needed by mySQL.
My problem is this. Suppose I had only 2 items to insert. I would do like this:
$stmt = $mysqli->prepare("INSERT INTO myTable (name, age) VALUES (?, ?)");
$stmt->bind_param("si", $_POST['name'], $_POST['age']);
My problem is the bind part. How do I do the bind when I have to insert 40 columns at once?
I can deal with the prepare part by doing this:
$sql = "INSERT INTO customers ($columns) VALUES ($values)";
$stmt = $mysqli->prepare($sql);
But the next line will result in a ridiculous long line, impossible to understand and very easy to go wrong.
$stmt->bind_param("ssssiidisisssiidiisssidiisidi", ....);
I don't see how I could build that in a loop for example.
How do I do that?
You can pass an array to the mysqli_stmt::bind_param() function as variable arguments with the ... syntax, introduced in PHP 5.6.
$params = ['name', 42];
$stmt = $mysqli->prepare("INSERT INTO myTable (name, age) VALUES (?, ?)");
$stmt->bind_param(str_repeat('s', count($params)), ...$params);
$stmt->execute();
You don't really need to set the data type individually for each column. You can treat them all as 's'.
I know you're asking about mysqli, but I'll just point out that this is easier with PDO:
$params = ['name', 42];
$stmt = $pdo->prepare("INSERT INTO myTable (name, age) VALUES (?, ?)");
$stmt->execute($params);
I'm inserting some values into my database.
$stmt = $conn->prepare("INSERT INTO `members` (`id`, `name`, `nickname`, `prefix`, `suffix`) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss",$row['member_id'], $row['name'], $row['nickname'], $row['prefix'], $row['suffix']);
$stmt->execute();
This does what I want: if a new user has joined this will add them to members. However, if an already existing member has changed their nickname this info doesn't get updated. I would like to 1) add new members like it currently does but also 2) update the nicknames for already existing members if there are any changes.
I tried adding the following code after the one above (first add members and then update) but it doesn't seem to work as I wanted.
$stmt = $conn->prepare("UPDATE members SET nickname = '?' WHERE id = '?'");
$stmt->bind_param("ss",$row['nickname'], $row['id']);
$stmt->execute();
You can use REPLACE INTO instead of INSERT INTO
Your prepare() would have
REPLACE INTO `members` (`id`, `name`, `nickname`, `prefix`, `suffix`) VALUES (?, ?, ?, ?, ?)
REPLACE updates the new data if the primary key value already exists.
More details here: https://dev.mysql.com/doc/refman/5.5/en/replace.html
I want insert data by GET in my sql but I can not insert data
<?php
include("config.php");
$f=$_GET["first_name"];
$l=$_GET["last_name"];
$e=$_GET["email"];
$m=$_GET["mobile"];
$b=$_GET["birthday"];
$g=$_GET["gender"];
$insert="INSERT INTO user ( `first_name`, `last_name`, `email`, `mobile`, `birthday`, `gender`)
VALUES ('$f', '$l', '$e', '$m', '$b', '$g')";
mysqli_query($insert);
?>
I try insert data by this link :
http://localhost:8888/restfull/insert.php?f=hayoo
It's been a long time since I have used mysqli the code below should most likely run though. As others have mentioned never bind unsanitized data (Even if you think you trust the data it's safe to use prepared statements still).
<?php
//Create you db connection
$conn = new mysqli('server', 'user', 'password', 'databasename');
//Create insert statement. Never concat un-sanitized data in statements
$insert="INSERT INTO user ( `first_name`, `last_name`, `email`, `mobile`, `birthday`, `gender`)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
//Values corespond to ? except the first param which represents format of expected data. "s" stands for string
$stmt->bind_param(
'ssssss',
$_GET["first_name"],
$_GET["last_name"],
$_GET["email"],
$_GET["mobile"],
$_GET["birthday"],
$_GET["gender"]
);
$stmt->execute();
Your url would look like this:
http://localhost:8888/restfull/insert.php?first_name=john&last_name=Doe&email=test#test.com&mobile=0&birthday=May&gender=male
Make sure if you are putting the url above in some type of form you correctly url encode values (I notice many of the values you are collecting will like require it slashes etc).
I have table in MySQL database called MyGuests which has 4 fields as : id (PK and Auto Increment), name,age and email. I am using following code to insert data from user input form to the database:
<?php
$sql = mysqli('localhost','user','password','database');
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
$query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (?, ?, ?, ?)");
$query->bind_param("isis",$name,$age,$email);
$query->execute();
?>
now I am confused how to insert value for id which is auto incremented field using the Prepared statement! As you can see I passed 4 parameters as (?, ?, ?, ?) for data entry and used the "isis" for bind_param(); but not sure what must put in $name,$age,$email for id?
Can you please help me to figure this out?
Thanks
Just omit the id in the query i.e.
INSERT INTO MyGuests ( name, age, email) VALUES (?, ?, ?)
It will automatically add the incremented id, hence the name :)
one more option is supplying null value to the auto-increment column:
ie.
instead of $query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (?, ?, ?, ?)"); use $query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (null, ?, ?, ?)");
I'm trying to insert data from a form into a database using PHP and Mysqli but I can't get it working! My database has 4 fields: DATE, TITLE, CONTENT, ID. The ID field is auto-increment.
I've checked the connection and that's working fine. I've also echoed the form field values and the $blogDate variable I created, they're all fine too.
Here's my prepared statement:
if ($newBlog = $mysqli->prepare('INSERT INTO Blog VALUES ($blogDate, $_POST["bTitle"], $_POST["bContent"])')) {
$newBlog->execute();
$newBlog->close();
}
It's just not inserting the values into my table.
You are generating SQL containing strings that are not quoted or escaped.
Don't insert the data directly into the SQL string, use placeholders (?) and then bind the parameters before executing.
$query = "INSERT INTO Blog VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $blogDate, $_POST["bTitle"], $_POST["bContent"]);
$stmt->execute();
Since you are aware about prepared statement:
$newBlog = $mysqli->prepare('INSERT INTO Blog (`dateCol`, `titleCol`, `contentCol`) VALUES (?, ?, ?)');
$newBlog->bind_param( 'sss', $blogDate, $_POST["bTitle"], $_POST["bContent"] );
$newBlog->execute();
$newBlog->close();
since you are using auto increment field you need to specify column name and then values
try this code
$query = "INSERT INTO Blog (colname_1,colname_2,colname_3) VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $blogDate, $_POST["bTitle"], $_POST["bContent"]);
$stmt->execute();