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
Related
I am receiving this error and am unable to figure out why.
Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in C:\xampp\htdocs\insert.php on line 32
$SELECT = "SELECT id FROM heroes WHERE name = ? LIMIT 1";
$INSERT = "INSERT INTO heroes (id, name, title, bp, ticket, diamond) VALUES ('NULL', '$name', '$title', '$bp', '$ticket', '$diamond')";
//Prepare statement
$stmt = $connection->prepare($SELECT);
$stmt->bind_param("s", $name);
$stmt->execute();
$stmt->bind_result($name);
$stmt->store_result();
$rnum = $stmt->num_rows;
if ($rnum==0){
$stmt->close();
$stmt = $connection->prepare($INSERT);
$stmt->bind_param("sssss", $name, $title, $bp, $ticket, $diamond);
$stmt->execute();
echo "New hero inserted successfully, sir!";
} else {
echo "There is already a hero with this name, sir!";
}
$stmt->close();
$connection->close();
You don't actually have any params to bind in your insert:
$INSERT = "INSERT INTO heroes (id, name, title, bp, ticket, diamond) VALUES ('NULL', '$name', '$title', '$bp', '$ticket', '$diamond')";
Do this:
$INSERT = "INSERT INTO heroes (name, title, bp, ticket, diamond) VALUES (?, ?, ?, ?, ?)";
Then the values you bind replace the question marks.
Also note there is a very significant difference between NULL and 'NULL' -- the latter is a string. If you have an auto-incrementing ID field, just leave it out of the insert and the database will fill it in for you.
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.
Is it possible to have a "mixed" SQL Insert like the following?
I want to be able to get one value from another table (that needs a param) and then enter in 2 more params.
$sql = "INSERT INTO tblquestions (userID, questionText, questionAnswer) VALUES (
Select userID FROM tblusers WHERE userEmail = (?),?,?)";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'sss', $userEmail, $question, $answer);
$result = mysqli_stmt_execute($stmt);
if (!$result) {
throw new Exception($conn->error);
}
It is unnecessary. Just use insert . . . select:
INSERT INTO tblquestions(userID, questionText, questionAnswer)
Select userID, ?, ?
FROM tblusers
WHERE userEmail = (?);
Can some onw please explain what is wrong with this ... this worked completely fine with procedural php
function foo(){
$incomingtime = date('Y-m-d H:i:s', time());
$stmt = $db->stmt_init();
$id = "Abc123" ;
$u_id = 1;
$c_id = 1;
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('ssii', $incomingtime, $id, $u_id, $c_id);
$stmt->execute();
printf("Affected rows (UPDATE): %d\n", $db->affected_rows); // Always return 1
$stmt->close();
}
But nothing goes in the database.
Datatype in mysql db for indate is datetime
There's several issues with this code.
$stmt_4 is used before it's defined.
$u_id and $c_id are both defined then not used.
Trying to execute $stmt without supplying parameters.
$db is not defined.
$id is not defined.
If you are trying to convert working code to a function make sure that either the function gets these passed in as an argument, they are marked as global or the function creates/ retrieves them.
Check changing:
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('ssii', $incomingtime, $id, $u_id, $c_id);
$u_id = 1;
$c_id = 1;
$stmt->execute();
to:
$u_id = 1;
$c_id = 1;
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (CURRENT_TIMESTAMP, ?, ?, ?)"
$stmt = $db->prepare($query);
$stmt->execute(array($id, $u_id, $c_id));
NOTE: I deleted the parameter ssii because it's not considered in the query. It only expects 4 parameters.
I was wondering if someone could help me.
Im trying to integrate some code into my application, the code that i need to integrate is written with PDO statements and i have no idea how it goes.
I was wondering if someone could help me convert it.
The code is as follows
$sql = "insert into message2 (mid, seq, created_on_ip, created_by, body) values (?, ?, ?, ?, ?)";
$args = array($mid, $seq, '1.2.2.1', $currentUser, $body);
$stmt = $PDO->prepare($sql);
$stmt->execute($args);
if (empty($mid)) {
$mid = $PDO->lastInsertId();
}
$insertSql = "insert into message2_recips values ";
$holders = array();
$params = array();
foreach ($rows as $row) {
$holders[] = "(?, ?, ?, ?)";
$params[] = $mid;
$params[] = $seq;
$params[] = $row['uid'];
$params[] = $row['uid'] == $currentUser ? 'A' : 'N';
}
$insertSql .= implode(',', $holders);
$stmt = $PDO->prepare($insertSql);
$stmt->execute($params);
You shoudl use PDO unles for some technical reason you cant. If you dont know it, learn it. Maybe this will get you started:
/*
This the actual SQL query the "?" will be replaced with the values, and escaped accordingly
- ie. you dont need to use the equiv of mysql_real_escape_string - its going to do it
autmatically
*/
$sql = "insert into message2 (mid, seq, created_on_ip, created_by, body) values (?, ?, ?, ?, ?)";
// these are the values that will replace the ?
$args = array($mid, $seq, '1.2.2.1', $currentUser, $body);
// create a prepared statement object
$stmt = $PDO->prepare($sql);
// execute the statement with $args passed in to be used in place of the ?
// so the final query looks something like:
// insert into message2 (mid, seq, created_on_ip, created_by, body) values ($mid, $seq, 1.2.2.1, $currentUser, $body)
$stmt->execute($args);
if (empty($mid)) {
// $mid id is the value of the primary key for the last insert
$mid = $PDO->lastInsertId();
}
// create the first part of another query
$insertSql = "insert into message2_recips values ";
// an array for placeholders - ie. ? in the unprepared sql string
$holders = array();
// array for the params we will pass in as values to be substituted for the ?
$params = array();
// im not sure what the $rows are, but it looks like what we will do is loop
// over a recordset of related rows and do additional inserts based upon them
foreach ($rows as $row) {
// add a place holder string for this row
$holders[] = "(?, ?, ?, ?)";
// assign params
$params[] = $mid;
$params[] = $seq;
$params[] = $row['uid'];
$params[] = $row['uid'] == $currentUser ? 'A' : 'N';
}
// modify the query string to have additional place holders
// so if we have 3 rows the query will look like this:
// insert into message2_recips values (?, ?, ?, ?),(?, ?, ?, ?),(?, ?, ?, ?)
$insertSql .= implode(',', $holders);
// create a prepared statment
$stmt = $PDO->prepare($insertSql);
// execute the statement with the params
$stmt->execute($params);
PDO really is better. It has the same functionality as MySQLi but with a consistent interface across DB drivers (ie. as long as your SQL is compliant with a different database you can theoretically use the exact same php code with mysql, sqlite, postresql, etc.) AND much better parameter binding for prepared statements. Since you shouldnt be using the mysql extension any way, and MySQLi is more cumbersome to work with than PDO its really a no-brainer unless you specifically have to support an older version of PHP.