**
I have a problem when updating and deleting, when I incorrectly enter the column id, although the database does not change, the system still reports
success **
$loai = trim($_POST['loai']);
$id = trim($_POST['id']);
$ten = trim($_POST['ten']);
$idghichu = trim($_POST['idghichu']);
$sql;
$conn = new mysqli('localhost','root','12345678','chamcomvantay');
if($loai == "xoa") {
$sql = "DELETE FROM chamcomvantay.tb_bophan WHERE ID='$id' ";
}
elseif ($loai == "sua") {
$sql = "UPDATE chamcomvantay.tb_bophan SET TENBP='$ten', GHICHU='$idghichu' WHERE ID='$id' ";
}
if(mysqli_query($conn, $sql)) {
echo "success"; // This is an error //
} else {
echo "Lỗi";
}
$conn->close();
?>
--my ajax code----
$idbophan = $('#idbophan').val();
$idten = $('#idten').val();
$idghichu = $('#idghichu').val();
$loai = "sua";
if($idbophan.trim() != "" ){
$.post('thaotacbophan.php',{'id':$idbophan.trim(),'ten': $idten.trim(),'idghichu':$idghichu.trim(),'loai':$loai.trim()}, function(data){
alert(data); // error but still alert("success"); ///
});
}
else{
alert("Vui lòng điền đầy đủ thông tin");
}
Related
I need some help on my log out. I try to show less code as possible to avoid long code.
What I'm trying to do is a webpage that allow user to log in and view some stuff. When the user done viewing the stuff, the user are able to log out. When logging out, it'll redirect the user to login page and update my database to clear up all the data such as session_id etc.
But the problem is, whenever the user click the log out button, it'll redirect the user to the login page, but not updating the query which is in the logout function. I'm trying to logs the user out by clearing all the session and data in the database such as session_id, last_log, etc.
Is there any way to make the log out button works?
In my protect class
class protect
{
var $username = "";
var $password = "";
var $id = "";
var $isAdmin = -1;
var $sess_id = "";
var $action = "";
var $query = "";
var $ip_address = "";
var $otp = "";
function __construct()
{
try
{
session_start();
$db = new DB("XXUser","password",DB_NAME);
$db->connect();
$this->check_login($db);
if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin']!=1)
{
$this->logout($db);
}
else
{
if($this->action == "logout")
{
$this->logout($db);
}
$this->check_session($db);
}
}
catch
{
$this->logout($db);
exit();
}
}
function post_value()
{
if (!empty($_POST))
{
foreach ($_POST as $key => $value)
{
$this->$key=$value;
}
}
}
function get_value()
{
if(isset($_GET['action']))
{
$this->action=$_GET['action'];
}
}
function insert_session($db)
{
$sql = "UPDATE myuser SET lastLog = now(), active = 'Y', last_active
= now(), last_access = now(), ip_addr = '".$this->ip_address."',
session_ID = '".trim($this->sess_id)."', fail_login_count = 0,
last_fail_login_time ='1900-01-01 00:00:00', otp =
'".$_SESSION['otp']."' WHERE ID = '".$_SESSION['id']."'";
$db->query($sql);
}
function check_session($db)
{
if(isset($_SESSION['loggedin']) || $_SESSION['loggedin'] == 1)
{
$sql2 = "SELECT * FROM myuser WHERE ID = '".$_SESSION['id']."'
AND otp = '".$_SESSION['otp']."'";
$db->query($sql2);
$db->fetchRow();
if($db->resultCount() == 0)
{
echo "<script type=\"text/javascript\">
alert(\"Access Denied\");
</script>";
session_destroy();
$db->disconnect();
header("Location: login2.php");
exit();
}
else
{
$this->check_time($db);
$this->refresh_session();
}
}
}
function refresh_session()
{
//Regenerate id
session_regenerate_id();
//Regenerate otp
$_SESSION['otp'] = trim(md5(time() .$_SESSION['id']));
}
function check_time($db)
{
$sql3 = "SELECT * FROM myuser WHERE ID = '".$_SESSION['id']."' AND
otp = '".$_SESSION['otp']."' AND last_active > DATE_SUB(NOW(),
INTERVAL 10 MINUTE)";
$db->query($sql3);
if($db->resultCount($db) == 0)
{
$this->logout($db);
}
else
{
$sql2 = "UPDATE myuser SET last_active = now() WHERE ID =
'".$_SESSION['id']."' AND otp = '".$_SESSION['otp']."'";
$db->query($sql2);
}
}
function check_login($db)
{
if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin']!=1)
{
$this->username = sanitize($_POST['username']);
$this->password = $_POST['password'];
$sql = "SELECT * FROM myuser WHERE userName = '".$this-
>username."' AND userPass = '".$this->password."'";
$db->query($sql);
if($db->resultCount() == 0)
{
echo "<script type=\"text/javascript\">
alert(\"Wrong Username or Password\");
</script>";
$db->disconnect();
$db->clear();
}
else
{
$db->fetchRow();
//Correct username but wrong password.
if($db->record['userName'] == $this->username)
{
if($db->record['userPass'] != $this->password)
{
echo "<script type=\"text/javascript\">
alert(\"Wrong Username or Password\");
</script>";
$sql3 = "UPDATE myuser SET ip_addr='".$this-
>ip_address."',fail_login_count=(fail_login_count+1)
WHERE userName='".$this->username."'";
mysql_query($sql3) or die(mysql_error());
}
else
{
$this->id = $db->record['ID'];
$sql4 = "SELECT * FROM subordinate_reporting WHERE
myuser_uid = '".$this->id."'";
$db->query($sql4);
if($db->record['active'] == 'Y')
{
session_destroy();
$db->disconnect();
header("Location: login2.php");
exit();
}
else if($db->resultCount() == 0)
{
echo "<script type=\"text/javascript\">
alert(\"".$db->record['real_name'].", You
are not authorized to access this page\");
</script>";
$db->clear();
}
else
{
echo "<script type=\"text/javascript\">
alert(\"Welcome ".$db-
>record['real_name'].". Your last access was
on ".$db->record['last_access']."\");
</script>";
$this->session($db);
}
}
}
}
}
}
//This function haven't use
function check_attempt($db)
{
$db->query("SELECT fail_login_count, last_fail_login_time FROM
myuser WHERE userName = ".$this->username."");
$db->fetchRow();
if($db->record['fail_login_count'] >= 3)
{
$db->query("UPDATE myuser SET blocked = 'Y',
last_fail_login_time = now()");
echo "<script type=\"text/javascript\">
alert(\"Your account has been blocked for 10 minutes due to
failed login attempts of 3 times\");
</script>";
}
if($db->record['blocked'] === 'Y')
{
if(($db->record['last_fail_login_time'] - time()) > 10)
{
$db->clear();
$db->query("UPDATE myuser SET last_fail_login_time = '1900-
01-01 00:00:00', fail_login_count = 0, blocked = 'N'");
}
else
{
$db->clear();
echo "<script type=\"text/javascript\">
alert(\"Please try again later\");
</script>";
}
}
}
function logout($db)
{
$sql = "UPDATE myuser SET session_ID = '', otp = '', active =
'N', last_active = '1900-01-01 00:00:00', lastLog = '1900-01-01
00:00:00' WHERE ID = ".$_SESSION['id']." AND
otp='".$_SESSION['otp']."'";
$db->query($sql);
echo $sql;
unset ($_SESSION['otp']);
unset ($_SESSION['loggedin']);
unset ($_SESSION['id']);
session_unset();
session_destroy();
$db->clear();
$db->disconnect();
header("Location: login2.php");
exit();
}
function session($db)
{
$_SESSION['loggedin'] = 1;
$_SESSION['id'] = $this->id;
$_SESSION['otp'] = trim(md5(time() .$_SESSION['id']));
$this->ip_address = $this->get_ip();
$this->sess_id = session_id();
$_SESSION['timeout'] = time();
$this->insert_session($db);
}
function logout_btn()
{
echo "<form name='logoutbtn' method='post' action=''>";
echo "\n <input type='hidden' name='action' value='logout'
/>";
echo "<input type='submit' id='button' value='Log Out' />";
echo "\n</form>";
}
function get_ip()
{
if(getenv('HTTP_CLIENT_IP'))
{
$ip = getenv('HTTP_CLIENT_IP');
}
else if(getenv('HTTP_X_FORWARDED_FOR'))
{
$ip = getenv('HTTP_X_FORWARDED_FOR');
}
else
{
$ip = getenv('REMOTE_ADDR');
}
return $ip;
}
}
In my normal html file
<?php
try
{
$prot = new protect();
if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin']!=1)
{
echo "<script type=\"text/javascript\">
alert("Access Denied");
</script>";
}
}
catch (Exception $e)
{
$e->getMessage();
}
?>
<!DOCTYPE html>
<html>
</html>
<head>
</head>
<body>
$ved = new view_exit_docket($db, $_SESSION['id']);
$ved->check_app_uid($db);
$ved->display_table($db);
$prot->logout_btn();
</body>
</html>
If the log out button was not working, then surely you would not have been redirected - this implies that failures are occurring elsewhere.
I will assume that some of the stuff you have edited out of your code is critical to its operation (other wise it would not behave as you describe).
it'll redirect the user to the login page, but not updating the query
From the code you've shown us, the only route to the redirection is through executing the query. If the data was not changed, then the query failed.
1) You didn't tell us anything about the DB class.
2) You don't check the return value from $DB->query() nor poll the state of the operation from $DB after executing the query. If you had, you might have got an error message explaining the problem.
3) You didn't show us the SQL you are running (the most likely place where the fault lies).
4) You have not said what happened to the session data
I am creating a API for android developer in PHP in which he want to delete some values from database and want to show a message after that.
Now the problem is this data is deleting successfully but this API always shows else part message after complete the process. If I remove the else part its return the null which crash the android app. So I just want to give a proper json message to the android developer
Here is the code which I am trying
if($clear_my_property == "yes" && $clear_my_requirement == "yes" && $all_of_these == "yes" && $user_name_id == $user_name_id1)
{
$tables_count = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_count as $table_count)
{
$user_count = mysql_query("select * from $table_count where user_name = '$user_name'");
$total_user_count = mysql_num_rows($user_count);
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
if($user_sql)
{
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
}
}
else
{
$response['success'] = 0;
$response['user']['error_msg'] = 'Record Not Found!';
}
}
}
I know there is something wrong with this logic. But I need expert advise where my logic is wrong and what I have to do make it success
Problem with your original code, is that you are setting success/failure inside the loop. One of the four table may/may not contain the username. And if the last table don't have that, then as per your logic you are getting "record not found" even if previous iteration of the loop deleted data from the tables where username exists.
<?php
$conn = mysqli_connect(.....);
if($clear_my_property == "yes" && $clear_my_requirement == "yes" && $all_of_these == "yes" && $user_name_id == $user_name_id1) {
$tables_count = array("property_for_sale","property_for_rent","cpo_post_requirements");
$userHistoryDeleted = 0;
foreach($tables_count as $table_count) {
//if history is found, then it will be deleted otherwise not
mysql_query("delete from $table_count where user_name = '$user_name'");
if(mysqli_affected_rows($conn)) {
$userHistoryDeleted = 1;
}
}
$msg = 'Record Not Found!';
if($userHistoryDeleted) {
$msg = 'Clear Successfully All History!';
}
$response['success'] = $userHistoryDeleted;
$response['user']['error_msg'] = $msg;
}
Change your code :
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
if($user_sql)
{
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
}
}
else
{
$response['success'] = 0;
$response['user']['error_msg'] = 'Record Not Found!';
}
to this one
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
}
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
I have a PHP login page on a website in the following form:
<?php
$logincorrect = 'notdefined';
$SubmitLogin = 'no';
session_set_cookie_params (3600, $httponly = true);
session_start();
if (isset($_POST['SubmitLogin'])==TRUE)
{
$SubmitLogin = 'yes';
$email = strtolower($_POST['email']);
$passwrd = md5($_POST['nametag']);
}
if($SubmitLogin == 'yes')
{
$link = mysql_connect ('address.website.com', 'restricteduser', 'password_here');
if (!$link)
{
echo '<p style="color:red">* Error: Could not connect to database.</p> ';
}
$email = mysql_real_escape_string(strip_tags($email),$link);
$passwrd = mysql_real_escape_string(strip_tags($passwrd), $link);
$selectDB = mysql_select_db ('database', $link);
if (!$selectDB)
{
echo('<p style="color:red">* Error: Could not select database.</p> ' );
mysql_close($link);
}
$passwrdcheck = mysql_query
(" SELECT * FROM tablename WHERE email = '$email' AND passwrd = '$passwrd'");
if (!$passwrdcheck)
{
echo('<p style="color:red">* Error: Could not search database.</p> ' );
mysql_close($link);
}
if(mysql_num_rows($passwrdcheck) == 0)
{
$logincorrect = 'no';
echo '<p style="color:red">Login details incorrect. Please try again.</p>';
}
else
{
$logincorrect = 'yes';
if($profile = mysql_fetch_array($passwrdcheck));
{
if($profile = mysql_fetch_array($passwrdcheck));
{
$ID = $profile['ID'];
$languages = mysql_query
(" SELECT * FROM translanguages WHERE ID = '$ID' ");
if (!$languages)
{
echo('<p style="color:red">* Error: Could not search database.</p> ' );
mysql_close($link);
}
$expertise = mysql_query
(" SELECT * FROM transexpertise WHERE ID = '$ID' ");
if (!$expertise)
{
echo('<p style="color:red">* Error: Could not search database.</p> ' );
mysql_close($link);
}
$tracking = mysql_query
(" SELECT * FROM transtracking WHERE ID = '$ID' ");
if (!$tracking)
{
echo('<p style="color:red">* Error: Could not search database.</p> ' );
mysql_close($link);
}
if($profile2 = mysql_fetch_array($languages))
{ if($profile3 = mysql_fetch_array($expertise))
{ if($profile4 = mysql_fetch_array($tracking))
{
$_SESSION['profile'] = $profile;
$_SESSION['profile2'] = $profile2;
$_SESSION['profile3'] = $profile3;
$_SESSION['profile4'] = $profile4;
//echo "Login successful. If you are not automatically redirected, please click <a href='profile.php'> here </a>.";
header ("Location: ./profile.php"); exit;
}
}
}
}
}
}
}
?>
This works fine from my PC and my android phone. However, it does not work from my ipad. I have tried chrome and safari on the ipad and the result is the same: when clicking the 'SubmitLogin' button, the login page just appears to refresh instead of connecting to the database and checking the entered information. No error messages are shown.
I have racked my brain for days, but can't work out why this would be. Any ideas? Thanks!
Edit:
The 'directing back to the login page' part of profile.php is as follows:
$loggedin = 'no';
session_set_cookie_params (3600, $httponly = true);
session_start();
if(isset($_SESSION['profile']) AND isset($_SESSION['profile2']) AND isset($_SESSION['profile3']) AND isset($_SESSION['profile4']))
{
$profile = $_SESSION['profile'];
$profile2 = $_SESSION['profile2'];
$profile3 = $_SESSION['profile3'];
$profile4 = $_SESSION['profile4'];
$loggedin = 'yes';
}
else
{
session_destroy();
header ("Location: ./login.php");
exit;
}
Ok, so when I execute the initial function it works fine, the username gets stored in the database, however when I run the second function that appends the username to the text the user chooses to enter the IF statement returns 'no user' - when a user is defined...
If anyone knows how to fix this that would be great - I am currently learning PHP and mysql so I am sorry if any of this is incorrect
<?php
session_start()
// connect to the database
mysql_connect("localhost", "root", "");
mysql_select_db("ajaxchat");
// read the stage
$stage = $_POST['stage'];
// primary code
if($stage == 'initial') {
// check the username
$user = $_POST['user'];
$query = mysql_query("SELECT * FROM chat_active WHERE user='$user'");
if (mysql_num_rows($query) == 0) {
$time = time();
//
mysql_query("INSERT INTO chat_active VALUES ('$user', '$time')");
// set the session
$_SESSION['user'] = $user;
echo 'good';
}
else {
echo 'taken';
}
}
/////////////// PROBLEM FUNCTION ///////////////
================================================
else if($stage == 'send') {
// get the textdomain
$text = $_POST['text'];
// check for user_error
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
echo $user.' - '.$text.'<br />';
}
else {
echo 'no user';
}
}
else {
echo 'error';
}
?>
This is the javascript:
<script type="text/javascript">
function chat_initialise() {
var user = document.getElementById("chat_user").value;
$.post("./chat.php", {stage:"initial", user:user}, function(data) {
if (data == "good") {
$('#initial').css('display', 'none');
$('#content').css('display', 'inline')
}
else {
alert("That username is taken! Please try another.");
}
});
}
function chat_send() {
var text = document.getElementById("chat_text").value;
$.post("./chat.php", {stage:"send", text:text}, function(data) {
document.getElementById("chat_text").value = '';
$('#window').text($('#window').text() + data);
// alert(data)
});
}
</script>
I fixed it - changed the POST function to take the current username then redefine it as a variable in the second function:
else if($stage == 'send') {
// get the textdomain
$text = $_POST['text'];
$user = $_POST['user'];
echo $user;
// check for user_error
if (isset($_SESSION['user'])) {
$_SESSION['user'] = $user;
echo $user.' - '.$text.'<br />';
}
else {
echo 'no user';
var_dump($_SESSION);
}
}
Thanks for all your help guys!!
Ok, so I have this in the top part of my code
require(__DIR__ . "/lib/db.php");
if (!empty($_POST["action"])) {
if ($_POST["action"] == "addCat") {
echo "Please wait...";
$sql1 = "INSERT INTO categories (name) VALUES ('".$_POST["name"]."')";
if (mysql_query($sql1)) {
$success = true;
}
if (!isset($success)) {
echo "Error Occured Adding Category!";
} else {
echo "Category added!";
}
}
if ($_POST["action"] == "delCat") {
echo "Please wait...";
$catNames = $_POST['catName'];
if(empty($catNames)) {
return;
} else {
$N = count($catNames);
for($i=0; $i < $N; $i++) {
$sql = "DELETE FROM categories WHERE id='$catNames[$i]'";
if (mysql_query($sql)) {
$success = true;
}
$sql2 = "SELECT * FROM catrel WHERE categoryID = '$catNames[$i]'";
if (mysql_query($sql2)) {
mysql_query("DELETE FROM catrel WHERE categoryID = '$catNames[$i]'");
}
}
}
if (!isset($success)) {
echo "Could not delete category! Error Occured!";
} else {
echo "Category deleted!";
}
}
}
I have a 2 different forms in the same page, with hidden values that will push addCat or delCat. For some reason it seems like the SQL is not getting parsed, however it is not displaying any errors. Any help would be highly appreciated. I can post the entire page if needed.