0

How the table looksI am coding a function to update the "status" attribute in the "users" table. A status of 1 will mean that the user is online while a status of 0 will mean that the user is offline.

I trying coding a PHP file to set the status to 1 whenever a user logs in.

No matter what, the PHP call returns a 0 telling me that the update query failed to execute. Checked the codes multiple times but I can't seem to locate any errors.

Can somebody help me out?

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

error_reporting(E_ERROR);

try{
	$conn = new mysqli("127.0.0.1", "root", "root", "classads");
	$userID = $_GET['userid'];
  
    $query = "update users set status = 1 where userid = " . $userID;	
	$result = $conn->query($query);

	if (!$result){
		$json_out = "[" . json_encode(array("result"=>0)) . "]";		
	}
	else {
		$json_out = "[" . json_encode(array("result"=>1)) . "]";		
	}

	echo $json_out;

	$conn->close();
}
catch(Exception $e) {
	$json_out =  "[".json_encode(array("result"=>0))."]";
	echo $json_out;
}
?>

enter image description here

4
  • What's the datatype of the userid column? Commented Apr 24, 2016 at 6:57
  • Check you have a connection first php.net/manual/en/function.mysqli-connect.php Commented Apr 24, 2016 at 6:59
  • Hi Rajdeep it's a primary key Commented Apr 24, 2016 at 7:01
  • @Dominic I mean to say, is userid column of type VARCHAR? Commented Apr 24, 2016 at 7:02

1 Answer 1

1

Change your query from

$query = "update users set status = 1 where userid = " . $userID;   

to

$query = "UPDATE users SET status = 1 WHERE userid = '" . $userID . "'";

And later, use ->affected_rows to check whether the UPDATE operation is successful or not.

Here's the reference:

Sign up to request clarification or add additional context in comments.

4 Comments

Affected rows (UPDATE): 0
@Dominic Do echo $userID; after this line $userID = $_GET['userid']; and see what you're getting.
It does echo the userid which I sent as parameter. But still returns a 0
@Dominic There are couple of things you need to debug. First check whether the database connection has established or not, like this: if($mysqli->connect_errno){ echo "connection failed: " . $mysqli->connect_error; }. Then check whether the row status is already set to 1 or not. Make use of mysqli::$error to bebug the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.