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.
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've created a php script for my registration page to insert new registration details into a MySQL Workbench database, however when I attempt to execute this script by using a submit button on the registration jsp page, the whole php code appears so evidently it has not been executed.
I am using the IntelliJ Ultimate edition which has the PHP plugin. This is a webapp which I deploy using tomcat
I also attempted to put and tags before and after the PHP code to see if it was just an error in terms of displaying output but this didn't solve the issue.
These are the relevant parts of the registration jsp page which collect user input and then post them :
<form action="registered.php" method="POST">
.............
<input type="submit" value="Submit"/>
</form>
Here is the php script which I am trying to execute:
<?php
$host_name = $_POST[host_name];
$host_password = $_POST[host_password];
$f_name = $_POST[f_name];
$s_name = $_POST[s_name];
$gender = $_POST[gender];
$house_num = $_POST[house_num];
$road = $_POST[road];
$city = $_POST[city];
$postcode = $_POST[postcode];
$country = $_POST[country];
$mobile = $_POST[mobile];
$dob = $_POST[dob];
if (!empty($host_name) || !empty($host_password) ||!empty($f_name) ||!empty($s_name) || !empty($gender) || !empty($house_num) || !empty($road) || !empty($city) || !empty($postcode) || !empty($country) || !empty($mobile) || !empty($dob)) {
$host = "jdbc:mysql://localhost/project";
$username = "projectuser";
$password = "test123";
$conn = new mysqli($host, $username, $password);
if (mysqli_connect_error()) {
die('Connect Error(' . mysqli_connect_errno() . ')' . mysqli_connect_error());
} else {
$SELECT = "SELECT host_name FROM hosts WHERE host_name = ? Limit 1";
$INSERT = "INSERT INTO hosts (host_name, host_password, f_name, s_name, gender, house_num, road, city, postcode, country, mobile, dob) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($SELECT);
$stmt->bind_param("s", $host_name);
$stmt->execute();
$stmt->bind_result($host_name);
$stmt->store_result();
$rnum = $stmt->num_rows;
if ($rnum == 0) {
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("sssssissssss", $host_namename, $host_password, $f_name, $s_name, $gender, $house_num, $road, $city, $postcode, $country, $mobile, $dob);
$stmt->execute();
echo "You have registered successfully";
} else {
echo "Someone already registered with this username";
}
$stmt->close();
$conn->close();
}
}else{
echo "All field are required";
die();
}
?>
This is the result:
Your issue here is that Apache Tomcat is a Java Application container, and does not execute PHP code.
Is running this script through PHP and not inserting the data via JSP or a servlet not an option?
If you must run PHP for some reason, maybe This Question will help you out
Good morning, I've created a page where users can send information using a form. It works perfectly fine when I use WAMP Server then I started uploading it to the hosting and now I get an error everytime I click submit.
Here's the error:
Here's the insert-message.php:
<?php
require_once ('database.php');
if (isset($_POST['send'])) {
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$empname = $_POST['empname'];
$position = ($_POST['position']);
$account = $_POST['account'];
$platform = $_POST['platform'];
$processor = $_POST['processor'];
$ram = $_POST['ram'];
$monitor = $_POST['monitor'];
$phone = $_POST['phone'];
$headset = $_POST['headset'];
{
$database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insert_query = "INSERT INTO tbl_pcrequest (day, month, year, empname, position, account, platform, processor, ram, monitor, phone, headset)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$insert = $database->prepare($insert_query);
$insert->execute(array($day, $month, $year, $empname, $position, $account, $platform, $processor, $ram, $monitor, $phone, $headset));
echo "<script>alert('Successfully sent!'); window.location='index.php'</script>";
}
}
?>
Database Schema:
PS: I've already changed all database connection credentials to my hosting credentials, don't worry.
Please let me know if you need something.
The database name you specify in database.php is teamspan_pcrequest. You should change it to only pcrequest based on the screenshot you sent from PhpMyAdmin.
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.
am getting the following error from my code:
Binding parameters failed: (1064) 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 '? (Name, Address, Location, Phone, Email, Time, Website, Photo1, Rating, Date_Pu' at line 1
Can anyone help me out please? Here is my code:
include("mysqli.php");
$search_tbl = mysql_query("SELECT * from listing_title where listing_title_ID = '$main_id'");
$tbl_name = $search_tbl['tbl_name'];
$stmt = $db->stmt_init();
global $tbl_name;
if($stmt->prepare("INSERT INTO ? (Name, Address, Location, Phone, Email, Time, Website, Photo1, Rating, Date_Published, categories_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"))
{
$stmt->bind_param('sssssssssisi',$tbl_name,$title,$address,$location,$phone,$email,$time,$website,$name,$rating,$date,$sub_cat);
$title = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];
$location = $_POST['location'];
$phone = $_POST['phone'];
$time = $_POST['time'];
$rating = $_POST['rating'];
$main = $_POST['main'];
$website = $_POST['website'];
$date = date('Y-m-d');
$stmt->execute();
$stmt->close();
}
else
{
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
}
else
{
echo 'a';
}
your script appears to be incomplete, but doing the best i could with what you had this is what you need. first of all, ditch whatever mysqli wrapper crap you are using. it is teaching you bad principles.
first file, your db info. call it config.php or whatever the hell you want. use require once instead of include. also, ditch the parenthesis around the requires these are not necessary at all, and use single quotes instead of double quotes. single quotes are treated as strings while double quotes php will search for variables inside, thus spending more resources from the cpu/cache.
config.php
$host = 'localhost';//your db host
$user = 'someuser'; //your db user
$pass = 'somepass'; //your db password
$name = 'somedb'; //the name of your db
$mysqli = new mysqli($host,$user,$pass,$name);
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit;
}else{
global $mysqli;//make your db connection available globally
}
Now for your script
script.php
require_once 'config.php';
//keep your post variables up here. you still need to santize and trim these
$title = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];
$location = $_POST['location'];
$phone = $_POST['phone'];
$time = $_POST['time'];
$rating = $_POST['rating'];
$main = $_POST['main'];
$website = $_POST['website'];
$date = date('Y-m-d');
global $mysqli;//fetch your db connection
$stmt = $mysqli->prepare("SELECT tbl_name from listing_title where listing_title_ID = ? ");
$stmt->bind_param('i',$main_id);
if($stmt->execute()) {
$stmt->bind_result($tbl_name);
$stmt->close();
$stmt = $mysqli->prepare("INSERT INTO ".$tbl_name."
(Name, Address, Location, Phone, Email, Time, Website, Photo1, Rating, Date_Published, categories_ID)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
$stmt->bind_param('ssssssssisi',$title,$address,$location,$phone,$email,$time,$website,$name,$rating,$date,$sub_cat);
if($stmt->execute()) {
$stmt->close();
}else{
$stmt->close();
//catch the error
}
}else{
$stmt->close();
//throw an exception or handle the error here.
}
Please note, this still needs work. you need to sanitize and trim your variables. here's an example function. to include funcs, just add a require_once to the config.php file, and it will be included in any file you include config.php in.
example of this:
require_once 'funcs.php';
example sanitize function:
funcs.php
function security($value) {
if(is_array($value)) {
$value = array_map('security', $value);
} else {
if(!get_magic_quotes_gpc()) {
$value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
} else {
$value = htmlspecialchars(stripslashes($value), ENT_QUOTES, 'UTF-8');
}
$value = str_replace("\\", "\\\\", $value);
}
return $value;
}
to call the function
$title = security(trim($_POST['name']));
I leave the sanitizing to you. its a valuable exercise and you have an example that will sanitize anything, whether it be integers, arrays, objects, or strings.
you should only use trims on strings though. if you want to sanitize an entire array, just use the security function.
good luck.