Adding data to database - php

When I try to add a user to the database with POST a new user is added but all fields are Null.
Any help guys ? Thank you in advance.This is my source code:
if($_SERVER['REQUEST_METHOD'] == "POST")
{
// Get data
$name = isset($_POST['name']) ;
$email = isset($_POST['email']);
$password = isset($_POST['password']);
$status = isset($_POST['status']);
// Insert data into data base
$sql = "INSERT INTO users (`name`, `email`, `password`, `status`) VALUES ('$name', '$email', '$password', '$status')";
$qur = mysql_query($sql);
if($qur){
$json = array("status" => 1, "msg" => "Done User added!");
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
**

isset return only true or false so if you want to insert value you can check it with if condition replace your code with above it will be work fine
if($_SERVER['REQUEST_METHOD'] == "POST"){
$name = (isset($_POST['name']))?$_POST['name']:'' ;
$email = (isset($_POST['email']))?$_POST['email']:'';
$password = (isset($_POST['password']))?$_POST['password']:'';
$status = (isset($_POST['status']))?$_POST['status']:'';
$sql = "INSERT INTO users (`name`, `email`, `password`, `status`) VALUES ('$name', '$email', '$password', '$status')";
$qur = mysql_query($sql);
if($qur){
$json = array("status" => 1, "msg" => "Done User added!");
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
header('Content-type: application/json');
echo json_encode($json);
save this form in html file and check it with this edited example
<form method="post">
<input type="text" name="name" value="Red Symbol" />
<input type="text" name="email" value="red#symbol.com" />
<input type="text" name="password" value="chock" />
<input type="text" name="status" value="1" />
<input type="submit" name="submit" value="Submit" />
</form>

You are not checking if any of the fields are empty.
You need to do that, and only perform the query if they are not.
You can also restructure your code to avoid nested if/else:
function sendJson($data){
header('Content-type: application/json');
echo json_encode($data);
//stop execution after sending response
exit;
}
//if not POST request, exit
if($_SERVER['REQUEST_METHOD'] !== "POST") {
sendJson(["status" => 0, "msg" => "Request method not accepted"]);
}
//default data
$defaults = [
'name' => false,
'email' => false,
'password' => false,
'status' => false,
];
$input = array_intersect_key(array_merge($defaults, $_POST), $defaults);
//if empty field, exit
if(in_array(false, $input)){
sendJson(["status" => 0, "msg" => "All fields are required"]);
}
// Insert data into data base
//you REALLY REALLY need to use PDO/MYSQLI with prepared statements, this code is dangerous
$sql = "INSERT INTO users (`name`, `email`, `password`, `status`) VALUES ('$input[name]', '$input[email]', '$input[password]', '$input[status]')";
$qur = mysql_query($sql);
//if query failed, exit
if(!$qur){
sendJson(["status" => 0, "msg" => "Error adding user!"]);
}
//if we get here, all is OK
sendJson(["status" => 1, "msg" => "Done User added!"]);
#mysql_close($conn);

Related

Issue with sending information from contact form

I am trying to send the values from a php form as email. When I set the $message to var_export($_POST,true); it exports the information but not in a easily readable way.
I have tried to set the values for each one as $complain_detail = $_POST['complain_detail']; but it stops the page from working or does not send the email.
<?php
include 'main.php';
check_loggedin($pdo);
// output message (errors, etc)
$msg = '';
if ($_POST['submit']) {
if ($_POST['complain_type'] == null || $_POST['complain_title'] == null || $_POST['complain_issue_type'] == null || $_POST['complain_form'] == null || $_POST['complain_assigned_to'] == null || $_POST['complain_detail'] == null) {
$msg = "Something missing, please input all required information.";
} else {
$stmt = $pdo->prepare('INSERT IGNORE INTO complains (id, complain_type, complain_from, complain_assigned_to, complain_title, complain_detail, complained_date, complain_issue_type, complain_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
$status = $stmt->execute(["", $_POST['complain_type'], $_POST['complain_form'], $_POST['complain_assigned_to'], $_POST['complain_title'], $_POST['complain_detail'], date("Y-m-d H:i:s"), $_POST['complain_issue_type'], "Open"]);
$complain_id = $pdo->lastInsertId();
$incident_record = $pdo->prepare('INSERT IGNORE INTO incident_record (id,complain_id, user_id, issue_date, assign_to, assign_by_client, record_type, record_details) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
$status = $incident_record->execute(["", $complain_id , $_SESSION['id'], date("Y-m-d H:i:s"), $_POST['complain_assigned_to'], $_POST['complain_form'], 'Created' , 'Complain Title: ' . $_POST['complain_title'] . ', Complain Details : ' . $_POST['complain_detail'] . ', Complain Issue Type : ' . $_POST['complain_issue_type']. ', Open' ]);
$to_email = 'email#sdf.coms';
$subject = 'New Incident Logged';
$message = var_export($_POST,true);
$headers = 'From: email#sdf.coms';
mail($to_email,$subject,$message,$headers,"-f email#sdf.coms");
$msg = "Incident has been loggged.";
}
} else {
$msg = "Whoops, something went wrong - Please try again.";
}
?>
Currently format is been sent as
array ( 'complain_type' => 'WASP', 'complain_title' =>
'Test', 'complain_assigned_to' => '9', 'complain_issue_type' =>
'Support', 'complain_form' => '9', 'complain_detail' => 'Is this
better?', 'submit' => 'Submit Issue', )
I would like to to read as
"A ticket has been opened under "type" and has been assigned to "user"
"with description!
$_POST is an array, containing the request elements. Let's try to visualise it together...
If you have this HTML:
<form action="action.php" method="post">
<p>Your name: <input type="text" name="name" /></p>
<p><input type="submit" /></p>
</form>
And this action.php file:
<?php var_dump($_POST);?>
The output will be the following:
array(1) { ["name"]=> string(1) "1" }
So, in order to access the name value within the array, I need to call for $_POST["element"] where your element is the HTML name of the request parameter.
So, if in your HTML, the message is obtained with the following input:
<input type="text" name="message" />
In order to properly retrieve it in your PHP code, you need to adjust the $message variable to be the following:
$message = $_POST["message"];
Thus, you can concatenate your request parameters into your message variable like this:
$message = "A ticket has been opened under " . $_POST["complain_type"] . " and has been assigned to user " . $_POST["complain_assigned_to"] . " with description " . $_POST["complain_detail"];

Can't post the values in 000webhost phpmyadmin database [duplicate]

This question already has answers here:
mysqli_real_escape_string() expects exactly 2 parameters, 1 given
(5 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I am trying to post the value in my database's table which i have made in 000webhost phpmyadmin server.To post/check i am using the postman software.
In postman software i am passing the key value pairs (in form-data selection and also tried to pass in x-www-form-urlencoded). But values getting added are null. not that i have pass in key value pairs.
And when i am passing without any key value pair it still adds the row with null values in my table.
Please help to solve..
I making this api to use it in my android application.
Here in my php code:
confi.php:
<?php
error_reporting(1);
$conn = mysqli_connect("localhost", "********", "******","id1536885_mydb");
?>
individualuser_details.php:
<?php
// Include confi.php
include_once('confi.php');
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
$name = isset($_POST['name']) ? mysqli_real_escape_string($_POST['name']) : "";
$adhar = isset($_POST['adhar']) ? mysqli_real_escape_string($_POST['adhar']) : "";
$email = isset($_POST['email']) ? mysqli_real_escape_string($_POST['email']) : "";
$password = isset($_POST['password']) ? mysqli_real_escape_string($_POST['password']) : "";
$contact = isset($_POST['contact']) ? mysqli_real_escape_string($_POST['contact']) : "";
$status = isset($_POST['status']) ? mysqli_real_escape_string($_POST['status']) : "";
//echo $name.' no';
// Insert data into data base
$sql ="INSERT INTO id1536885_mydb.`individualuser_details` (`ID`, `name`, `adhar`, `email`, `password`, `contact`, `status`) VALUES (NULL, '$name', '$adhar', '$email', '$password', '$contact', '$status');";
// echo $sql;
$qur = mysqli_query($conn,$sql);
if($qur){
$json = array("status" => 1, "msg" => "Done User added!");
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysqli_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>

PHP - JSON empty values in database

I am very new to php. I wan't to create json service which will be responsible to save registration form values in database. The problem is, it saves empty values in database. The problem is I can't understand how to get values from json and save them in database
php code
<?php
// Include confi.php
include_once('confi.php');
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
$name = isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) :'';
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : '';
$password = isset($_POST['pwd']) ? mysql_real_escape_string($_POST['pwd']) : '';
$status = isset($_POST['status']) ? mysql_real_escape_string($_POST['status']) : '';
// Insert data into data base
$sql = "INSERT INTO `test`.`users` (ID,`name`, `email`, `password`, `status`) VALUES (NULL,'$name', '$email', '$password', '$status');";
$qur = mysql_query($sql);
if($qur){
$json = array("status" => 1, "msg" => "Done User added!");
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
Sending values with post method
{
"name":"aamir",
"email":"a#a.com",
"pwd":"12345678",
"status":"yes"
}
This is the result
and I have followed this link
https://trinitytuts.com/build-first-web-service-php/
From my opinion you have problems with client-server interactions.
PHP did not parse JSON data, it work only with url-encoded values.
So, your $_POST variable is empty array.
To get JSON formatted values, you should use
$post = json_decode(file_get_contents('php//input'), true));

PHP Post Webservice Issue

Trying to implement a post webservice in PHP so that finally it can be used in ios app for communicating to DB. Can you please identify the mistake.
Please find the code below. It is saying that "Request Method not accepted" status 0 returned
<?php
// Create connection
$con=mysqli_connect("myhost.com","myuser","mypassword","mydb");
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
$lat= isset($_POST['lat']) ? mysql_real_escape_string($_POST['long']) : "";
$long= isset($_POST['long']) ? mysql_real_escape_string($_POST['long']) : "";
$timeStamp = isset($_POST['timeStamp']) ? mysql_real_escape_string($_POST['timeStamp']) : "";
$deviceId = isset($_POST['deviceId']) ? mysql_real_escape_string($_POST['deviceId']) : "";
// Insert data into data base
$sql = "INSERT INTO `gpsReporting` (`lat`, `long`, `timeStamp`, `deviceId`) VALUES ('$lat', '$long', '$timeStamp', '$deviceId');";
$qur = mysql_query($sql);
if($qur){
$json = array("status" => 1, "msg" => "Done User added!");
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);

MySQL parameter error

I'm trying to get my query to work for this PHP but I'm getting a "Invalid Parameter Number: number of bound variables do not match number of tokens" This is a snippet of my PHP:
<?php
/*
Our "config.inc.php" file connects to database every time we include or require
it within a php script. Since we want this script to add a new user to our db,
we will be talking with our database, and therefore,
let's require the connection to happen:
*/
require("configmob.php");
//if posted data is not empty
if (!empty($_POST)) {
//If the username or password is empty when the user submits
//the form, the page will die.
//Using die isn't a very good practice, you may want to look into
//displaying an error message within the form instead.
//We could also do front-end form validation from within our Android App,
//but it is good to have a have the back-end code do a double check.
if (empty($_POST['FirstName']) || empty($_POST['LastName'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "Please Enter Both a First Name and a Last Name.";
//die will kill the page and not execute any code below, it will also
//display the parameter... in this case the JSON data our Android
//app will parse
die(json_encode($response));
}
//if the page hasn't died, we will check with our database to see if there is
//already a user with the username specificed in the form. ":user" is just
//a blank variable that we will change,Spot FROM Reservation WHERE Date = ':Date' AND Time = ':Time' AND Spot = ':Spot' ";
//now lets update what :user should be
$query = "Select * FROM Reservation WHERE Date = ':Date' AND TimeIn = ':TimeIn' AND Spot = ':Spot'";
$query_params = array(':Date' => $_POST['Date'] , ':TimeIn' => $_POST['Time'] , ':Spot' => $_POST['Spot']
);
//Now let's make run the query:
try {
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
die(json_encode($response));
}
//fetch is an array of returned data. If any data is returned,
//we know that the username is already in use, so we murder our
//page
$row = $stmt->fetch();
if ($row) {
// For testing, you could use a die and message.
//die("This username is already in use");
//You could comment out the above die and use this one:
$response["success"] = 0;
$response["message"] = "I'm sorry, this Reservation is already Taken";
die(json_encode($response));
}
//If we have made it here without dying, then we are in the clear to
//create a new user. Let's setup our new query to create a user.
//Again, to protect against sql injects, user tokens such as :user and :pass
$query = "INSERT INTO Reservation (Fname, Lname, Garno, Gname, EmpID, CustID, License, Floor, Spot, TimeIn, TimeOut, Date, Confirmation)
VALUES (:Fname, :Lname, :Garno, :Gname, :EmpID, :CustID, :License, :Floor, :Spot, :TimeIn, :TimeOut, :Date, :Confirmation) ";
//Again, we need to update our tokens with the actual data:
$query_params = array(
':Fname' => $_POST['FirstName'],
':Lname' => $_POST['LastName'],
':Gname' => $_POST['Garage'],
':Date' => $_POST['Date'],
':TimeIn' => $_POST['Time'],
':Spot' => $_POST['Spot'],
':Confirmation' => $_POST['Confirmation'],
);
//time to run our query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
die(json_encode($response));
}
//If we have made it this far without dying, we have successfully added
//a new user to our database. We could do a few things here, such as
//redirect to the login page. Instead we are going to echo out some
//json data that will be read by the Android application, which will login
//the user (or redirect to a different activity, I'm not sure yet..)
$response["success"] = 1;
$response["message"] = "Reservation Added!!";
echo json_encode($response);
//for a php webservice you could do a simple redirect and die.
//header("Location: loginmob.php");
//die("Redirecting to loginmob.php");
} else {
?>
<h1>Register</h1>
<form action="register.php" method="post">
Username:<br />
<input type="text" name="username" value="" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
<input type="submit" value="Register New User" />
</form>
<?php
}
?>
Thank you for the help!
This is what I found in your second statement:
$query = "Select * FROM Reservation WHERE Date = ':Date' AND TimeIn = ':Time' AND Spot = ':Spot'";
$query_params = array(':Date' => $_POST['Date'] , ':TimeIn' => $_POST['Time'] , ':Spot' => $_POST['Spot']
);
Your :TimeIn should be :Time like follows:
$query_params = array(':Date' => $_POST['Date'] , ':Time' => $_POST['Time'] , ':Spot' => $_POST['Spot']
Update:
Also in your second query you have :Garno missing, please try the following:
$query = "INSERT INTO Reservation (Fname, Lname, Garno, Gname, EmpID, CustID, License, Floor, Spot, TimeIn, TimeOut, Date, Confirmation)
VALUES (:Fname, :Lname, :Garno, :Gname, :EmpID, :CustID, :License, :Floor, :Spot, :TimeIn, :TimeOut, :Date, :Confirmation) ";
//Again, we need to update our tokens with the actual data:
$query_params = array(
':Fname' => $_POST['FirstName'],
':Lname' => $_POST['LastName'],
':Garno' => $_POST['Garno'], // Hopefully $_POST['Garno'] is what you want.
':EmpID' => $_POST['EmpID'], // Hopefully $_POST['EmpID'] is what you want.
':CustID' => $_POST['CustID'], // Hopefully $_POST['CustID'] is what you want.
':License' => $_POST['License'], // Hopefully $_POST['License'] is what you want.
':Floor' => $_POST['Floor'], // Hopefully $_POST['Floor'] is what you want.
':TimeOut' => $_POST['TimeOut'], // Hopefully $_POST['TimeOut'] is what you want.
':Gname' => $_POST['Garage'], // You don't need this, remove this.
':Date' => $_POST['Date'],
':TimeIn' => $_POST['Time'],
':Spot' => $_POST['Spot'],
':Confirmation' => $_POST['Confirmation'],
);

Categories