I make a project in android studio for login/register.
I use volley library and a php script that connects my java code with my database.The POST method working perfectly and i can insert information in my database.But i get nothing on response.Seems there is an error in my php script.
Here is the php script:
$con = mysqli_connect("mysql10.000webhost.com", "a3288368_user", "abcd1234", "a3288368_data");
$name = $_POST["name"];
$age = $_POST["age"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (name, age, username, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "siss", $name, $age, $username, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
Any ideas what is going wrong?
Use
print_r(json_encode($response));
You can't echo json string.
Before echoing out the response, you should set a JSON header:
header("Content-type: application/json; charset=utf-8");
This tells the HTTP client to expect a JSON type of content.
Related
Hi I'm trying to insert the json array into my MySQL database. I'm passing the data form my iphone there i have converted the data into json format and I'm passing the data to my server using the url its not inserting into my server.
This is my json data.
[{"name":"0","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"13123123","phone":"sdfsdfdsfsd","city":"sdfsf","email":"13123123"}]
This is my Php code.
<?php
$json = file_get_contents('php://input');
$obj = json_decode($data,true);
//Database Connection
require_once 'db.php';
/* insert data into DB */
foreach($obj as $item) {
mysql_query("INSERT INTO `database name`.`table name` (name, phone, city, email)
VALUES ('".$item['name']."', '".$item['phone']."', '".$item['city']."', '".$item['email']."')");
}
//database connection close
mysql_close($con);
//}
?>
My database connection code.
<?php
//ENTER YOUR DATABASE CONNECTION INFO BELOW:
$hostname="localhost";
$database="dbname";
$username="username";
$password="password";
//DO NOT EDIT BELOW THIS LINE
$link = mysql_connect($hostname, $username, $password);
mysql_select_db($database) or die('Could not select database');
?>
Please tell where I'm doing wrong in the above code basically I'm not a php developer I'm mobile application developer so I'm using the php as a server side scripting please tell me how to resolve this problem.
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
I think you are passing the wrong variable. You should pass $json in json_decode as shown above.
You are missing JSON source file. Create a JSON file then assign it to var data:
<?php
require_once('dbconnect.php');
// reading json file
$json = file_get_contents('userdata.json');
//converting json object to php associative array
$data = json_decode($json, true);
// preparing statement for insert query
$st = mysqli_prepare($connection, 'INSERT INTO users(firstname, lastname, gender, username) VALUES (?, ?, ?, ?)');
// bind variables to insert query params
mysqli_stmt_bind_param($st, 'ssss', $firstname, $lastname, $gender, $username);
// processing the array of objects
foreach ($data as $user) {
$firstname = $user['firstname'];
$lastname = $user['lastname'];
$gender = $user['firstname'];
$username = $user['username'];
// executing insert query
mysqli_stmt_execute($st);
}
There is no such variable as $data. Try
$obj = json_decode($json,true);
Rest looks fine. If the error still persists, enable error_reporting.
Its simple you can insert json datatype as below. reference link: click here for more details
insert into sgv values('c-106', 'admin','owner',false,'[{"test":"test"},
{"test":"test"}]',0,'pasds');
$string=mysql_real_escape_string($json);
header("Access-Control-Allow-Origin: http://localhost/rohit/");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
//files needed to connect to database
include_once 'config/database.php';
include_once 'objects/main.php';
//get Database connection
$database = new Database();
$db = $database->getConnection();
//instantiate product object
$product = new Product($db);
//get posted data
$data = json_decode(file_get_contents("php://input"));
//set product property values
$product->b_nm = $data->Business_Name;
$product->b_pno = $data->Business_Phone;
$product->b_ads = $data->Business_Address;
$product->b_em = $data->Business_Email;
$product->b_typ = $data->Business_Type;
$product->b_ser = $data->Business_Service;
$name_exists = $product->nameExists();
if($name_exists){
echo json_encode(
array(
"success"=>"0",
"message" => "Duplicate Record Not Exists."
)
);
} else{
if($product->b_nm != null && $product->b_pno != null && $product->b_ads != null && $product->b_em != null && $product->b_typ != null && $product->b_ser != null){
if($product->create()){
//set response code
http_response_code(200);
//display message: Record Inserted
echo json_encode(array("success"=>"1","message"=>"Successfully Inserted"));
}
}
else{
//set response code
http_response_code(400);
//display message: unable to insert record
echo json_encode(array("success"=>"0","message"=>"Blank Record Not Exists."));
}
}
I'm trying to create a basic Register and Log in Application by following this tutorial: https://www.youtube.com/watch?v=JQXfIidfFMo&t=193s and because the code in Android Studio has shown 0 Compile Errors I've decided not to put that here.
What's wrong
Many users have reported in the comments section both old and new that they could not get their information sent to their database so any help would be greatly appreciated. The user inputs their 'name', 'username', 'password', and 'age' to register and this information is to then sent to my database hosted on 000webhost. Everything has been followed to the T.
The name of the table is called 'user'.
Here is the code to my Login.php file
<?php
$con = mysqli_connect("localhost:3306","id7390457_user","abcd1234","id7390457_data");
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ssis", $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $user_id, $name, $age, $username, $password);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["name"] = $name;
$response["age"] = $age;
$response["username"] = $username;
$response["password"] = $password;
}
echo json_encode($response);
?>
Here is the code to my Register.php file
<?php
$con = mysqli_connect("localhost", "id7390457_user", "abcd1234", "id7390457_data");
$name = $_POST["name"];
$age = $_POST["age"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (name, age, username, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssis", $name, $age, $username, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
I have been under the impression that the line
$con = mysqli_connect("localhost", "id7390457_user", "abcd1234", "id7390457_data");
Is followed by using ('hostname', 'username', 'password', 'nameofdatabase')
However as I am doing this from my Mac so my host is 'localhost'
My DB Name is: id7390457_data
My DB User is: id7390457_user
I've tried using 'localhost:3306'
I've tried just 'user' and 'data'
I've watched YouTube videos, visited websites in other languages and none have seemed to provide any advise.
I've deleted multiple databases starting from scratch but I still face the issue whereby my information isn't being sent to phpMyAdmin on 000webhost.
My webhost doesn't have an index.html page but I don't think that this would be the issue.
Thank you
Any help would mean the world to me. Thank you wish you well!
Hi and welcome to StackOverflow!
You are right, the mysqli_connect expects the host, user, pass and db name in that order, so if the database is running and the values are correct as you said, this looks OK.
However on this line, note the second argument ssis:
mysqli_stmt_bind_param($statement, "ssis", $name, $age, $username, $password);
It states the type of the parameters, s for string and i for integer. It looks like the order is messed up, because age is expected as a string and username as an integer. If you replace it with siss, I would expect it to work.
More info: https://secure.php.net/manual/en/mysqli-stmt.bind-param.php
I'm trying to get my Android Studio register app to send information to the database. I'm using a WAMP server. Below is my Register.php code that was uploaded and if anyone sees anything wrong with it could you help to amend it?
<?php
$con = mysqli_connect("localhost", "root", "", "users");
$Name = $_POST["Name"];
$DoctorNumber = $_POST["DoctorNumber"];
$Password = $_POST["Password"];
$statement = mysqli_prepare($con, "INSERT INTO users(Name, DoctorNumber, Password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "siss", $Name, $DoctorNumber, $Password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
You can't connect your Android (or even iOS) app directly to a MysQL database. You'll have to create a webapp that exposes it, and the use a library like Retrofit to make the http calls.
I have been trying to build a register and login android app using php and mysql with android studio. It appears that the values are being entered to the databse but it is not giving a response back. Table name is harry and php file is:
<?php
define('DBUSER', 'id650955_gokulm100');
define('DBPASS', 'gokulm100');
define('DBHOST', 'localhost');
define('DBNAME', 'id650955_harry');
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
if (!$conn) {
die('error connecting to database');
}
echo 'you have created case';
if(isset($_POST["username"]) && isset($_POST["email"]) && isset($_POST["phone"]) && isset($_POST["password"]))
{
$username = $_POST["username"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$password = $_POST["password"];
$statement = mysqli_prepare($conn, "INSERT INTO harry (username, email, phone, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssis", $username, $email, $phone, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = 1;
echo json_encode($response);
}
else{
echo "not set";
}
?>
assuming that the data is inserted to the database you need to look at your output, it looks like you're sending json text via json_encode and in the same time echo a string "you have created case"
so your output will be a mix of simple characters and some json string. which probably send a parsing error to the callback in the android side of the code.
first you should add a header that indicates the you will be returning json code at the top of the file
header("Content-Type: application/json",true);
then change all your output to be json , any
echo "str";
should be
echo json_encode(array("message"=>"str"));
then see if you still don't get any message back.
I am following a tutorial of making a login register for android by tonakami TV in youtube, I encountered a problem where the android app can't update or connect to the database via LOCALHOST XAMPP. For one week I'm stuck searching all possible solution but found none. Perhaps you guys can help me with the problem of my PHP files(register.php and fetchuserdata.php), I also found out that I also have this error in the php files: mysqli_connect(): (HY000/1044): Access denied for user 'my_user'#'localhost' to database 'my_db'. I grant all privileges but still can't connect and I don't know if the problem is from the PHP files, the link to the server in android studio or of XAMPP localhost phpmyadmin. Thanks !
Screenshot of Android Studio: highlighted link
Register.php
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$name = $_POST["name"];
$age = $_POST["age"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO User (name, age, username, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "siss", $name, $age, $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
mysqli_close($con);
?>
FetchUserData.php
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM User WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $name, $age, $username, $password);
$user = array();
while(mysqli_stmt_fetch($statement)){
$user["name"] = $name;
$user["age"] = $age;
$user["username"] = $username;
$user["password"] = $password;
}
echo json_encode($user);
mysqli_close($con);
?>
Instead of localhost use this: http://10.0.2.2
Reference