Give A Report when Unsuccesfull update database - php

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.

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

Getting the ID of the other user along with its information inside database,

I am having a problem on how to get the id of the selected user along with it's information while I am logged in as an another user, using mysql, the two tables is innerjoined with each other I just dont know how to get the ID of other user, and passing it on other database
if(isset($_POST['send']))
{
$query = "SELECT * FROM tblmessage INNER JOIN tblusers ON tblmessage.userid=tblusers.userid";
$res = mysqli_query($con,$query);
while ($row = mysqli_fetch_assoc($res))
{
$receiverID = $row['userid'];
}
$sender = $_SESSION['Email'];
$receiver = $_POST['email'];
$message = $_POST['textmessages'];
$date = date("Y-m-d h:i:sa");
$q = 'INSERT INTO `tblmessage`(`id`,`sender_name`,`receiver_name`,`receiver_id`,`message_text`,`date_time`,`userid`)
VALUES("","'.$sender.'","'.$receiver.'","'.$receiverID.'","'.$message.'","'.$date.'","'.$user_id.'")';
$r = mysqli_query($con, $q);
if($r)
{
echo"<script>alert('Message Sent')</script>
<script>window.location.href='messages.php?id=$receiverID';</script>";
}
else
{
echo $q;
}
}

MySql update query not updating data

I have a simple query which updates the last time a user logs in. For some reason, it is not updating the data when a user logs in. I would be grateful if someone could point out my error. Thanks
<?php
session_start();
$message="";
if(count($_POST)>0) {
$username_usr = $_POST["user_name"];
$password_usr = md5($_POST['password']);
$conn = mysql_connect("localhost","root","");
mysql_select_db("logistor_logistor",$conn);
$result = mysql_query("SELECT * FROM user_usr WHERE username_usr='" . $username_usr . "' and password_usr = '". $password_usr ."'");
$row = mysql_fetch_array($result);
if(is_array($row)) {
$_SESSION["username"] = $row[username_usr];
$_SESSION["password"] = $row[password_usr];
$_SESSION["S_name"] = $row[name_usr];
} else {
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["username"])) {
$query = "UPDATE user_usr SET logincounter_usr = logincounter_usr+1, lastlogin_usr = NOW() WHERE username_usr = '". $_SESSION["username"] ."'";
header("Location:user_dashboard.php");
}
?>
you miss execute the query in update
$query = "UPDATE user_usr SET logincounter_usr = logincounter_usr+1, lastlogin_usr = NOW() WHERE username_usr = '". $_SESSION["username"] ."'";
$result = mysql_query($query);

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

Getting a blank page with PHP&MySQL

I'm getting a blank page with this code:
session_start();
include "config.php";
$af = $_GET['id'];
database_connect();
$query2 = "SELECT * FROM friends WHERE usr1 = '".$id."' AND usr2 = '".$af."'";
$result2 = mysql_query($query2) or die(mysql_error());
while ($row2 = mysql_fetch_assoc($result2)) {
if($row2['id']){
echo "<script type='javascript'>alert('You are already friends with this person.');</script>";
header('Location: profile.php?id="'.$af.'"');
}else{
mysql_query("INSERT INTO friends (usr1, usr2)
VALUES ('".$id."', '".$af."')") or die(mysql_error());
echo "<script type='javascript'>alert('You two are friends now!');</script>";
header('Location: profile.php?id="'.$af.'"');
};
};
This is the config.php (i changed the variables here though)
$h = "localhost";
$u = "user";
$p = "pass";
$d = "datab";
$sql = 'SELECT id FROM craffyposts limit '.($page*$eachPage).','.$eachPage;
$sql_count = 'SELECT id FROM craffyposts';
function database_connect(){
global $h, $d, $u, $p;
$link = #mysql_connect("$h","$u","$p");
$sql_error = mysql_error();
if (!$link) {
echo "Connection with the database couldn't be made.<br>";
echo "$sql_error";
exit;
}
if (!#mysql_select_db("$d")) {;
echo "The database couldn't be selected.";
exit;
}
return $link;
}
if($_SESSION['usrid']){
database_connect();
$query = mysql_query("SELECT * FROM craffyusers WHERE id='" .$_SESSION['usrid']. "' ") or die (mysql_error());
while ($obj = mysql_fetch_object($query)) {
$id = htmlspecialchars($obj->id);
$username = htmlspecialchars($obj->username);
$email = htmlspecialchars($obj->email);
$realname = htmlspecialchars($obj->name);
$srvrid = htmlspecialchars($obj->serverid);
$propic = htmlspecialchars($obj->profilepic);
};
};
What's the issue here?
because there will 0 or 1 result, you can remove the while clause:
$row2 = mysql_fetch_assoc($result2);
if($row2 && $row2['id']){
echo "<script type='javascript'>alert('You are already friends with this person.');</script>";
header('Location: profile.php?id="'.$af.'"');
}else{
mysql_query("INSERT INTO friends (usr1, usr2)
VALUES ('".$id."', '".$af."')") or die(mysql_error());
echo "<script type='javascript'>alert('You two are friends now!');</script>";
header('Location: profile.php?id="'.$af.'"');
};
Add this lines at the beginning of the script
error_reporting(E_ALL);
ini_set("display_errors", 1);
The error will appear.

Categories