I'm not sure if my code is ok, it seems ok to me but when I input data, data not insert but adding at url like index.php?firstname=Kid&lastname=Max&username=OfficialKidMax.
<?php
if (isset($_POST['memadd'])) {
include('conn.php');
$thisusername = $post["username"];
$thisemail = $post["email"];
$sql = "SELECT * FROM members WHERE username = : thisusername OR `email` = : thisemail LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->execute(['thisusername' => $thisusername] OR ['thisemail' => $thisemail]);
$user = $result = $stmt->fetchAll();
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
if(empty($user)){
$query = "INSERT INTO members (`usermid`, `firstname`, `lastname`, `username`, `email`, `phone`, `usernid`, `address`, `address2`, `zipcode`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->execute(array($_POST['usermid'], $_POST['firstname'], $_POST['lastname'], $_POST['username'], $_POST['email'], $_POST['phone'], $_POST['usernid'], $_POST['address'], $_POST['address2'], $_POST['zipcode']));
}
}$_SESSION['success'] = 'Record Added';
header( 'Location: success.php' );
Update
I change my code a little bit.
Hi, thanks for your reply. I changed my code a little bit. It's work well now.
<?php
ini_set('display_errors', 1); ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if ($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['memadd']) &&
include('conn.php')) {
$sql = "SELECT * FROM `members` WHERE `usermid` =? OR `email` =?";
$stmt = $conn->prepare($sql);
$stmt->execute([$_POST['usermid'], $_POST['email']]);
$result = $stmt->fetchAll();
if ($result) { // if member exists
if ($result['email'] === [$_POST['email']]) {
array_push($errors, "User email already exists");
}
if ($result['usermid'] === [$_POST["usermid"]]) {
array_push($errors, "User ID already exists");
}
if(empty($result)){
// I run this query code at first to check if INSERT is ok and it's worked.
//But problem happen after if add.
$query = "INSERT INTO members (`usermid`, `firstname`, `lastname`, `username`, `email`, `phone`, `usernid`, `address`, `address2`, `zipcode`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->execute(array($_POST['usermid'], $_POST['firstname'], $_POST['lastname'], $_POST['username'], $_POST['email'], $_POST['phone'], $_POST['usernid'], $_POST['address'], $_POST['address2'], $_POST['zipcode']));
}
}
$_SESSION['message'] = 'Record Added';
header( 'Location: madd.php' );
I think this code is ok, or maybe not because I'm getting another problem.
if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) { ?>
<p><?php echo $error; ?></p>
<?php } ?>
</div>
<?php endif ?>
[21-Apr-2021 01:21:49 UTC] PHP Warning: count(): Parameter must be an array or an object that implements Countable in /errors.php on line 1
To save your self some grief learning php. These two links will help.
https://phptherightway.com/
Easy to read PDO tutorial.
https://phpdelusions.net/pdo
I did test this so there may still be some errors.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (isset($_POST['memadd'])) {
include('conn.php');
//
// Not sure what $post is. I assumen you ment $_POST
// Are these really needed?
// $thisusername = $post["username"];
// $thisemail = $post["email"];
// Removed the space after the :
// My optinion but if you habe to use the ` for anything. It's time to be more descriptive in your names.
//
$sql = "SELECT * FROM members WHERE username = :thisusername OR `email` = :thisemail LIMIT 1";
$stmt = $conn->prepare($sql);
//
// Not sure what the OR was doing.
//
$stmt->execute([
':thisusername' => $_POST['username'],
':thisemail' => $_POST['email']
]);
// Do you really need a second copy of the result?
$user = $result = $stmt->fetchAll();
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
if(empty($user)){
//
// I find usig the INSERT INTO table SET fld1=val1, fld2=val2, ...
// Much easyer to keep strack feilds and values.
//
$query = "INSERT INTO members (`usermid`, `firstname`, `lastname`, `username`, `email`, `phone`, `usernid`, `address`, `address2`, `zipcode`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->execute(array($_POST['usermid'], $_POST['firstname'], $_POST['lastname'], $_POST['username'], $_POST['email'], $_POST['phone'], $_POST['usernid'], $_POST['address'], $_POST['address2'], $_POST['zipcode']));
//
// You not doing any testing. How do you know it worked?
//
}
}
$_SESSION['success'] = 'Record Added';
header( 'Location: success.php' );
Related
I'm trying to use this php document to use a form to input information into a database. I keep getting the same error, Column 'custID' cannot be null. I don't know whats wrong or what to do. I might have to take the L for this assignment but it would be helpful if I could get an answer in case I run into the same problem in the future.
I already tried doing NOT NULL AUTO_INCREMENT in the mysql code. i also tried doing the same thing by using NULL for custID. Neither worked.
if(isset($_POST['submit'])){
$data_missing = array();
if(empty($_POST['custID'])){
$data_missing[] = 'Customer ID';
}else{
$custID = trim($_POST['custID']);
}
if(empty($_POST['custFirstName'])){
$data_missing[] = 'First Name';
}else{
$custFirstName = trim($_POST['custFirstName']);
}
if(empty($_POST['custLastName'])){
$data_missing[] = 'Last Name';
}else{
$custLastName = trim($_POST['custLastName']);
}
if(empty($_POST['address'])){
$data_missing[] = 'Address';
}else{
$address = trim($_POST['address']);
}
if(empty($_POST['city'])){
$data_missing[] = 'city';
}else{
$city = trim($_POST['city']);
}
if(empty($_POST['custstate'])){
$data_missing[] = 'State';
}else{
$custstate = trim($_POST['custstate']);
}
if(empty($_POST['custEmail'])){
$data_missing[] = 'Email';
}else{
$custEmail = trim($_POST['custEmail']);
}
if(empty($_POST['custPhone'])){
$data_missing[] = 'Phone';
}else{
$custPhone = trim($_POST['custPhone']);
}
if(empty($_POST['Password'])){
$data_missing[] = 'Password';
}else{
$Password = trim($_POST['Password']);
}
}
if(empty($data_missing)){
require_once '../LabYourLastProject/mysqli_connect.php';
$query = "INSERT INTO Customers (custID, custFirstName, custLastName, address, city,"
. " custstate, custEmail, custPhone, Password) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "sssssssss", $custID, $custFirstName,$custLastName, $address, $city, $custstate, $custEmail, $custPhone, $Password);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
if($affected_rows == 1){
echo 'Student Entered';
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}else{
echo 'Error Occurred <br />';
echo mysqli_error($dbc);
}
}else{
echo'You need to enter the following data<br />';
foreach($data_missing as $missing){
echo "$missing<br />";
}
}
Its supposed to insert the data passed from the form in another file into a database and show what data is missing. I just get the error.
You have to remove custID because is an AUTO_INCREMENT
$query = "INSERT INTO Customers (custFirstName, custLastName, address, city,"
. " custstate, custEmail, custPhone, Password) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
and this code
mysqli_stmt_bind_param($stmt, "sssssssss", $custFirstName,$custLastName, $address, $city, $custstate, $custEmail, $custPhone, $Password);
When inserting data to a database table the primary key which for your case is custID needs to be left out as it is not necessary here. It will be taken care by the server. Good thing you have put it to be auto_increment. You can include it in your insert code only when you have a value that is unique. But under normal circumstance leave it blank and insert other fields
$query = "INSERT INTO Customers (custFirstName, custLastName, address, city,"
. " custstate, custEmail, custPhone, Password) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
I want to save form data to database. I get a success message in the url. But the data get not saved to the database. mysqli_stmt_execute($stmt); seems to get not executed. Can anyone explain me the below code error?
if (isset($_POST['register-submit'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$type = $_POST['utype'];
$sql = "INSERT INTO `users`(`idroles`, `user_email`, `first_name`, `last_name`, `password`) VALUES((SELECT `idroles` FROM `roles` WHERE `name`= $type), ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location../View/login_register.php");
exit();
} else if (mysqli_stmt_prepare($stmt, $sql)) {
$hashpwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ssss", $firstname, $lastname, $email, $hashpwd);
mysqli_stmt_execute($stmt);
header("Location:../View/login_register.php?success");
exit();
}
}
You can check if mysqli_stmt_execute succeded by doing so:
if(mysqli_stmt_execute($stmt)) {
header("Location:../View/login_register.php?success");
exit();
} else {
echo mysqli_error($conn);
exit();
}
I am currently trying to set up a prepared statement to allow users to sign up for my web page. My POST information passes correctly to my submit page from my form, and I am able to successfully insert ?'s upon submission if I remove the prepared statement, but I get an error with this current code.
<?php
if(isset($_POST['submit'])){
$uid = 'NULL';
$fn = $_POST['fn'];
$ln = $_POST['ln'];
$u = $_POST['u'];
$p = $_POST['p'];
$dob = $_POST['dob'];
$sx = $_POST['sx'];
$pn = $_POST['pn'];
$a = $_POST['a'];
$up = $_POST['CURRENT_TIMESTAMP'];
$c = $_POST['cn'];
$s = $_POST['s'];
$z = $_POST['z'];
require_once('../mysqli_connect.php');
$query = "INSERT INTO u (userid, fn, ln, username, p, dob, sx, pn, em, a, up)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($mysqli, $query);
if($stmt){
$stmt->bind_param('isssssssssi', $uid, $fn, $ln, $u, $p, $dob, $sx, $pn, $em, $a, $up);
$stmt->execute();
$stmt->close();
}
if (mysqli_query($mysqli, $query)) {
$userid = mysqli_insert_id($mysqli);
echo "Your user ID is ". $userid;
} else {
echo "Error: " . $query . "<br>" . mysqli_error($mysqli);
}
// display error if occurs
var_dump($mysqli);
mysqli_close($mysqli);
?>
Here is the error code that I receive:
Error: INSERT INTO u (userid, fn, ln, username, p, dob, sx, pn, em, a, up) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' at line 1
I have tried changing versions of php, I am currently running 5.3, but when I switch to anything beyond I get an error for mysqli class. I have tried back ticking and quoting the ?'s but that does not seem to work either. I am hoping someone can expand upon what is already available regarding prepared statement, because I have searched high and low and have been unable to find what my problem stems from. So, I guess my question is, how do I correctly pass my variables via a prepared statement, and what syntax do I need to use near the ? placeholders?
Updated code:
if(isset($_POST['submit'])){
$uid = 'NULL';
$fn = $_POST['fn'];
$ln = $_POST['ln'];
$u = $_POST['u'];
$p = $_POST['p'];
$dob = $_POST['dob'];
$sx = $_POST['sx'];
$pn = $_POST['pn'];
$em = $_POST['em'];
$a = $_POST['a'];
$c = $_POST['cn'];
$s = $_POST['s'];
$z = $_POST['z'];
require_once('../mysqli_connect_aimU.php');
$query = "INSERT INTO u (userid, fn, ln, username, p, dob, sx, pn, em, a) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if (!$stmt = mysqli_prepare($mysqli, $query)) {
echo "Error: ".$stmt->error;
exit();
}
if(!$stmt->bind_param('isssssssss', $uid, $fn, $ln, $u, $p, $dob, $sx, $pn, $em, $a)){
echo "Error: ".$stmt->error;
}
if($stmt->execute()){
$userid = $stmt->insert_id;
echo "Your user ID is ".$userid;
} else {
echo "Error: ".$stmt->error;
}
$cityid= "SELECT id FROM c WHERE cn = '$c' LIMIT 1";
$result = mysqli_fetch_array($cityid);
if ($result != true) {
$query = "INSERT INTO c (cn) VALUES (?)";
if(!$stmt->bind_param('s', $cn)) {
echo "insert error dawg".$stmt->error;
}
if(!$stmt->execute()){
$cityid = $stmt->insert_id;
echo "Your city ID is".$cityid;
} else {
$query = "INSERT INTO ucl (cid, uid) VALUES (?, ?)";
if(!$stmt = mysqli_prepare($mysqli, $query)) {
echo "Error: ".$stmt->error;
exit();
}
if(!$stmt->bind_param('ss', $cityid, $userid)){
echo "Error: ".$stmt->error;
}
if (!$stmt->execute()){
echo "Error: ".$stmt->error;
}
}
}
You have used prepared statements so you don't then need to also use mysqli_query(). You can/should error check at each step to help identify any problems.
$query = "INSERT INTO u (userid, fn, ln, username, p, dob, sx, pn, em, a, up)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if (!$stmt = mysqli_prepare($mysqli, $query))
{
echo "Error: ".$stmt->error;
exit();
}
if (!$stmt->bind_param('isssssssssi', $uid, $fn, $ln, $u, $p, $dob, $sx, $pn, $em, $a, $up))
{
echo "Error: ".$stmt->error;
exit();
}
if ($stmt->execute()) {
$userid = $stmt->insert_id;
echo "Your user ID is ". $userid;
} else {
echo "Error: ".$stmt->error;
}
$stmt->close();
I'm doing, or trying to do, a database project for the university, but when registering a user this error appears:
Fatal error: Call to a member function bind_param() on a non-object in (...)
Initially I wrote
$insert = $db->prepare("INSERT INTO customer (name, email, phonenumber, adress, password) VALUES (?, ?, ?, ?, ?");
But then I changed to well, you can see in the code.
<?php
require 'db/connect.php';
require 'functions/security.php';
if(!empty($_POST)) {
if(isset($_POST['name'], $_POST['email'], $_POST['address'], $_POST['phone'], $_POST['password'])) {
$name = trim($_POST['name']);
$email `enter code here` = trim($_POST['email']);
$phone = trim($_POST['phone']);
$address = trim($_POST['address']);
$password = trim($_POST['password']);
if(!empty($name) && !empty($email) &&!empty($phone) && !empty($address) &&!empty($password)){
$insert = $db->prepare("INSERT INTO customer VALUES (?, ?, ?, ?, ?");
$insert->bind_param('ssiss', $name, $email, $phone, $address, $password);
//$insert->close();
if($insert->execute()){
print_r("Done");
die();
}
}
}
}
?>
Call to a member function in query's means that the query couldn't get executed because it contains an error.
In this case, you didn't closed the VALUES ().
Change $insert = $db->prepare("INSERT INTO customer VALUES (?, ?, ?, ?, ?"); to $insert = $db->prepare("INSERT INTO customer VALUES (?, ?, ?, ?, ?)");
Make sure you do check if an error could get executed.
Example of checking if an query could get executed:
$query = $this->_db->prepare("SELECTTEST name FROM user"); //.. Bad query (false)
if(!$query) //.. If the query is false.
{
trigger_error('Query couldn\'t get executed');
}
If this solved your error, I will really appreciate that you vote my answer as answer.
I have this code, but when i try to make second query to db it crashes, why? Here is part of the code, where it crashes
if ($this->doRegister === true) {
$db = DB::connect();
$stmt = $db->prepare('SELECT `user_id` FROM `users` WHERE `user_name` = ? OR `user_email` = ? LIMIT 1');
$stmt->bind_param('ss', $this->store['userData']['name'], $this->store['userData']['email']);
$stmt->execute();
$stmt->bind_result($userId);
$stmt->fetch();
if (is_numeric($userId)) {
$stmt = $db->prepare('INSERT INTO `users`(`user_name`, `user_password`, `user_email`, `user_ip`, `user_dateRegistered`, `user_type`) VALUES (?, ?, ?, ?, ?, ?)');
$hashedPassword = $this->encrytion('md5', md5($this->store['userData']['name']) . md5($this->store['userData']['password']));
$dateRegistered = time();
$type = 1;
$stmt->bind_param('ssssii', $this->store['userData']['name'], $hashedPassword, $this->store['userData']['email'], $_SERVER['REMOTE_ADDR'], $dateRegistered, $type);
$stmt->execute();
$this->registerUser();
} else {
return array('register' => 'User name or email already exists');
}
} else {
return $this->store['userDataState'];
}
Before executing/preparing the new query, you need to close it.
$stmt->close();