insert array from input to MySQL PDO - php

I tried to insert multiple rows to PDO MySQL but it's didn't work
my code is below
<input type="text" name="firstname[]"> <input type="text" name="lastname[]">
function input_checker($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$firstname = input_checker($_POST["firstname"]);
$lastname = input_checker($_POST["lastname"]);
$rows = array($firstname, $lastname);
$stmt = $conn->prepare("INSERT INTO memo(ID, firstname, lastname)
VALUES (NULL, :firstname, :lastname)");
foreach($rows as $key => $value){
$stmt->bindParam($key, $value);
}
$stmt -> execute();

$rows is not an associative array, so there's no :firstname and :lastname keys in it. Also, bindParam() binds to references, so using the same $value variable each time through the loop will bind both parameters to the last value from the loop.
You don't need the array in the first place. Just bind each parameter separately.
But $_POST['firstname'] and $_POST['lastname'] are arrays, so you need to loop through them.
$firstname = $lastname = null;
$stmt = $conn->prepare("INSERT INTO memo(ID, firstname, lastname)
VALUES (NULL, :firstname, :lastname)");
$stmt->bindParam(":firstname", $firstname);
$stmt->bindParam(":lastname", $lastname);
foreach ($_POST['firstname'] as $i => $firstname) {
$lastname = $_POST['lastname'][$i];
$stmt->execute();
}

You are binding with the array index as the key (which are numeric in the version you are using), but you are using names for the parameters.
There is no need to use an array anyway as it is shorter to bind each parameter at a time...
$stmt = $conn->prepare("INSERT INTO memo(ID, firstname, lastname)
VALUES (NULL, :firstname, :lastname)");
$stmt->bindParam(":firstname", $firstname);
$stmt->bindParam(":lastname", $lastname);
$stmt -> execute();

Related

Number of variables doesn't match number of parameters in prepared statement in

I'm writing PHP code to send user input to the database. And http://fwtest.ga/register.php is my URL. every time I click the URL or check the JSON data in JSONLint website I get "mysqli_stmt_bind_param(): "Number of variables doesn't match a number of parameters in prepared statement" here is Mycode
<?php
$con = mysqli_connect("hostname", "username", "password", "dbname");
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$email = $_POST["email"];
$password = $_POST["password"];
$user_id = $_POST["user_id"];
$statement = mysqli_prepare($con, "INSERT INTO `user` (first_name, last_name, email, password) VALUES
('$first_name', '$last_name', '$email', '$password')");
mysqli_stmt_bind_param($statement, 'ssss', $first_name, $last_name, $email, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
You are injecting the params and you are preparing the query at the same time, use ? to tell mysql where to place the data,remove the variables from the sql string
$statement = mysqli_prepare($con, "INSERT INTO `user` (first_name, last_name, email, password) VALUES
(?, ?, ?, ?)");
I declared the five variables after a $con, and use only four of them mysqli_prepare function. Now it's working.

(PHP) What's my mistake here?

The data on the form failed to saved on the database. I cannot find what's wrong here. I already checked the name of the input forms an it is all correct. I'm using PDO
if ($_POST) {
$accountuname = ($_POST['accountuname']);
$accountpassword = ($_POST['accountpassword']);
$accounttype = ($_POST['accounttype']);
$companyname = ($_POST['companyname']);
$companyproduct = ($_POST['companyproduct']);
$companyaddress = ($_POST['companyaddress']);
$companycontactnum = ($_POST['companycontactnum']);
$query = "INSERT INTO user_accounts SET USER_NAME=?, USER_PASS=?, USER_ACC_TYPE=?, COMPANY_NAME=?, COMPANY_PRODUCT=?, COMPANY_ADDRESS=?, COMPANY_CONTACTNUM=?";
$stmt = $conn->prepare($query);
$stmt -> bindParam(1,$accountuname);
$stmt -> bindParam(2,$accountpassword);
$stmt -> bindParam(3,$accounttype);
$stmt -> bindParam(4,$companyname);
$stmt -> bindParam(5,$companyproduct);
$stmt -> bindParam(6,$companyaddress);
$stmt -> bindParam(7,$companycontactnum);
$stmt -> execute();
}else{
header("location:index.php");
}
Change the SQL query from:
INSERT INTO user_accounts SET USER_NAME=?, USER_PASS=?, USER_ACC_TYPE=?, COMPANY_NAME=?, COMPANY_PRODUCT=?, COMPANY_ADDRESS=?, COMPANY_CONTACTNUM=?
To:
INSERT INTO user_accounts (USER_NAME, USER_PASS, USER_ACC_TYPE, COMPANY_NAME, COMPANY_PRODUCT, COMPANY_ADDRESS, COMPANY_CONTACTNUM) VALUES (?, ?, ?, ?, ?, ?, ?)
INSERT INTO syntax.
If you are using mysqli, acording to the documentation, the bind_param (instead of bindParam... maybe you are using a framework?) function expects the first parameter to be a string, instead of an int:
bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
types
A string that contains one or more characters which specify the types
for the corresponding bind variables:
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
You should change the 1,2,3,4... to 'd,s,b' (the variable type), and it should work.
Hope it helps!
You have to specify the binded parameter type, and also your query was incorrect.
Here is the correct version in MySQLi:
$query = "INSERT INTO user_accounts (USER_NAME, USER_PASS, USER_ACC_TYPE, COMPANY_NAME, COMPANY_PRODUCT, COMPANY_ADDRESS, COMPANY_CONTACTNUM) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->bindParam("sssssss", $accountuname, $accountpassword, $accounttype, $companyname, $companyproduct, $companyaddress, $companycontactnum);
// Set parameters and execute
$accountuname = $_POST['accountuname'];
$accountpassword = $_POST['accountpassword'];
$accounttype = $_POST['accounttype'];
$companyname = $_POST['companyname'];
$companyproduct = $_POST['companyproduct'];
$companyaddress = $_POST['companyaddress'];
$companycontactnum = $_POST['companycontactnum'];
$stmt->execute();
Here is the correct version in PDO:
$query = "INSERT INTO user_accounts (USER_NAME, USER_PASS, USER_ACC_TYPE, COMPANY_NAME, COMPANY_PRODUCT, COMPANY_ADDRESS, COMPANY_CONTACTNUM) VALUES (:uname, :upass, :utype, :cname, :cproduct, :caddress, :ccontactnum)";
$stmt = $conn->prepare($query);
$stmt->bindParam(':uname', $accountuname);
$stmt->bindParam(':upass', $accountpassword);
$stmt->bindParam(':utype', $accounttype);
$stmt->bindParam(':cname', $companyname);
$stmt->bindParam(':cproduct', $companyproduct);
$stmt->bindParam(':caddress', $companyaddress);
$stmt->bindParam(':ccontactnum', $companycontactnum);
// Set parameters and execute
$accountuname = $_POST['accountuname'];
$accountpassword = $_POST['accountpassword'];
$accounttype = $_POST['accounttype'];
$companyname = $_POST['companyname'];
$companyproduct = $_POST['companyproduct'];
$companyaddress = $_POST['companyaddress'];
$companycontactnum = $_POST['companycontactnum'];
$stmt->execute();
For MYSQLi: In this example I assumed all the posted data are string, otherwise you would have to change the 'sssssss' in the bindParam function.
Read more about prepared statements here
Read more about MySQLi INSERT syntax here

Prepared statement PDO does nothing

I am trying to figure out how prepared statements work in PDO. I have the following file:
<?php
$user = "root";
$pass = "<removed for this post>";
$db = new PDO("mysql:host=localhost;dbname=pdo-demo", $user, $pass);
$stmt = $db->prepare("INSERT INTO pdo-demo (firstname, lastname, email) value (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
$firstname = "John";
$lastname = "Doe";
$email = "johndoe#nowhere123.com";
$stmt->execute();
$db = null;?>
When I enter the page nothing happens, what am I missing? Shouldn't it insert the data?
pdo-demo that translates to pdo minus demo And your using that name for database AND table.
Turns out I needed backticks (`) for the variable names like so:
$stmt = $db->prepare("INSERT INTO `pdo-demo` (`firstname`, `lastname`, `email`) value (:firstname, :lastname, :email)");
Now it worked

foreach in PDO prepared statement

I would like to have a bit of clarification about prepared statements, and how they behave when assembled in other ways.
The sample code below is from Straight out this W3 entry. My problem is that, having many more values than the four provided in this example, I'd love to store them in an array and then run a foreach to prepare each string.
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
// insert another row
$firstname = "Mary";
etc
Would the edit below be safe for application, or does it crack the whole point of prepared statements?
$stuff = array("firstname", "lastname", "email");
foreach ($stuff as $singlestuff) {
$singlestuff1 = ':'.$singlestuff;
$singlestuff2 = '$'.$singlestuff;
$stmt = $conn->prepare("INSERT INTO MyGuests ($singlestuff1) ) VALUES ($singlestuff2)");
$stmt->bindParam($singlestuff1, $singlestuff2);
}
Sorry for any macroscopic mistake, the code is just an illustration of the concept.
Thanks in advance!
Bind within the foreach loop, assumed the variables exist:
foreach ($stuff as $singlestuff) {
$stmt->bindParam(':' . $singlestuff, $$singlestuff);
}

mysqli prepared statement woes

I'm trying to implement my first prepared statement using mysqli.
At the moment I have this:
<?php
$con = new mysqli('example.com', 'user', 'password', 'database');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();}
$first = $_GET['firstname'];
$last = $_GET['surname'];
$dob = $_GET['dob'];
$address = $_GET['homeaddress'];
$college = $_GET['college'];
$emergname = $_GET['emergencyname'];
$emergnumber = $_GET['emergencynumber'];
$condition = $_GET['condition'];
$conditiondetails = $_GET['conditiondetails'];
$medication = $_GET['medication'];
$medicationdetails = $_GET['medicationdetails'];
if($stmt = $con->prepare("INSERT INTO medical ('forename', 'surname', 'dob', 'address', 'college', 'emergency_name', 'emergency_number', 'condition', 'condition_details', 'medication', 'medication_details') VALUES (:forename, :surname, :dob, :address, :college, :emergencyname, :emergencynumber, :condition, :conditiondetails, :medication, :medicationdetails)")){
$stmt->bind_param(':forename', $first);
$stmt->bind_param(':surname', $last);
$stmt->bind_param(':dob', $dob);
$stmt->bind_param(':address', $address);
$stmt->bind_param(':college', $college);
$stmt->bind_param(':emergencyname', $emergname);
$stmt->bind_param(':emergencynumber', $emergnumber);
$stmt->bind_param(':condition', $condition);
$stmt->bind_param(':conditiondetails', $conditiondetails);
$stmt->bind_param(':medication', $medication);
$stmt->bind_param(':medicationdetails', $medicationdetails);
$stmt->execute();
$stmt->close();} ?>
I have previously tried a variance using:
<?php
$stmt = $con->prepare("INSERT INTO medical ('forename', 'surname', 'dob', 'address', 'college', 'emergency_name', 'emergency_number', 'condition', 'condition_details', 'medication', 'medication_details') VALUES (?,?,?,?,?,?,?,?,?,?,?)")
$stmt->bind_param('sssssssssss', $first...);
?>
In both instances I get an error message that the $stmt variable doesn't exist.
Any suggestions as to where I'm going wrong?
Column names should be escaped with backticks, not single-quotes. Also, you can't use named parameter bindings.
Try
$stmt = $con->prepare("INSERT INTO medical (`forename`, `surname`, `dob`, `address`, `college`, `emergency_name`, `emergency_number`, `condition`, `condition_details`, `medication`, `medication_details`) VALUES (?,?,?,?,?,?,?,?,?,?,?)")
if (!$stmt)
{
echo $con->error;
}
Maybe you should try using this SQL syntax instead:
$stmt = $con->prepare("INSERT INTO medical VALUES (:forename, :surname, :dob, :address, :college, :emergencyname, :emergencynumber, :condition, :conditiondetails, :medication, :medicationdetails)");
$stmt->bind_param(':forename', $first);
$stmt->bind_param(':surname', $last);
$stmt->bind_param(':dob', $dob);
$stmt->bind_param(':address', $address);
$stmt->bind_param(':college', $college);
$stmt->bind_param(':emergencyname', $emergname);
$stmt->bind_param(':emergencynumber', $emergnumber);
$stmt->bind_param(':condition', $condition);
$stmt->bind_param(':conditiondetails', $conditiondetails);
$stmt->bind_param(':medication', $medication);
$stmt->bind_param(':medicationdetails', $medicationdetails);
$stmt->execute();
Or try:
$stmt = $con->prepare("INSERT INTO medical VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('sssssssssss', $first, $second, $third, $fourth, $fifth, $sixth, $seventh, $eighth, $ninth, $tenth, $eleventh);
Meaning, without no Use-Fields declaration in your INSERT statement.

Categories