I have the following code to connect between mysql database and android.
$conn = mysqli_connect($servername, $username, $password, $database);
//if there is some error connecting to the database
//with die we will stop the further execution by displaying a message causing the error
if ($conn) {
$response["Connection"] = 1;
}
else {
$response["Connection"] = 0;
}
$userID= $_POST['user_id'];
function recordExists() {
$query = "SELECT * FROM user_table";
$result = mysqli_query($conn, $query);
$response["found"] = "i am here";
while($row=mysqli_fetch_array($result)){
$response["found"] = $row['user_id'];
if($row['user_id']==$userID){
return true;
}
}
return false;
// $result_num_rows = mysqli_num_rows($result);
//
// if($result_num_rows>0) {
// return true; // The record(s) do exist
// }
// return false; // No record found
}
$exists=recordExists();
if ($exists) {
$query = "SELECT * FROM user_table WHERE $userID";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array ($result);
$Nickname = array();
if ($row['nickname'] == NULL){
array_push($response["nickname"], "False");
}else{
array_push($response["nickname"], $row["nickname"]);
}
$response["Sync"] = "Already Added";
echo (json_encode($response));
} else {
$UserToBeAdded= $_POST['user_id'];
$NameToBeAdded= $_POST['name'];
$EmailToBeAdded= $_POST['email'];
$UserToBeAdded2 = mysqli_real_escape_string($conn, $UserToBeAdded);
$NameToBeAdded2 = mysqli_real_escape_string($conn, $NameToBeAdded);
$EmailToBeAdded2 = mysqli_real_escape_string($conn, $EmailToBeAdded);
$sql_query = "insert into user_table (user_id, name, email) values ('$UserToBeAdded2', '$NameToBeAdded2', '$EmailToBeAdded2');";
mysqli_query($conn, $sql_query);
$response["ID"] = $UserToBeAdded2;
$response["Name"] = $NameToBeAdded2;
$response["Email"] = $EmailToBeAdded2;
$response["Sync"] = "Just Added";
$response["nickname"] = "False";
echo (json_encode($response));
}
mysqli_close($conn);
from the above code, i can receive responses from the php side. however the following response is not received.
$response["found"] = "i am here";
if u see from my code above, basically the function recordExists() will definitely be called. however the response " i am here" is not encoded in JSON when i emulate the android app. anything wrong?
try to declare the response variable above all functions. so add $response=array();on top of the file.
here you can read up about the scope of php variables:
https://secure.php.net/manual/en/language.variables.scope.php
You have a variable scope issue with the connection variable. Pass the connection variable as a parameter.
recordExists($conn);
Also use prepared statements to prevent sql injection attacks.
Related
I'm retrieving users from my database with this php code below.
The problem is that when I execute the query without the AND condition, it works fine. With the AND condition it gives me always the else result.
include("config.php");
$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$contact = mysqli_real_escape_string($con, $_GET['contact']);
$password = mysqli_real_escape_string($con, $_GET['motdepasse']);
$sql = "SELECT * FROM bonfoodUtilisateurs WHERE contact = '$contact' AND motdepasse = '$password'";
$result = mysqli_query($con,$sql);
$response = array();
if (mysqli_num_rows($result)!=0) {
$response['code'] = '1';
$response['message'] = 'success message.';
echo json_encode($response);
mysqli_close($con);
}else{
$response['code'] = '2';
$response['message'] = 'error message.';
echo json_encode($response);
mysqli_close($con);
}
?>
I'm expecting to get a result like ```{"code":"2","message":"error message."}
if the user's ```contact and ```password don't exist in the data table
otherwise get ```{"code":"1","message":"success message."}
I'm getting this error for the following php code on line 12. I'm trying to insert data into a table and if it succeeds, redirect to another page after alert.
<?php
session_start();
include 'dbconn.php';
$name = $_POST["name"];
$hof = $_POST["hof"];
$tier = $_POST["tier"];
$services = $_POST["services"];
$proced = $_POST["proced"];
$addr = $_POST["addr"];
$phone = $_POST["phone"];
$depname = $_SESSION['depname'];
$qry = "INSERT INTO '.$depname.'(name,hof,tier,services,method,address,phone) VALUES ('$name','$hof','$tier','$services','$proced','$addr','$phone')"; //This is where the problem is;
if(mysqli_query($conn,$qry) === TRUE) {
echo "<script type='text/javascript'>alert('Success');
window.location='welcome.php';
</script>";
}
else{
echo "<script type='text/javascript'>alert('Error');
window.location='welcome.php';
</script>";
}
?>
In addition to what everyone else said this should fix your errors. You will still have security problems that you need to fix.
Also, I don't use mysqli I use PDO so you will have to forgive me if the syntax is slightly wrong.
Your problem is that mysqli_query() doesn't return a row. You need to need to fetch a row from your result and then assign it to $_SESSION['depname']
Login.php should look like this
// Note we are using prepared statements to prevent SQL injections
// Also note the use of backticks `, which are used for identifiers
$mysqli = new mysqli('host', 'user', 'password', 'database');
$stmt = $mysqli->prepare('SELECT `id`,`depname` FROM `admin` WHERE `username` = ? and password = ?');
$stmt->bind_param('ss', $myusername, $mypassword);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows == 1) {
session_start();
$row = $result->fetch_assoc();
$_SESSION['depname'] = $row['depname'];
header("location: welcome.php");
exit;
}
Other Script
<?php
session_start();
include 'dbconn.php';
$name = $_POST["name"];
$hof = $_POST["hof"];
$tier = $_POST["tier"];
$services = $_POST["services"];
$proced = $_POST["proced"];
$addr = $_POST["addr"];
$phone = $_POST["phone"];
$depname = $_SESSION['depname'];
$qry = "INSERT INTO `{$depname}` (`name`,`hof`,`tier`,`services`,`method`,`address`,`phone`) VALUES (?,?,?,?,?,?,?)";
// prepare our query to prevent sql injections
$stmt = $mysqli->prepare($qry);
$stmt->bind_param('sssssss', $name, $hof, $tier, $services, $proced, $addr, $phone);
$stmt->execute();
// not sure why you aren't using header here like #JayBlanchard said, but whatever
if($stmt->affected_rows == 1) {
echo "<script type='text/javascript'>alert('Success');
window.location='welcome.php';
</script>";
}
else
{
echo "<script type='text/javascript'>alert('Error');
window.location='welcome.php';
</script>";
}
im still developing android my android project i really need help, my problem is i couldn't get the user id of the user that login in my system so when they put a record a user id will attached to it data .. i want to do this to output their own data in my system. hope someone could help. its only php code thank you someone who would help.
<?php
// Connection Details altered to hide actual values.
$con = mysqli_connect("localhost", "db_user", "db_password", "db_name");
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM tbl_userinfo WHERE username = '$username' AND password='$password' LIMIT 1";
$res = mysqli_query($con,$sql);
$response = array();
$response["success"] = false;
$row = mysqli_fetch_array($res);
if(mysqli_num_rows($res)> 0){
$response["success"] = true;
session_start();
$_SESSION['user_id'] =$userID;
}
echo json_encode($response);
?>
thats for log in, here's for saving data..
<?php
session_start();
$userID ="";
// Connection Details altered to hide actual values.
$con = mysqli_connect("localhost", "db_user", "db_password", "db_name");
if(!isset($_SESSION['user_id'])){
$userID = $_SESSION['user_id'];
$checkdate = $_POST["checkdate"];
$checkno = $_POST["checkno"];
$datepaid = $_POST["datepaid"];
$clientname = $_POST["clientname"];
$bank = $_POST["bank"];
$amount = $_POST["amount"];
$status = "UNFINISHED";
$statement = mysqli_prepare($con, "INSERT INTO tbl_checkinfo (user_id,checkno, checkdate, datepaid, clientname, bank, amount, status) VALUES (?,?, ?, ?, ?,?,?,?)");
mysqli_stmt_bind_param($statement, "iissssis", $userID, $checkno, $checkdate, $datepaid, $clientname, $bank, $amount, $status);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = false;
if($statement){
$response["success"] = true;
}
echo json_encode($response);
}
?>
and for displaying user data.
<?php
// Connection Details altered to hide actual values.
$con = mysqli_connect("localhost", "db_user", "db_password", "db_name");
$checkdate = $_POST["checkdate"];
$checkno = $_POST["checkno"];
$datepaid = $_POST["datepaid"];
$clientname = $_POST["clientname"];
$bank = $_POST["bank"];
$amount = $_POST["amount"];
$status = "UNFINISHED";
$sql = "Select * from tbl_checkinfo";
$result = mysqli_query($con, $sql);
// $statement = mysqli_prepare($con, "Select * from tbl_checkinfo");
// mysqli_stmt_execute($statement);
// mysqli_stmt_store_result($statement);
// mysqli_stmt_bind_result($statement, $user_id, $checkdate, $checkno, $datepaid, $clientname, $bank, $amount, $status);
$response = array();
$info=array();
$flag = array();
$response["success"] = false;
if( mysqli_num_rows( $result ) > 0 ) {
while($row = mysqli_fetch_array($result))
{
$flag[checkdate]=$row[checkdate];
$flag[checkno]=$row[checkno];
$flag[datepaid]=$row[datepaid];
$flag[clientname]=$row[clientname];
$flag[bank]=$row[bank];
$flag[amount]=$row[amount];
$flag[status]=$row[status];
array_push($info, $flag);
}
$response["success"] = true;
$response["message"] = $info;
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "No entries yet";
echo json_encode($response);
}
?>
Firstly, when posting questions on public forums, please remove your host, DB name, password, etc from the code. :)
Secondly, try to print_r($row) and see on which index is the user id available, then in your code, add this line:
if(mysqli_num_rows($res)> 0){
$response["success"] = true;
$response["user_id"] = $row[USER_ID_INDEX];
session_start();
$_SESSION['user_id'] =$row[USER_ID_INDEX];
}
Where you defined $userID variable, You have to assign proper value to session variable,
if(mysqli_num_rows($res)> 0){
$response["success"] = true;
session_start();
$_SESSION['user_id'] =$row[USER_ID_INDEX];
}
$row['user_id_in_table'] should give you the id.
The following always echoes 'success' even if mname is not found. If it's not found, it should show 'failed'. Why is it showing 'success' when I enter an mname that isn't found?
<?php
$conn = mysqli_connect("localhost","root","","lpdb");
//update
if (isset($_POST['forgot'])){
$password = 'password';
$mname = $_POST['mname'];
$query = "UPDATE logindb SET password ='$mname' WHERE mname = '$mname'";
$result = mysqli_query($conn, $query);
if ($result) {
echo 'success';
} else {
echo 'failed';
}
}
?>
From the documentation:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
An update that doesn't update anything isn't a failure, so the result is TRUE. Use mysqli_affected_rows to find out how many rows were updated by the UPDATE:
<?php
$conn = mysqli_connect("localhost","root","","lpdb");
//update
if (isset($_POST['forgot'])){
$password = 'password';
$mname = $_POST['mname'];
$query = "UPDATE logindb SET password ='$mname' WHERE mname = '$mname'";
mysqli_query($conn, $query); // ***
$result = mysqli_affected_rows($conn); // ***
if ($result > 0) { // *** Or perhaps == 1, up to you
echo 'success';
} else {
echo 'failed';
}
}
?>
firstcheck for mname:
<?php
//check if user submitted first
if (isset($_POST['forgot'])){
$password = 'password';
$mname = $_POST['mname'];
$conn = mysqli_connect("localhost","root","","lpdb");
//update
$query = "UPDATE logindb SET password ='$mname' WHERE mname = '$mname'";
$result = mysqli_query($conn, $query);
if($result){
echo 'success';
} else {
echo 'failed to update for some reason';
//or maybe echo the db err
echo mysqli_error();
}
?
I made a login script which works perfectly except the fact that it logs in even when the username and Password is incorrect.
Here is the code:
<?php
//SQL ENTRY
$username_db = "root";
$password_db = "";
$host = "127.0.0.1";
$db = "teach_login";
//Requested
$usern = $_POST['username'];
$pw = $_POST['password'];
//Make it safe
$usern = htmlspecialchars($usern);
$pw = htmlspecialchars($pw);
$pwmd5 = md5($pw);
//SQL SETTINGS
$db_handle = mysql_connect($host, $username_db, $password_db);
$db_open = mysql_select_db($db, $db_handle);
echo $db_open."<br />";
if ($db_open){
$SQL = "SELECT `username` FROM userpassword WHERE (username = '$usern' && password = '$pwmd5') ";
$result = mysql_query($SQL);
echo $result."<br />";;
if ($result >= 1){
$SQL_name = "SELECT * FROM `userpassword` WHERE (username = '$usern') ";
$result_new = mysql_query($SQL_name);
while($row = mysql_fetch_assoc($result_new)){
$name = $row['full_name'];
echo $name;
echo "<br />";
echo $row['password']."<br>";
$SQL = "UPDATE `userpassword` SET `logged_in`=[1] WHERE `username` = '$usern' ";
$result = mysql_query($SQL);
if ($result > 0){
mysql_close($db_handle);
}else{
echo "Data Not written";
}
}
/*echo $result_new."<br />";
echo $result_name_array."<br />";
$name = $result_name_array[1];
echo $name."<br />";
session_start();
$_SESSION['login_name'] = $name;
$_SESSION['login'] = 1;
mysql_close($db_handle);
//header ("location: teach_home.php");
*/
}else{
echo "Cannot Login";
//header ("location: teach_login.php");
mysql_close($db_handle);
}
}else {
echo ('DATABASE NOT FOUND');
mysql_close($db_handle);
}
?>
The output is this which is the SQL ENTRY:
1<br>
Resource id #4<br>
Salik Sadruddin<br>
14918756cc99b9e6ce69f4c943680efc<br>
Data Not written<br>
This is where the flaw is:
$result = mysql_query($SQL);
if ($result >= 1){
// …
}
The returned value of mysql_query is not the number of selected rows but:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
In your case the query will probably succeed but select no record, however mysql_query will return a resource that will fulfill the expression $result >= 1.
To fix this, use mysql_num_rows to get the number of selected rows:
if ($result && mysql_num_rows($result) === 1){
// …
}
Also consider using MySQLi or PDO_MYSQL instead of standard MySQL extension. An you should also read about SQL injections as your current code is vulnerable.
For update, if UPDATE statement is succeeded $result will give you 0. For Insert it will give you 1
$SQL = "UPDATE `userpassword` SET `logged_in`=[1] WHERE `username` = '$usern' ";
$result = mysql_query($SQL);
if ($result == 0){
echo "Data Updated";
mysql_close($db_handle);
}else{
echo "Data Not written";
}