Column 'custID' cannot be null - php

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 (?, ?, ?, ?, ?, ?, ?, ?)";

Related

Why PDO data adding into header instead of insert into db?

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' );

PHP mysqli prepared statement INSERT error

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();

Insert data into MySQLi via PHP - WAMP server

I have a wamp server setup. It works perfectly :)
I then entered phpMyAdmin and created a table. With an android app I have made, I would like to insert a record in my database. The android (java) code is correct, I'm 100% sure of that. When I create a record though, it doesn't work.
Since I don't know PHP very well at all I assume my mistake lies somewhere in Register.php
Here is the file:
Any insight into what my problem is would be fantastic!
Please note that I am using my correct public ip in the true file. I just entered a random one for the code below. Also, I have created a user with permissions required (in the place of username and password). The database "database" also DOES exist.
Register.php
$con = mysqli_connect("http://148.12.0.153:3306","username","password", "database");
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$phone = $_POST["phone"];
$balance = $_POST["balance"];
$NameAndSurname = $_POST["NameAndSurname"];
$DateOfBirth = $_POST["DateOfBirth"];
$SchoolName = $_POST["SchoolName"];
$Gender = $_POST["Gender"];
$Grade = $_POST["Grade"];
$Class = $_POST["Class"];
$Country = $_POST["Country"];
$Province = $_POST["Province"];
$Address = $_POST["Address"];
$City = $_POST["City"];
$PostalCode = $_POST["PostalCode"];
$statement = mysqli_prepare($con, "INSERT INTO users (username, email, password, phone, balance, NameAndSurname, DateOfBirth, SchoolName, Gender, Grade, Class, Country, Province, Address, City, PostalCode) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssssisssiisssssi", $username, $email, $password, $phone, $balance, $NameAndSurname, $DateOfBirth, $SchoolName, $Gender, $Grade, $Class, $Country, $Province, $Address, $City, $PostalCode);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
mysqli_close($con);
Ok a number of things to mention here.
First you are using the android app to launch this Register.php script on your Apache server, just like it was a web page, so this script is running on the server and not your phone or tablet. Therefore Apache and MySQL and the script are all running on the WAMPServer PC. So your connection string does not need some real ip address, it can use and should use something like localhost or 127.0.0.1
Next your database access code is assuming everything will just happen correctly and this may not be the case see above paragraph. So always check status codes and report back the status's to the calling program so it can make sensible decisions about what to do next. Its also a good idea to log errors to the PHP Error log, so when this goes live you can check logs and see if anything is going wrong without needing to run the phone app.
So try these changes :
// init the reply class
$result = new stdClass();
$result->status = 'OK';
$con = mysqli_connect("127.0.0.1","username","password", "database");
if ( ! $con ) {
$result->status = 'ERROR';
$result->error_code = mysqli_connect_errno();
$result->error_message = mysqli_connect_error();
// terminate and report to error log
error_log('Database connection failed'.mysqli_connect_error(), 0);
echo json_encode($result); // return status as json
exit;
}
// You should never use data sent from the screen without
// validating it and cleaning it up so you need some sort of
// $_POST = validate_sanity($_POST);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$phone = $_POST["phone"];
$balance = $_POST["balance"];
$NameAndSurname = $_POST["NameAndSurname"];
$DateOfBirth = $_POST["DateOfBirth"];
$SchoolName = $_POST["SchoolName"];
$Gender = $_POST["Gender"];
$Grade = $_POST["Grade"];
$Class = $_POST["Class"];
$Country = $_POST["Country"];
$Province = $_POST["Province"];
$Address = $_POST["Address"];
$City = $_POST["City"];
$PostalCode = $_POST["PostalCode"];
$sql = "INSERT INTO users
(username, email, password, phone,
balance, NameAndSurname, DateOfBirth,
SchoolName, Gender, Grade, Class,
Country, Province, Address, City,
PostalCode)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$statement = mysqli_prepare($con, $sql );
if ( ! $statement ) {
$result->status = 'ERROR';
$result->error_code = mysqli_errno();
$result->error_message = mysqli_error();
// terminate and report to error log
error_log('Database connection failed'.mysqli_error(), 0);
echo json_encode($result); // return status as json
exit;
}
$res = mysqli_stmt_bind_param($statement, "ssssisssiisssssi",
$username, $email, $password, $phone, $balance,
$NameAndSurname, $DateOfBirth, $SchoolName, $Gender,
$Grade, $Class, $Country, $Province, $Address, $City,
$PostalCode);
if ( ! $res ) {
$result->status = 'ERROR';
$result->error_code = mysqli_errno();
$result->error_message = mysqli_error();
// terminate and report to error log
error_log('Database connection failed'.mysqli_error(), 0);
echo json_encode($result); // return status as json
exit;
}
if ( mysqli_stmt_execute($statement) ) {
$result->status = 'OK';
$result->message = 'Row deleted';
echo json_encode($result); // return status as json
exit;
} else {
$result->status = 'ERROR';
$result->error_code = mysqli_errno();
$result->error_message = mysqli_error();
// terminate and report to error log
error_log('Database DELETE failed'.mysqli_error(), 0);
echo json_encode($result); // return status as json
exit;
}
//mysqli_close($con);
//PHP will do all the connection and statment closing automatically
// So you dont actually need to do any of this unless you are running
// a script the will consume large numbers of statement and you may
// feel it necessary to close them out to kepp the memory footprint smaller
Change the mysqli_stmt_close to
mysqli_stmt_close($statement) or die(mysqli_error());
This will give you a more precise error as to why this is failing.

Function prepare query

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.

error when try to send second query to mysql in my class

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();

Categories