retrieve mysql row with php - php

I have been trying to retrieve a row from mysql database with no success. the row that i have been retrieving is only one. here is my code below:
<?php
$email = $_POST["email"];
$usrname = $_POST["username"];
$pass = $_POST["password"];
$code = $_POST["code"];
$status = $_POST["status"];
$userinfo = $_POST["user_info_id"];
$firstname = $_POST["fname"];
$middlename = $_POST["mname"];
$lastname = $_POST["lname"];
$img = $_POST["image"];
require "init.php";
$query = "select * from user where email like '".$email."';";
$result = mysqli_query($con,$query);
if (mysqli_num_rows($result)>0)
{
$response = array();
$code = "reg_false";
$message = "User already exist";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
else
{
$query = "insert into user (email,username,password,code,status,user_info_id) values('".$email."','".$usrname."','".$pass."','".$code."','".$status."','".$userinfo."');";
//$query2 = "insert into userinfo (fname,mname,lname) values('".$firstname."','".$middlename."','".$lastname."');";
$result = mysqli_query($con,$query);
if(!$result)
{
$response = array();
$code = "reg_false";
$message = "Error try again";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
else
{
$query = "select user_info_id from user group by user_info_id DESC limit 1";
$result = mysqli_query($con, $query);
if ($mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["user_info_id"]. " - Name: " . $row["fname"]. " " . $row["lname"]. $row["mname"] . "<br>"; }
}
$query1 = "insert into userinfo (user_info_id,fname,mname,lname) values('".$result."','".$firstname."','".$middlename."','".$lastname."','".$img."');";
$result = mysqli_query($con,$query1);
$response = array();
$code = "reg_false";
$message = "Success";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
}
mysqli_close($con);
?>
The error I was getting was:
Notice: Undefined variable: mysqli_num_rows in C:\xampp\htdocs\loginapp\register.php on line 46
Fatal error: Uncaught Error: Function name must be a string in C:\xampp\htdocs\loginapp\register.php:46 Stack trace: #0 {main} thrown in C:\xampp\htdocs\loginapp\register.php on line 46
I am fairly new to php and mysql.

Please use this query to get num rows.
$query = "select * from user where email like '".$email."';";
$result = mysqli_query($con,$query);
$row_count = mysqli_num_rows($result);
Then use your if conditions like this
if ($row_count>0)
{
$response = array();
$code = "reg_false";
$message = "User already exist";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
else
{
.......

Related

How can I update an exisiting image with MYSQL

I'm trying to update an existing image in my database using mysql query.
This is my edit.php where i edit user info
<?php
require_once "config.php";
if(isset($_GET['edit']))
{
$id = $_GET['edit'];
$res = mysqli_query($link,"SELECT * FROM user_data WHERE id=$id");
$row = mysqli_fetch_array($res);
}
if(isset($_GET['id']))
{
$newText = $_GET['voornaam'];
$newText2 = $_GET['tussenvoegsel'];
$newText3 = $_GET['achternaam'];
$newText4 = $_GET['stemsoort'];
$newText5 = $_GET['adres'];
$newText6 = $_GET['postcode'];
$newText7 = $_GET['plaats'];
$newText8 = $_GET['telefoon'];
$newText9 = $_GET['mobiel'];
$newText10 = $_GET['email'];
$newText11 = $_GET['status'];
$newText12 = $_GET['lid_sinds'];
$newText13 = $_GET['lid_tot'];
$id = $_GET['id'];
$res = mysqli_query($link,"SELECT * FROM user_data WHERE id=$id");
$row = mysqli_fetch_array($res);
$sql = "UPDATE user_data SET voornaam='$newText', tussenvoegsel='$newText2', achternaam='$newText3', stemsoort='$newText4', adres='$newText5', postcode='$newText6', plaats='$newText7', telefoon='$newText8', mobiel='$newText9', email='$newText10', status='$newText11',lid_sinds='$newText12',lid_tot='$newText13' WHERE id=$id";
$res = mysqli_query($link,$sql)
or die("Could not update".mysqli_error($link));
echo "<meta http-equiv='refresh' content='0;url=index.php'>";
}
?>
And this is how I upload images to a folder and then into mysql database
<?php
$msg = "";
$css_class = "";
$conn = mysqli_connect('localhost','root','','test');
if (isset($_POST['save-user'])) {
echo "<pre>", print_r($_FILES['profileImage']['name']),"</pre>";
$bio = $_POST['bio'];
$profileImageName = time() . '_' . $_FILES['profileImage']['name'];
$target = 'images/' . $profileImageName;
if(move_uploaded_file($_FILES["profileImage"]["tmp_name"], $target)) {
$sql = "INSERT INTO users (profile_image, bio) VALUES ('$profileImageName','$bio')";
if (mysqli_query($conn,$sql)) {
$msg = "image uploaded";
$css_class = "alert alert-success";
}else {
$msg = "Database Error: Failed to save user";
$css_class = "alert alert-danger";
}
} else {
$msg = "Failed to upload image";
$css_class = "alert alert-danger";
}
}
?>
How can I combine the two and let a user edit his uploaded profile image? Thanks for helping out

PHP Update Confusion

I am updating MySQL row using the following code. could any one tell me how i can error check the update query and only print Success if the update query was successful without any error? and print failed if update query was not successful!
<?php
//start the session
session_start();
// include db configuration
include('include/db_connect.php');
// user's information
$member_id = $_SESSION['id'];
$member_name = $_SESSION['name'];
$contact_id = $_GET['id'];
// $get_contact = "SELECT * FROM `contacts` where contacts_id = '$contact_id'";
$get_contact = mysqli_query($conn, "SELECT * FROM `contacts` where contacts_id = '$contact_id'");
$row = mysqli_fetch_array($get_contact);
if(isset($_POST['submit'])){
$contact_id = $_POST['contact_id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$cphone = $_POST['cphone'];
$city = $_POST['city'];
$update = "UPDATE `contacts` SET `first_name`='$fname',`last_name`='$lname',`cellphone_number`='$cphone',`city`='$city' WHERE contacts_id = ". $contact_id;
if (mysqli_query($conn, $update)) {
echo "
<script>
var msg = confirm('Contact Updated');
if(msg == true || msg == false){
location.href='update_contact.php?id=$contact_id';
}
</script>
";
} else {
echo "Error: " . $update . "<br>" . mysqli_error($conn);
}
}
?>
My question is this: I'm doing my best to find whats the error and i couldn't what it is. It is for my elective project.
first of all please learn how to use procedure based query to be safe from SQL injection( I am not here to give tutorials on procedure and SQL injection, it is just warning against malicious code) and now your code solution. There was a problem in the way you were concatenating a variable with a string in your query. I have fixed that part for you.
if you still get any error then share what error you are getting and what is the error message.
<?php
//start the session
session_start();
// include db configuration
include('include/db_connect.php');
// user's information
$member_id = $_SESSION['id'];
$member_name = $_SESSION['name'];
$contact_id = $_GET['id'];
$get_contact = mysqli_query($conn, "SELECT * FROM `contacts` where contacts_id = '".$contact_id."'");
$row = mysqli_fetch_array($get_contact);
if(isset($_POST['submit'])){
$contact_id = $_POST['contact_id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$cphone = $_POST['cphone'];
$city = $_POST['city'];
$update = "UPDATE `contacts` SET `first_name`='".$fname."',`last_name`='".$lname."',`cellphone_number`='".$cphone."',`city`='".$city."' WHERE contacts_id = '".$contact_id."'";
if (mysqli_query($conn, $update)) {
echo "
<script>
var msg = confirm('Contact Updated');
if(msg == true || msg == false){
location.href='update_contact.php?id=$contact_id';
}
</script>
";
} else {
echo "Error: " . $update . "<br>" . mysqli_error($conn);
}
}
?>
use this function:
function alertBox($alert_msg, $redirect_link)
{
$alert = '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>';
$alert .= '<script type="text/javascript">alert("'.$alert_msg.'");';
if(!empty($redirect_link)):
$alert .='window.location="'.$redirect_link.'";';
endif;
$alert .='</script>;';
return $alert;
}
// and for calling..
if((mysqli_query($con,$sql))
{
echo alertBox("sucessfull","example.php");
}

Give A Report when Unsuccesfull update database

i'm very new in PHP programming. I have a code for update database value with 2 condition. Here is my code.
<?php
$objConnect = mysql_connect("localhost","root","");
$objDB = mysql_select_db("");
$id = $_REQUEST["id"];
$serial_number = $_REQUEST["serial_number"];
$email = $_REQUEST["email"];
$nama = $_REQUEST["nama"];
$password = $_REQUEST["password"];
/*** Check Email Exists ***/
$strSQL = "SELECT * FROM iot WHERE email = '".$email."' AND id != '".$id."'";
$objQuery = mysql_query($strSQL);
$objResult = mysql_fetch_array($objQuery);
if($objResult)
{
$arr['StatusID'] = "0";
$arr['Error'] = "Email Exists!";
echo json_encode($arr);
exit();
}
/*** Update ***/
$strSQL = " UPDATE iot SET
email = '".$email."'
,nama = '".$nama."'
,password = '".$password."'
WHERE id = '".$id."' AND serial_number = '".$serial_number."'
";
$objQuery = mysqli_query($objConnect,$strSQL);
if(!$objQuery)
{
$arr['Report'] = "Cannot save data!";
}
else
{
$arr['Report'] = "Saved";
}
mysql_close($objConnect);
echo json_encode($arr);
?>
What i want is if one of two condition not meet, then it will show a report " Cannot Save Data".
Sorry for my bad english.
Cheers.

Can't get output of array_push

I'm working on Android apps that showing the output of table in SQL from PHP file, the problem is this PHP file won't show anything in output.
I have tried to find the solution all over Internet but can't find any.
This is the source code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['user_email'];
require_once 'DB_Connect.php';
$db = new DB_Connect();
$response = array();
$sql = ("SELECT * FROM white_list WHERE user_email = '" . $email . "'");
$result = mysqli_query($db->connect(), $sql) or die(mysqli_error());
$no_of_rows = mysqli_num_rows($result);
if ($no_of_rows > 0) {
$response["white_list"] = array();
while ($row = mysqli_fetch_array($result)) {
$white_list = array();
$white_list["name"] = $row["wl_name"];
$white_list["hp"] = $row["wl_hp"];
$white_list["address"] = $row["wl_address"];
$white_list["link"] = $row["wl_link"];
array_push($response["white_list"], $white_list);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Data";
echo json_encode($response);
}
}

PHP Scripts Logs in even when the Login is incorrect

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";
}

Categories