Inserting Multiple values into MySQL database using PHP - php

I'm wondering how to insert multiple values into a database.
Below is my idea, however nothing is being added to the database.
I return the variables above (email, serial, title) successfully. And i also connect to the database successfully.
The values just don't add to the database.
I get the values from an iOS device and send _POST them.
$email = $_POST['email'];
$serial = $_POST['serial'];
$title = $_POST['title'];
After i get the values by using the above code. I use echo to ensure they have values.
Now I try to add them to the database:
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = '$email'");
if (mysqli_num_rows($assessorEmail) == 0) {
echo " Its go time add it to the databse.";
//It is unqiue so add it to the database
mysqli_query($connection,"INSERT INTO assessorID (email_address, serial_code, title)
VALUES ('$email','$serial','$title')");
} else {
die(UnregisteredAssessor . ". Already Exists");
}
Any ideas ?

Since you're using mysqli, I'd instead do a prepared statement
if($stmt = mysqli_prepare($connection, "INSERT INTO assessorID (email_adress, serial_code, title) VALUES (?, ?, ?)"))
{
mysqli_stmt_bind_param($stmt, "sss", $email, $serial, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is of course using procedural style as you did above. This will ensure it's a safe entry you're making as well.

Related

Query executed, but data not saved into database PHP/SQL

I'm trying to execute a SQL query that saves POST data into the database. The data comes in correctly, and the arrays that are coming with the POST data are converted to strings.
When the query gets executed the message 'Succesfully saved into database' appears, however the data isn't visible in the database, so there must be a little mistake inside my code, however I can't seem to find it.
See my code below:
//database connection file
require "includes/dbh.inc.php";
foreach ($_POST as $post_var){
$obj = json_decode($post_var);
//Convert arrays to string
$userLikes = implode("|", $obj->userLikes);
$userEvents = implode("|", $obj->userEvents);
$userPosts = implode("|", $obj->userPosts);
$sql = "INSERT INTO visitor_data (id, fb_id, name, location, likes, events, posts) VALUES (NULL, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: dom.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ssssss", $obj->userId, $obj->userName, $obj->userLocation, $userLikes, $userEvents, $userPosts);
mysqli_stmt_execute($stmt);
echo '<p>Succesfully saved into database</p>';
exit();
}
}
This is how the database looks like
Thanks in advance!
You should not assume that the query ran successfully because an exception was not thrown. You need to consider what the function returns and how many rows are affected before knowing if it ran successfully or not. Update your code to this and figure out what is going on:
Also check to make sure you are not just updating the same row over and over.
//database connection file
require "includes/dbh.inc.php";
foreach ($_POST as $post_var){
$obj = json_decode($post_var);
//Convert arrays to string
$userLikes = implode("|", $obj->userLikes);
$userEvents = implode("|", $obj->userEvents);
$userPosts = implode("|", $obj->userPosts);
$sql = "INSERT INTO visitor_data (id, fb_id, name, location, likes, events, posts) VALUES (NULL, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: dom.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ssssss", $obj->userId, $obj->userName, $obj->userLocation, $userLikes, $userEvents, $userPosts);
if ( mysqli_stmt_execute($stmt) ) {
echo '<p>Succesfully saved into database</p>';
} else {
printf("Error: %s.\n", mysqli_stmt_error($stmt) );
}
}
mysqli_stmt_close($stmt);
}

Unable to insert data into MySQL database using PHP

I am unable to insert data into MySQL database. I do not know the reason since no error is triggered. I am using XAMPP on windows to run local server. Here is the code. It would be great if someone could help.
I am always getting "Values not inserted" output. I also tried printing the $query when I got exact values I entered through a form in the VALUES ('$email', ...) part of the SQL query.
<?php
$dbconnect = mysqli_connect("localhost","root","","id3626001_login_details");
if (!$dbconnect)
{
die("Connection Failed" .mysqli_connect_error());
}
if (!mysqli_select_db($dbconnect, "id3626001_login_details"))
{
echo "Could not connect to Database";
}
if (isset($_REQUEST['username']) && ($_SERVER["REQUEST_METHOD"] == "POST")){
$username = $_REQUEST['username'];
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
// Inserting values into the database through a query
$query = "INSERT INTO user_registration (ID, email, username, password) VALUES ('$email', $username', '".md5($password)."')";
if (!mysqli_query($dbconnect, $query))
{
echo "Values not inserted";
}
$result = mysqli_query($dbconnect, $query);
if($result){
echo "Registration Successful";
}
}
?>
there is a problem in your query,
1) your column counts and count of values you are passing are not the same (must be same
2) you forgot to put ' (quote befor $username')
change your query to
// Inserting values into the database through a query
$query = "INSERT INTO user_registration ( email, username, password) VALUES ('$email', '$username', '".md5($password)."')";
When you are testing you should not only print only query, you should also copy that query and run it directly into database through [(localhost/phpmyadmin)> select your databse > SQL ] and see what error are displaying there when firing a query.
UPDATE
for #Akintunde 's suggestion
for security concerns you should not be using these kind of insertion methods which is fully open to SQL injections you must follow some rule to avoid to get your script being target of sql injection
use Prepared Statements instead for database operations
Here in your query you forgot to put upper quote '-> $username',
$query = "INSERT INTO user_registration (email, username, password) VALUES ('$email', '$username', '".md5($password)."')";
Here we are not passing Id as a param so you need to make id auto increment in database for that table.
and why are to passing your query twice into mysqli_query() you can check for once like,
$result = mysqli_query($dbconnect, $query);
if ($result)
{
echo "Registration Successful";
}
else{
echo "Values not inserted";
}

php error Column count doesn't match value count at row 1? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
I have checked for similar questions regarding the error however they didn't match the issue I seem to be having.
Getting the following error when attempting to insert data into database:
Column count doesn't match value count at row 1?
Here is a screenshot of the database table:
In the HTML a form, with an action of the php file, has multiple inputs with the names: name, surname, DateOfBirth, email, password, confirm-password
PHP:
<?php
// Only process the form if $_POST isn't empty
if ( ! empty( $_POST ) ) {
// Connect to MySQL
$mysqli = new mysqli( 'localhost', 'root', '', 'pptpp' );
// Check our connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
// Insert our data
$sql = "INSERT INTO user ( Forename, Surname, DateOfBirth, Email, Password ) VALUES ( '{$mysqli->real_escape_string($_POST['name, surname, DateOfBirth, email, password '])}' )";
$insert = $mysqli->query($sql);
// Print response from MySQL
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_id}";
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
// Close our connection
$mysqli->close();
}
?>
The following part
$mysqli->real_escape_string($_POST['name, surname, DateOfBirth, email, password ']
is invalid for two reasons:
mysqli::real_escape_string() takes only 1 argument at a time, a string (unless using procedural, mysqli_real_escape_string(), then the first is the connection, then the string as the second)
The $_POST can't be accessed in that way, I highly doubt you have one field named all that. You'll have to specify the index, as $_POST['name'] etc.
The solution is to match each column with the respective escaped value from $_POST,
like $mysqli->real_escape_string($_POST['name']) for the name,
$mysqli->real_escape_string($_POST['email']) for the email and so on, an example could be assigning it to variables, and using those in the query, as shown below.
$name = $mysqli->real_escape_string($_POST['name']);
$surname = $mysqli->real_escape_string($_POST['surname']);
$dob = $mysqli->real_escape_string($_POST['DateOfBirth']);
$email = $mysqli->real_escape_string($_POST['email']);
$password = $mysqli->real_escape_string($_POST['password']);
$sql = "INSERT INTO user (Forename, Surname, DateOfBirth, Email, Password) VALUES ('$name', '$surname', '$dob', '$email', '$password')";
$insert = $mysqli->query($sql);
Then you should note that even with mysqli::real_escape_string(), it's not secure against SQL injection, and that you should use parameterized queries. An example of that is given below.
// Insert our data
$sql = "INSERT INTO user (Forename, Surname, DateOfBirth, Email, Password) VALUES (?, ?, ?, ?, ?)";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("sssss", $_POST['name'], $_POST['surname'], $_POST['DateOfBirth'], $_POST['email'], $_POST['password']);
if (!$stmt->execute())
die("Execution failed: ".$stmt->error);
echo "Success! Row ID: ".$stmt->insert_id;
$stmt->close();
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
Usage of PHP error-reporting would've likely mentioned something about undefined indexes when you use the current escape. Always (in development) let PHP give you the errors, by enabling error-reporting with error_reporting(E_ALL); ini_set("display_errors", 1); at the top of your file.
Also note that storing passwords in plain-text is a big no. You should use functions like password_hash() / password_verify() to properly and securely store your users passwords.
References
http://php.net/manual/en/mysqli.real-escape-string.php
http://php.net/manual/en/mysqli-stmt.prepare.php
How can I prevent SQL injection in PHP?

Inserting into 2 tables PHP with subquery, last insert id, and prepared statement

So, I have problem with inserting data into 2 tables directly using subquery and last insert id.
i have following codes
if (isset($_POST['recipient']))
$recipient = sanitize($_POST['recipient']);
if (isset($_POST['message']))
$message = sanitize($_POST['message']);
$sql = "INSERT INTO message (senderID, message)
VALUES (?,?)";
if ($stmt = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt, "is", $userID, $message);
mysqli_stmt_execute($stmt);
$newID = mysqli_insert_id($connection);
$sql2 = "INSERT INTO message_recipient (messageID, recipientID)
SELECT ?, userID
from user
where username = $recipient";
if ($stmt2 = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt2, "ii", $newID, $recipient);
mysqli_stmt_execute($stmt2);
mysqli_stmt_close($stmt2);
}
}
for the $stmt2 ,it works well in phpmyadmin, but without the prepared statement. The first query works well, it can add data, but can't the second. Also, i dont know why the first query will insert 2 data, with first data correct and second false.
Is the way i get last insert id wrong, or my second query is false?
Any help given really appreciated. thank you so much

Data not inserting into database to a table

I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help
You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php
Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.

Categories