Related
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' );
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 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 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.
// Insert the new user into the database
// This WORKS, and was copied from an example
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: MEMBER. Please contact the developer.');
}
$insert_stmt->close();
// If user inserted, add place with user as owner
// This DOESN'T work, and was added by me
//$ownerid = $mysqli->lastInsertId();
$placename = $_POST['placename'];
$placename = mysqli_real_escape_string($mysqli, $placename);
$location = $_POST['autocomplete'];
$location = mysqli_real_escape_string($mysqli, $location);
if ($place_stmt = $mysqli->prepare("INSERT INTO places (member_owner, location, name) VALUES (?, ?, ?)")) {
$place_stmt->bind_param('iss', 1, $location, $placename);
if (! $place_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: PLACE. Please contact the developer.');
}
}
$place_stmt->close();
}
header('Location: ./register_success.php');
I can confirm that the 2 variables $location and $placename are successfully retrieved. The result I get from running this code is that the members table is successfully updated, but the places table is not and the script dumps me into a blank HTML.
I figured out that bind_param doesn't like to accept hard-coded values. I was trying to "test" my code by inserting a value of 1 into a column before I messed around with trying to get the last inserted ID. The error reporting suggested by Fred really helped (as did other suggestions, as you can see I've implemented).
The altered code:
// Insert the new user into the database
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ./error.php?err=Registration failure: MEMBER. Please contact the developer.');
exit;
}
$insert_stmt->close();
// If user inserted, add place with user as owner
$ownerid = $mysqli->insert_id;
if ($place_stmt = $mysqli->prepare("INSERT INTO places (member_owner, location, name) VALUES (?, ?, ?)")) {
$place_stmt->bind_param('iss', $ownerid, $location, $placename);
if (! $place_stmt->execute()) {
header('Location: ./error.php?err=Registration failure: PLACE. Please contact the developer.');
exit;
}
}
$place_stmt->close();
header('Location: ./register_success.php');
}
Thanks for all the help!