I have an issue with ajax response. I am using custom query for fetch result from database. Json response always shows null value while query is running successfully. Here is my code:
if(isset($_POST)){
$arr = array();
//$query = mysql_query(" insert into login (user,pass) values ('".$_POST['firstname']."','".$_POST['lastname']."') ") or die('test');
$query = mysql_query(" select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ") or die('test');
$rows = mysql_num_rows($query);
while($fetch = mysql_fetch_array($query))
{
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
else
{
$arr['failed']= "Login Failed try again....";
}
}
echo json_encode($arr);
}
#Amandhiman i did not get what is the use of if statement with in the while
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
the mention code definitely works for you
if($rows>0)
{
while($fetch = mysql_fetch_array($query))
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
}else
{
$arr['failed']= "Login Failed try again....";
}
Try with the below code, (mysql is deprected), working for me with my test database table (Debug it, var_dump $result, $result->fetch_assoc(), $result->num_rows)
<?php
$servername = "localhsot";
$username = "yourser";
$password = "passyour";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
if(isset($_POST)){
$arr = array();
$query = "select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ";
$result = $conn->query($query);
$rows = $result->num_rows;
while($fetch = $result->fetch_assoc())
{
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
else
{
$arr['failed']= "Login Failed try again....";
}
}
echo json_encode($arr);
}
try this
if(isset($_POST)){
$arr = array();
//$query = mysql_query(" insert into login (user,pass) values ('".$_POST['firstname']."','".$_POST['lastname']."') ") or die('test');
$query = mysql_query(" select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ") or die('test');
$rows = mysql_num_rows($query);
if($rows>0)
{
while($fetch = mysql_fetch_array($query))
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
}else
{
$arr['failed']= "Login Failed try again....";
}
echo json_encode($arr);
}
First of all start session before playing with it on the top of page
session_start();
check your database connectivity.
Use print_r($arr) for testing your array();
first off all you are using session variable . to use session variable you need to initialize it by session_start()
you are using key in the array in this way it will return the last inserted record in the array . try this code
<?php
$servername = "localhsot";
$username = "yourser";
$password = "passyour";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
if(isset($_POST)){
$arr = array();
$query = "select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ";
$result = $conn->query($query);
$rows = $result->num_rows;
while($fetch = $result->fetch_assoc())
{
if($fetch)
{
// if wants to use session then start session
session_start(); // else it will return null
$_SESSION['ID']= $fetch['id']; // i don't know why this ??
// $arr['id'] = $_SESSION['ID']; comment this
$arr[] = array('msg'=>'succsee','ID'=>$fetch['id']);
}
else
{
$arr[]= array('msg'=>'fail','ID'=>null);
}
}
echo json_encode($arr);
}
Related
I'm tring to retrive information from a database while a user send Login command from iOS app.
To test this function i'm launching my php page manually (ex. http://www.testdatabase.com/LoginFunctions.php) and forcing username programmatically.
The problem is that mysqli_query return NULL value. if i use "or die(mysql_error()" nothing happens. Even if i use mysqli_num_rows return 1, but $result is still empty.
So when mysql_fetch_assoc is been executed the programm crashes without showing any error.
Any idea? Thanks
<?php
// Create connection
$con=mysqli_connect("localhost","super","super","testdb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$action = "login";
$username = "Peperoncino";
$response = array();
if ($action == "login")
{
$query = "SELECT psw AS pswrd,id FROM Activities WHERE nome = 'Peperoncino' LIMIT 1";
if ($result = mysqli_query($con, $query))
{
$values = mysql_fetch_assoc($result);
$password = $values['pswrd'];
$response["password"] = $password;
$response["message"] = "Get information from db";
}
else
{
echo "err";
}
echo json_encode($response);
}
// Close connections
mysqli_close($con);
?>
You are using the deprecated mysql_fetch function.Use the new one
<?php
// Create connection
$con=mysqli_connect("localhost","super","super","testdb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$action = "login";
$username = "Peperoncino";
$response = array();
if ($action == "login")
{
$query = "SELECT psw AS pswrd,id FROM Activities WHERE nome = 'Peperoncino' LIMIT 1";
if ($result = mysqli_query($con, $query))
{
$values = mysqli_fetch_assoc($result);
$password = $values['pswrd'];
$response["password"] = $password;
$response["message"] = "Get information from db";
}
else
{
echo mysqli_error($conn);
}
echo json_encode($response);
}
// Close connections
mysqli_close($con);
?>
I have a problem
I want to echo the value of "points" column.
What I tried, but did not work:
$stmt = $mysqli->prepare("SELECT points FROM member_profile WHERE user_id = '$firstName'");
$stmt->execute();
$array = [];
foreach ($stmt->get_result() as $row)
{
$array[] = $row['points'];
}
print_r($array);
THis is my current code:
<?php
header('Content-Type: text/html; charset=Windows-1250');
session_start();
$firstName = $_SESSION['firstname'];
$servername = "db.xxxx.gsp-europe.net";
$username = "xxxxxxxxxxxxx";
$password = "xxxxxxxxxxxxxx";
$dbname = "xxxxxxxx";
/// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// check if the user exist
$check = "SELECT * FROM `member_profile` WHERE user_id = '$firstName'";
$result = mysqli_query($conn,$check) or die(mysqli_error($conn));
$rows = mysqli_num_rows($result);
//if exist increse points with 1
if($rows>=1){
$sql = "UPDATE `member_profile` SET points = points + 1 WHERE user_id = '$firstName'";
if ($conn->query($sql) === TRUE) {
echo "Thingz created successfully";
} else {
echo "Error doing sum thingz: " . $conn->error;
}
}
// if don't exist create user with points 0
if ($rows == 0)
{
$query = "INSERT into `member_profile` (user_id, points) VALUES ( '$firstName' ,'0')";
$result = mysqli_query($conn,$query)or die(mysqli_error($conn));
$conn->close();
}
?>
What I need in the nutshell: In the end of file, will be a "echo" that will show the current value of "points" column with identificator "user_id". Thats all
Thanks for your time, I appreciate it !
You are getting the result, but aren't fetching the datas.
$stmt->get_result() returns a result set -> mysqli_result and to handle this, you need to call the method fetch_array() from that result.
change your code to :
$results = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
$array[] = $row['points'];
}
If you only want 1 result without using arrays, don't use arrays (yes, yes).
$results = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
$points = $row['points'];
}
I am trying to use php to check my database to see if a value exists. My main goal is to use this value
$_GET['UDID']
and if it is equal to any value that is in the database it will return
echo 'FOUND';
I am using this code:
<?php
$servername = "*****";
$username = "*****";
$password = "*****";
$dbname = "*****";
$connect = new mysqli($servername, $username, $password, $dbname);
if ($connect->connect_error) {
die("CONNECTION FAILED: " . $connect->connect_error);
}
$udid = $_GET['UDID'];
$id = mysqli_real_escape_string($connect, $udid);
$result = mysqli_query($connect, "SELECT udid FROM data WHERE udid = '$id'");
if($result === FALSE) {
die("ERROR: " . mysqli_error($result));
}
else {
while ($row = mysqli_fetch_array($result)) {
if($row['udid'] == $udid) {
$results = 'Your device is already registered on our servers.';
$results2 = 'Please click the install button below.';
$button = 'Install';
$buttonlink = 'https://**link here**';
}
else {
$results = 'Your device is not registered on our servers';
$results2 = 'Please click the request access button below.';
$button = 'Request Access';
$buttonlink = 'https://**link here**';
}
}
}
?>
But for some reason it is not working, I am sure I am over looking something. your help is greatly appreciated.
Try this:
$sql = mysqli_query($connect, "SELECT udid FROM data WHERE udid = '" .$udid. "'");
And also, make sure to set the value from 'GET' to $udid. Should be like this:
$udid = $_GET['UDID'];
We can use mysqli_fetch_array() instead to get the result row. I also include error handling. Now your code must look like this :
$udid = $_GET['UDID'];
$id = mysqli_real_escape_string($connect, $udid);
$result = mysqli_query($connect, "SELECT `udid` FROM `wmaystec_WMT-SS`.`data` = '$id'");
if($result === FALSE) {
die(mysqli_error("error message for the user")); //error handling
}
else {
while ($row = mysqli_fetch_array($result)) {
echo "FOUND :" .$row['thefieldnameofUDIDfromyourDB'];
}
}
I would suggest you to first escape the string, using the mysqli_real_escape_string function, and then call the SQL query.
$udid = mysqli_real_escape_string($connect, $udid);
$sql = mysqli_query($connect, "SELECT udid FROM data WHERE udid = '$udid'");
I am new in PHP so I have to apologize for such a dumb question, but I am not sure how to find the right answer. I should check if my final result is empty (if $sql found anything). If it didnt find I would like to get some notification example "The list is empty". That message will also be visible from Android app when I call the url?
<?php
$host = "";
$user = "";
$pwd = "";
$db = "";
$con = mysqli_connect($host, $user, $pwd, $db);
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
// query the application data
$sql = "SELECT * FROM lista WHERE Grad='".$_GET['grad']."' AND Predmet='".$_GET['predmet']."'";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
echo json_encode($rows);
If mysqli_num_rows returns 0, you have no records.
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) == 0) {
$rows = "no rows found";
} else {
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
}
mysqli_close($con);
echo json_encode($rows);
The following code always displays
rows = 0
eventhough the table contains Ravi in the field 'to'. Does anyone know what is wrong with this code?
<?php
$response = array();
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("algopm1",$con);
//if (isset($_POST['to'])) {
$to = "Ravi";
$result = mysql_query("SELECT *FROM `events` WHERE to = '$to'");
if (!empty($result)) {
if (mysql_num_rows($result)>0) {
$result = mysql_fetch_array($result);
echo $result["to"] + " " + $result["from"];
} else {
echo 'rows = 0';
}
} else {
echo 'empty for Ravi';
}
//} else {
//}
?>
to is a reserved word in MySQL, if you want to use it you must encase it in backticks:
.... WHERE `to` = ...
I have not look at your code but I recommend looking at
http://php.net/manual/en/intro.mysql.php
this before you continue to use mysql and not mysqli. It isn't that different but mysqli seems to have a wrapper over mysql and uses the "->" to instantiate new classes for a connection. If that makes any sense.
Try this:
<?php
$response = array();
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("algopm1",$con);
//if (isset($_POST['to'])) {
$to = "Ravi";
$result = mysql_query("SELECT *FROM `events` WHERE `to` = '$to'");
if (!empty($result)) {
if (mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
echo $row["to"] + " " + $row["from"];
} else {
echo 'rows = 0';
}
} else {
echo "empty for $to";
}
//} else {
//}
?>
MYSQLI version + some adjustments:
<?PHP
$host = "localhost";
$user = "root";
$password = "";
$database="algopm1";
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
$query = "SELECT *FROM `events` WHERE `to` = '$to'";
$result = mysqli_query($link, $query);
if (mysql_num_rows($result)>0) {
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo $row["to"]. "+". $row["from"];
}
}
ELSE {
echo 'rows = 0';
}
}
mysqli_close($link);
?>
I would like to credit #njk and #Wezy for their contribution with regard to the reserved word to in mysql. The WHILE loop is not necessary if the table events can only contain one "to" in this case "Ravi". I suspect that the number of events can be greater than one.
#Wezy has a point but let's do the troubleshooting:
As #JonathanRomer in his comment suggested, do:
$result = mysql_query("SELECT *FROM `events` WHERE `to` = '$to'") or die(mysql_error());
What does it say? Does it fail at all?
Or, just before mysql_query do:
die("SELECT *FROM `events` WHERE `to` = '$to'");
this will print faulty query being executed. Next, fire up mysql console or PHPMyAdmin and try executing this query manually.
Again, what does it say?
Actually, my main purpose was to encode this message and receive it on a mobile device by using JSON. This is the full code. For normal checking purpose, instead of using json_encode(*), the values can be displayed individually. This is the solution I got and it is working perfectly for receiving the data in an android app on which I am working.
<?php
$host = "localhost";
$user = "root";
$password = "";
$database="algopm1";
$response = array();
$mysqli = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()){
$response["success"] = 0;
$response["message"] = mysqli_connect_error();
echo json_encode($response);
}
if(isset($_POST['to'])) {
$to = $_POST['to'];
$query = "SELECT *FROM `events` WHERE `to` = '$to'";
if($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->store_result();
$i = 0;
if($stmt->num_rows > 0) {
$stmt->bind_result($rowto, $rowfrom, $rowevent);
$response["events"] = array();
while($stmt->fetch()) {
$events = array();
$events["to"] = $rowto;
$events["from"] = $rowfrom;
$events["event"] = $rowevent;
array_push($response["events"], $events);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No events found";
echo json_encode($response);
}
$stmt->close();
}
} else {
$response["success"] = 0;
$response["message"] = "Required fields are missing";
echo json_encode($response);
}
$mysqli->close();
?>