I'm a beginner in PHP and i've got this code where both if and else parts are executed in the same "run". I know it's logically impossible but that's what I'm getting.
Here's my PHP Code:
<?php
require_once 'create_request_form.php';
$db = new create_request_form();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['rqTitle']) && isset($_POST['rqMname']) && isset($_POST['rqUname']) && isset($_POST['rqBranch']) && isset($_POST['rqText']) && isset($_POST['rqMinPrice']) && isset($_POST['rqMaxPrice']) && isset($_POST['rqImage']) && isset($_POST['rqCategory']) && isset($_POST['rqDateTime'])) {
// receiving the post params
$rqTitle = $_POST['rqTitle'];
$rqMname = $_POST['rqMname'];
$rqUname = $_POST['rqUname'];
$rqBranch = $_POST['rqBranch'];
$rqText = $_POST['rqText'];
$rqMinPrice = $_POST['rqMinPrice'];
$rqMaxPrice = $_POST['rqMaxPrice'];
$rqImage = $_POST['rqImage'];
$rqCategory = $_POST['rqCategory'];
$rqDateTime = $_POST['rqDateTime'];
// check if there is a request with the same title
if ($db->checkReqTitle($rqTitle)) {
// Request already exists
$response["error"] = TRUE;
$response["error_msg"] = "Request already exists with the title: " . $rqTitle;
echo json_encode($response);
} else {
// create a new request
$request = $db->StoreReqInfo($rqTitle, $rqMname, $rqUname, $rqBranch, $rqText, $rqMinPrice, $rqMaxPrice, $rqImage, $rqCategory, $rqDateTime);
if ($request) {
// request stored successfully
$response["error"] = FALSE;
$response["request"]["rqTitle"] = $request["rqTitle"];
$response["request"]["rqMname"] = $request["rqMname"];
$response["request"]["rqUname"] = $request["rqUname"];
$response["request"]["rqBranch"] = $request["rqBranch"];
$response["request"]["rqText"] = $request["rqText"];
$response["request"]["rqMinPrice"] = $request["rqMinPrice"];
$response["request"]["rqMaxPrice"] = $request["rqMaxPrice"];
$response["request"]["rqImage"] = $request["rqImage"];
$response["request"]["rqCategory"] = $request["rqCategory"];
$response["request"]["rqDateTime"] = $request["rqDateTime"];
echo json_encode($response);
} else {
// request failed to store
$response["error"] = TRUE;
$response["error_msg"] = "An error occurred while creating the request. Please try again.";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter is missing!";
echo json_encode($response);
}
?>
The required behavior (storing data in the database) is all performed well but the $response I'm getting is the error string i've assigned to when a request title already exists instead of the JSON formatted array of the stored request (Both if and else bodies are executed but i get the result of if body as a response).
A screenshot of the $response using Postman to send the request:
A screenshot from my Samsung Galaxy Note 3:
I'm also using Galaxy Note 4 for testing and it just shows me a blank Toast message and doesn't start the intent(doesn't move to home screen).
So far the only possible explanation is that the script is being executed twice, however I can't find anywhere that called it a second time.
This is the java code responsible for sending a request with required paramters to the php script above.
private void storeRequest(final String rTitle, final String rMname, final String rUname,
final String rBranch, final String rText, final String rMinPrice,
final String rMaxPrice, final String imagePath, final String rCategory) {
// Tag used to cancel the request
String cancel_req_tag = "request";
//A progress dialog message to let the user know they are being registered
progressDialog.setMessage("Please wait while we add your request...");
showDialog();
//creating a StringRequest to send the registration info to the script
// at the server for processing
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_REQUEST, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Request Response: " + response.toString());
hideDialog();
try { //json objects must be surrounded by try catch statement
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) { // error is set to false, meaning no error
// Launch home activity
Intent intent = new Intent(CreateRequestActivity.this, HomeActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(CreateRequestActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(CreateRequestActivity.this,
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("rqTitle", rTitle);
params.put("rqText", rText);
params.put("rqMname", rMname);
params.put("rqUname", rUname);
params.put("rqBranch", rBranch);
params.put("rqMinPrice", rMinPrice);
params.put("rqMaxPrice", rMaxPrice);
params.put("rqImage", imagePath);
params.put("rqCategory", rCategory);
params.put("rqDateTime", DateFormat.getDateTimeInstance().format(new Date()));
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
Any ideas?
Thanks in advance!
So turns out the problem stemmed from the Java code and not PHP (poor PHP ;P). More accurately, Volley requests have a problem with request timeouts, especially when sending requests using POST method.
So what worked for me was adding this line right before adding the request to the queue:
strReq.setRetryPolicy(new DefaultRetryPolicy(0, -1, 0));
*Replace strReq with your request name. Basically what this line does is that it prevents volley from sending a duplicate request when the first request takes too long.
The original & more datailed answer:
The DefaultRetryPolicy.class's hasAttemptRemaining() class looks like this:
protected boolean hasAttemptRemaining() {
return this.mCurrentRetryCount <= this.mMaxNumRetries;
}
From what I can see, setting the maxNumRetries to 0 will still make that return true if it hasn't done a retry yet.
I fixed it with a
request.setRetryPolicy(new DefaultRetryPolicy(0, -1, 0);
Source: Android Volley makes 2 requests to the server when retry policy is set to 0
Related
why nothing happened when i put the correct email, but whatevet i put correct or incorrect password the program still not doing anything. It's like the program not checked the password, can you help me ?
This my login.php
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email = $_POST['email'];
$password = $_POST['password'];
require_once 'connect.php';
$sql = "SELECT * FROM user WHERE email='$email' ";
$response = mysqli_query($conn, $sql);
$result = array();
$result['login'] = array();
if ( mysqli_num_rows($response) === 1 ) {
$row = mysqli_fetch_assoc($response);
if ( password_verify($password, $row['password']) ) { // I Think The Problem At This but i still don't know.
echo $password;
$index['name'] = $row['name'];
$index['email'] = $row['email'];
$index['id'] = $row['id'];
array_push($result['login'], $index);
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
mysqli_close($conn);
} else {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
mysqli_close($conn);
}
}
}
?>
This my SignInActivity.java // or at this the problem is ?
public class SignInActivity extends AppCompatActivity {
private EditText email,password;
private Button login;
private TextView link_regist;
private static String URL_LOGIN = "https://awalspace.com/app/imbalopunyajangandiganggu/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
email = findViewById(R.id.titEmail);
password = findViewById(R.id.titPassword);
login = findViewById(R.id.btnSignIn);
link_regist = findViewById(R.id.tvToSignUp);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mEmail = email.getText().toString().trim();
String mPassword = password.getText().toString().trim();
if(!mEmail.isEmpty() || !mPassword.isEmpty())
{
login(mEmail,mPassword);
}
else{
email.setError("Silahkan Masukkan Email");
password.setError("Silahkan Masukkan Password");
}
}
});
}
private void login(final String email, final String password) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray =jsonObject.getJSONArray("login");
if (success.equals("1")){
for (int i = 0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name").trim();
String email = object.getString("email").trim();
Toast.makeText(SignInActivity.this, "Success Login. \n Your Name : "+name+"\nYour Email : "+email,Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SignInActivity.this, "Error "+e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SignInActivity.this, "Error "+error.toString(),Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email",email);
params.put("password",password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Partial answer:
First off
You are open to SQL injection. You should parameterize your query.
Parameterized queries in PHP with MySQL connection
Second
You can add the password to your query so you don't have to do a 2nd check, if you store the passed password in the DB, or you can hash your password first then use it in your query. That avoids getting more user data than necessary (with the associated possible leaking of data) and avoids needing a second method to find the correct user.
This is shown in the link above.
If you store a salt in the DB, I can understand why you need the 2nd method, but you might be able to salt the password in the SQL, via a SQL function. Since you don't include the code for password_verify, we have no way to know what you're actually doing there, so I'm keeping this as basic as I can. (My philosophy is to keep things simple until complications are required.)
Third
Even if you are getting all the columns in that table, specify the column names you need. You might end up adding to that table later, which would cause this query to pull more data than it needs, again.
Fourth
Since you already have the email, which is one of the parameters of the query, you don't need to get it from the DB.
FYI, the link above adds each parameter individually, but mysqli_stmt_bind_param can do them all in one shot.
Object oriented style
mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] ) : bool
Procedural style
mysqli_stmt_bind_param ( mysqli_stmt $stmt , string $types , mixed &$var1 [, mixed &$... ] ) : bool
...
types
A string that contains one or more characters which specify the types for the corresponding bind variables:
...
https://www.php.net/manual/en/mysqli-stmt.bind-param.php
$stmt = mysqli_prepare($dbc, "SELECT name, id FROM users WHERE email= ? AND password = ?");
mysqli_stmt_bind_param($stmt, "ss", $email, $password); // or use a hash from a method instead of $password
mysqli_stmt_execute($stmt);
$row = mysqli_stmt_fetch($stmt);
This should pull just the one user, unless it doesn't pull any users, so you should have a clear indication of whether this user has access to your site/data/whatever or not. I would suggest sending an actual success message that you can recognize as something a little more specific to you, rather than the generic message you have right now. I understand you're still in testing phase, so it's something to think about later, if you hadn't already.
I would also suggest sending an HTTP 401 message back if $row is null. That way it's 100% guaranteed that your client software understands what happened as well as not giving any specifics as to why it failed. You can still tell the user something more meaningful, such as "Email and Password Combination Not Recognized". Also, don't specify if the email or the password is wrong, since this can lead to easier brute force hacking. There's a lot of contention around this idea of prompts, so I'll let you do your own research and make up your mind about it.
Whether your Java code is correctly sending the login credentials to your PHP server, IDK. I'm rusty on that, so I'll let someone else chime in, and why I'm saying this is a partial answer. At least this answer should get your PHP on the right track.
I have done some queries to the database and they usually work but when I am trying to do it in the current class, I get the following error:
{"code":403,"success":false,"message":"Forbidden, No token provided"}
Both classes are too long to post here, and thus I think this is all I can provide:
SET_USER_STAR_COUNT = URL + "setUserProfileStars";
JSONObject request_data=new JSONObject();
try
{
request_data.put("newscore",newStars);
} catch (JSONException e)
{
e.printStackTrace();
}
OkHttp3Connection.doOkHttp3Connection("", Services_Url_class.SET_USER_STAR_COUNT, OkHttp3Connection.Request_type.POST, request_data, new OkHttp3Connection.OkHttp3RequestCallback() {
#Override
public void onSuccess(String result, String user_tag) {
System.out.println("oO" + result);
}
#Override
public void onError(String error, String user_tag)
{}
});
And here is the controller:
Router.post('/setUserProfileStars', function (req, res) {
var username = req.decoded.name;
var newStars = req.decoded.newscore;
var response = [];
var addStars = 'MATCH (n:User) WHERE n.username = "' + username + '" SET n.stars = "'+ newStars +'" RETURN n.stars AS totalStars';
dbneo4j.cypher({
query: addStars
}, function (err, data) {
if (err) {
return res.send({
code: 9325,
message: 'error encountered',
error: err
}).status(9325);
}
response.push(data);
res.send({
code: 200,
message: 'success',
data: response
}).status(200);
});
});
If there is anything else I can provide then I will do so.
The error comes when I try to print the result. My question is why is it doing so and how can I debug and check what is wrong with it?
403 Forbidden indicates that the server is refusing to process your request because you are not authorized. According to the message details, the server expects an authorization token to be passed as a header. You will have to work with the server to determine what "token" it expects.
I am making a login/register android app UI with nodejs as the backend language. Whats happening is that whenever I click the register button, it sends the json response before querying the database (select statement to check if username exists) causing the android app to get the wrong response which causes me to click the button twice to register the correct response. For instance lets say their is a username called test in the database and I try to sign up using the username test, it will tell me that the username is already taken and if erase test and enter lets say 'bob' which does not exist in the database it still says the username is already taken even though it is not but when I click the register button again it will register the user. I am assuming this is happening because it is async(it sends the json response while or before querying the database). How can I make this synchronus or is there another way to fix this?
server file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
//connection
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database : "androidtest"
});
//use json
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//declare variables to hold values entered by the user
var name;
var username;
var password;
var age;
//boolean array to let frontend know what is going on
var response;
app.post('/', function(req, res) {
//retrieve variables
username = req.body.username;
name = req.body.name;
age = req.body.age;
password = req.body.password;
//query database
//check if username is taken
var select = "SELECT * FROM users WHERE username = ? LIMIT 1";
con.query(select, [username], function (err, results) {
if (err) throw err;
//if username is taken send json string 'exists' to android app
if(results.length) {
response = {"exists" : "true"};
//if username is available send string 'success' and add the user to the database
} else {
var add = "INSERT INTO users (name, username, age, password) VALUES (?, ?, ?, ?)";
response = {"success" : "true"};
con.query(add, [name, username, age, password]);
if (err) throw err;
console.log('row inserted');
}
});
//send json
res.json(response);
//prevents the functions from being executed more than once
res.end('/');
});
//listen on port 3000
app.listen(3000);
android app java:
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = etName.getText().toString();
final String username = etUserName.getText().toString();
final String password = etPassword.getText().toString();
final int age = Integer.parseInt(etAge.getText().toString());
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
//Boolean exists = jsonResponse.getBoolean("exists");
String exists = jsonResponse.getString("exists");
if (exists.matches("true")) {
Toast toast = Toast.makeText(getApplicationContext(), "username already exists", Toast.LENGTH_SHORT);
toast.show();
}
} catch(Exception e) {
e.printStackTrace();
}
try {
JSONObject jsonResponse = new JSONObject(response);
//Boolean success = jsonResponse.getBoolean("success");
String success = jsonResponse.getString("success");
if (success.matches("true")) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, age, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
You have to put
res.json(...);
res.end('/');
after the closing bracker of the following line (after & outside the else block):
console.log('row inserted');
then it first gets executed when to query has finished.
Task: sync records from android sqlite to mysql.
Problem: mysql/php is not inserting data into my table in mysql. But no errors were shown.
DB_Connect.php:
<?php
class DB_Connect {
// constructor
function __construct(){
}
// destructor
function __destruct(){
}
// connecting to database
public function connect(){
require_once 'config.php'; // defined DB_HOST,DB_USER,DB_PASSWORD here
// connecting to mysql
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
// selecting database
mysqli_select_db($con,"heart");
// return database handler
return $con;
}
// closing database connection
public function close(){
mysqli_close($this->connect());
}
}
?>
DB_Operations.php:
<?php
class DB_Operations {
private $db;
public $last_id;
public $error;
public $error_conn;
public $error_no;
// constructor
function __construct(){
require 'DB_Connect.php';
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct(){
}
// Storing new doctor
public function storeDoctor($_id,$firstName,$lastName,$specialization,$licenseNumber,$clinicAddress,$email,$contactNum,$username,$password,$aboutMe){
$result = mysqli_query($this->db->connect(),"INSERT INTO doctor(_id,first_name,last_name,specialization,license_number,clinic_address,email,contact_number,username,password,about_me) VALUES('$_id','$firstName','$lastName','$specialization','$licenseNumber','$clinicAddress','$email','$contactNum','$username','$password','$aboutMe')");
if (mysqli_connect_errno()){
$this->error_conn = mysqli_connect_error();
}
if(!$result){
if(mysqli_errno($this->db->connect()) == 1062){
// duplicate key - primary key violation
return true;
} else{
// for other reasons
$this->error = mysqli_error($this->db->connect());
$this->error_no = mysqli_errno($this->db->connect());
return false;
}
} else{
$this->last_id = mysqli_insert_id($this->db->connect());
return true;
}
}
// getters
public function getError(){
return $this->error;
}
public function getError_no(){
return $this->error_no;
}
public function getError_conn(){
return $this->error_conn;
}
...
insertuser.php:
<?php
include 'DB_Operations.php';
// create object for DB_Operations class
$db = new DB_Operations();
// get JSON posted by Android Application
$json = $_POST["doctorsJSON"];
// remove slashes
if(get_magic_quotes_gpc()){
$json = stripslashes($json);
}
// decode JSON into Array
$data = json_decode($json);
// util arrays to create response JSON
$a = array();
$b = array();
// loop through an array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data); $i++){
// store doctor into MySQL DB
$res = $db->storeDoctor($data[$i]->_id,$data[$i]->first_name,$data[$i]->last_name,$data[$i]->specialization,$data[$i]->license_number,$data[$i]->clinic_address,$data[$i]->email,$data[$i]->contact_number,$data[$i]->username,$data[$i]->password,$data[$i]->about_me);
// based on insertion, create JSON response
$b["local_id"] = $data[$i]->_id;
if($res){
$b["server_id"] = $db->last_id;
$b["status"] = 'yes';
}else{
$b["status"] = 'no';
$b["err_no"] = $db->getError_no();
$b["error"] = $db->getError();
$b["error_conn"] = $db->getError_conn();
}
array_push($a,$b);
}
// post JSON response back to Android Application
echo json_encode($a);
?>
I have a function in java which syncs the sqlite data to mysql:
public void syncSQLiteToMySQL(Context context,String selectQuery){
dop = new DatabaseOperations(context);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
ArrayList<HashMap<String,String>> doctorList = new ArrayList<HashMap<String,String>>();
doctorList = dop.getAllDoctors();
if(doctorList.size()!=0){
String json = dop.composeJSONfromSQLite(selectQuery);
params.put("doctorsJSON", json);
Log.i("json to pass", json);
client.post("http://"+ip+":8080/changed_server_name/insertuser.php",params ,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.e("client response",response);
try {
JSONArray arr = new JSONArray(response);
for(int i=0; i<arr.length();i++){
JSONObject obj = (JSONObject)arr.get(i);
// did something with json response here
dop.updateSyncStatus(obj.getString("local_id"),obj.getString("status"));
}
message = "DB Sync completed!";
} catch (JSONException e) {
message = "Error Occured [Server's JSON response might be invalid]!";
Log.e("JSONException",e.getMessage());
}
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
if(statusCode == 404){
message = "Requested resource not found";
}else if(statusCode == 500){
message = "Something went wrong at server end";
}else{
message = "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]";
Log.e("sync post failure",error.toString());
}
}
});
}
}
So, here's the response:
[{"local_id":"0","status":"no","err_no":0,"error":"","error_conn":null}]
The JSON works fine. No problem with it. I have checked and it passes correct data. Just the PHP and MySQL side. Somehow, I couldn't find the error to this code. There is no error message, error number is 0, and there was no error in connecting to DB. But the query in storeDoctor() returns false. How could this be? I have been reading about this problem on this site and others, but I have not really found something that's close to my problem.
Please enlighten me. Your help would really be appreciated. Thanks in advance.
Edit: I also tried mysqli_ping($this->db->connect()); and it returns true which means the connection is okay. So, what really is this something that makes the query fail?
Did you try using error_reporting(E_ALL);
Also inside the constructor you used
$this->db->connect();
And then in the store you used
$result = mysqli_query($this->db->connect(),
Can you post the code for connect
I sending a JSON object from my android app to my web service. (using volley). Here is a part of my code.
private void sendtoDB(final String ngno){
String tag_string_req = "req_save_to_db";
final JSONObject JSONdates = new JSONObject();
for(int i = 0 ; i < dates.size() ; i++){
try{
JSONdates.put("date", dates.get(i));
}catch (Exception e){
e.printStackTrace();
}
}
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_UpdateDates, new Response.Listener<String>() {
#Override
public void onResponse(String response) { ....}
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("ngno", ngno);
params.put("JSON", JSONdates.toString());
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
dates array contains several date Strings that i want to store in my Database. Below is the output of my JSON object (JSONdates).
{"dates":["Wed Mar 30 00:00:00 GMT+05:30 2016","Thu Mar 31 00:00:00 GMT+05:30 2016"]}
My question is how do i receive this JSON object in my php and how to decode it properly and get each date value to a variable so i can execute sql query accordingly.
This is my php code.
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
if(isset($_POST['ngno']) && isset($_POST['JSON']) ){
$ngno = $_POST['ngno'];
$json = json_decode($_POST['JSON'], true);
foreach($json){
$date = $json['date'];
$job = $db->updateDates($ngno, $date);
if($job){
$response["error"] = FALSE;
echo json_encode($response);
}
else{
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in Updating!";
echo json_encode($response);
}
}
}
else{
$response["error"] = TRUE;
$response["error_msg"] = "Dates are missing!";
echo json_encode($response);
}
?>
updateDates function
public function updateDates($ngno, $date){
$stmt = $this->conn->prepare("INSERT INTO datepicker(ngno, date) VALUES($ngno, $date)");
$result = $stmt->execute();
$stmt->close();
}
I get a syntax error near forearch($json) unexcepted ')'.
Any help would be much appreciated.
EDIT 1:
changed the foreach loop in php code as following
foreach($dates as $date){
error_log[$date];
$job = $db->updateDates($ngno, $date);
if($job){
$response["error"] = FALSE;
echo json_encode($response);
}
else{
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in Updating!";
echo json_encode($response);
}
}
But now it says, PHP Warning: Invalid argument supplied for foreach()
Any help Guys? Im new to programming and not sure how to get it fixed.
change foreach($json){ to foreach($json['dates'] as $date){and delete the line $date = $json['date'];. See php manual about foreach for more info about the foreach syntax