How to execute php script for web application in IntelliJ? - php

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

Related

Checking registered email and mobile in database using PHP and SQL

I have this PHP code, which registers a user. All form validation is done by jQuery and the request is sent by Ajax to this PHP page. Everything is working fine except it’s not checking if email and mobile is already registered.
<?php
require('db_connection.php');
$error = "";
if($_SERVER['REQUEST_METHOD'] == "POST"){
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$password = $_POST['password'];
$hashed_password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt = $conn->prepare("SELECT `user_email`, `user_mobile` FROM `users` where `user_email` = ? && `user_mobile` = ? LIMIT 1");
$stmt->bind_param("si", $email, $mobile);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows() > 0){
$row = $stmt->fetch();
if($email == isset ($row['user_email'])){
echo "email exists";
}
if($mobile == isset($row['user_mobile'])){
echo "mobile exists";
}
}else{
$stmt = $conn->prepare("INSERT INTO `users`(`user_name`, `user_email`, `user_mobile`, `user_password`) values (?, ?, ?, ?)");
$stmt->bind_param("ssis", $name, $email, $mobile, $hashed_password);
$stmt->execute();
echo "successfull";
}
$stmt->close();
}
$conn->close();
?>
from my observation the problem is somewhere I'm fetching the rows, because the registration is happening with different email and mobile.

PHP Prepared Statement not executing correctly

I have been staring at a problem for far to long now.
I have a PHP file that is preparing an insert query, binding the params, and executing the query (Simple).
QUERY
$stmt = $db->prepare("SELECT insert_user(?, ?, ?, ?, ?, ?)");
For some reason the $stmt object returned by execute returns -1 for the affected rows. If I alter the code to do just an insert query with the values I wanted to bind, hard coded instead, the query works just fine.
HARD CODED QUERY
$db->query("SELECT insert_user('Test', 'Account', 'testAccount#testApp.io', 'testAccount9', '1980-01-01', 1)");
Something is going wrong in the bind_param section. I have errors turned on and am checking for mysqli errors too, but both are returning no errors.
PHP FILE
...
$postdata = file_get_contents("php://input");
if (isset($postdata) && !empty($postdata)) {
$request = json_decode($postdata);
}
if (
validate_string($request->fname)
&& validate_string($request->lname)
&& validate_integer(intval($request->gender))) {
$stmt = $db->prepare("SELECT insert_user(?, ?, ?, ?, ?, ?)");
if ($stmt) {
$stmt->bind_param("ssssis", $first_name, $last_name, $email, $password, $gender, $dob);
$first_name = $request->fname;
$last_name = request->lname;
$email = $request->email;
$password = password_hash($request->password, PASSWORD_BCRYPT);
$gender = intval($request->gender);
$dob = $request->dob;
$stmt->execute();
if ($stmt->affected_rows > 0) {
echo toJson('success');
} else {
echo toJson('fail');
}
} else {
echo toJson("Prepare failed: (" . $db->errno . ") " . $db->error);
}
} else {
echo toJson('fail - passed data not valid');
}
...
I feel the error must be simple at this point, but I have tried at least 23,432 different things to no success.
My guess the problem is here "ssssis" .
The fifth should be string, the last integer. Maybe this should work?

Multiple prepared statements on same page MYSQLI

I have some issues with my code. It seems like I'm not able to have multiple prepared statements which seems a little unusual to me.
I would be glad if you can spot an error or help me because I can't figure out the issue.
My error:
Fatal error: Call to a member function bind_param() on boolean in /Applications/XAMPP/xamppfiles/htdocs/platform/creating_user.php on line 37
I am trying to check if the users email already exists in the database and then register the user.
The code works fine when i dont execute the $check.
$check->execute();
I would also like some response on my workflow (the way my code is built up). is it okay?
Thanks!
<?php
$db = new mysqli("localhost","root","","database");
session_start();
if (isset($_POST)){
if(
!empty($_POST["name"])
& !empty($_POST["city"])
& !empty($_POST["zip"])
& !empty($_POST["email"])
& !empty($_POST["tel"])
& !empty($_POST["password"])
) {
$name = encrypt($_POST["name"]);
$city = encrypt($_POST["city"]);
$zip = encrypt($_POST["zip"]);
$email = encrypt($_POST["email"]);
$tel = encrypt($_POST["tel"]);
$password = encrypt($_POST["password"]);
if(!empty($name) && !empty($city) && !empty($zip) && !empty($email) && !empty($tel) && !empty($password)) {
$check = $db->prepare("SELECT email FROM user WHERE email = ?");
$check->bind_param('s', $email);
$check->execute();
if ($check->num_rows == 1) {
header("Location: index.php");
die();
} else {
$insert = $db->prepare("INSERT INTO user (name, city, zip, email, tel, password, created) VALUES (?, ?, ?, ?, ?, ?, NOW())");
$insert->bind_param("ssssss",$name, $city, $zip, $email, $tel, $password);
if ($insert->execute()){
$db->close();
$_SESSION["user"] = $email;
header("Location: created_user");
die();
} else {
header("Location: create-user");
die();
}
}
} else {
header("Location: create-user");
die();
}
} else {
header("Location: create-user");
die();
}
} else {
header("Location: create-user");
die();
}
?>
On php.net I found this
mysqli::prepare() returns a statement object or FALSE if an error
occurred.
So this mean something is wrong with your $db object. This could be:
Wrong password
Wrong username
...

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.

mysqli insert statement problems

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.

Categories