mysql_affected_rows sometimes returns 0 instead of 1 - mysql

I have a strange problem with php scripts - mysql_affected_rows() sometimes returns "0" for no reason.
There is a similar question #stackoverflow and answer to this question is:
MySQL only actually updates a row if there would be a noticeable difference before and after the updat.
But this is not my case. For example, if value before update is 1320402744 and value after update is 1320402944 mysql_affected_rows() anyway return "0". Is this difference not enough noticable?
Below are 3 files. As you can see, all files include file "functions.inc.php" which calls function "online()".
File "login.php" is working fine. It inserts a new row in "session" table correctly.
File "content.php" is working fine - it displays content and correctly runs function "online() in "functions.inc.php".
Then I call file "test.php". It deletes "something from sometable" correctly. Then it refreshes itself (Header("Location: /test.php");). After refreshing I am logged off.
I added this to "online()" function:
echo "affected_rows";
It returns 0.
I added more code to "online() function:
$checkuser = mysql_query("SELECT userid FROM session WHERE userid = '" . $_SESSION['id'] . "'") or die('Error');
$found = mysql_num_rows($checkuser);
echo $found;
$result = mysql_query("UPDATE session SET time='$ctime' WHERE userid='".$_SESSION['id']."'") or die('Error');
$affected_rows = mysql_affected_rows();
if ($affected_rows != 1) #session_destroy();
echo $affected_rows;
The result is 1 and 0.
I checked the database. "time" field in session table has been updated.
So, I can't understand how is it possible that the row exists, it updates correctly but mysql_affected_rows(); returns 0, and why this happends only if te same page has been refreshed.
functions.inc.php
<?php
#ob_start();#session_start();
#mysql_connect(C_HOST, C_USER, C_PASS) or die('Cant connect');
#mysql_select_db(C_BASE) or die('Cant select DB');
function online() {
$ctime = time()+1800;
if((isset($_SESSION['id']))&&(is_numeric($_SESSION['id']))) {
$query = mysql_query("UPDATE session SET time='$ctime2' WHERE userid='".$_SESSION['id']."'") or die('Error');
$affected_rows = mysql_affected_rows();
if ($affected_rows != 1) #session_destroy();
}
}
//many other functions go here
online();
?>
login.php
<?php
include_once 'configuration.inc.php';
include_once 'functions.inc.php';
//many things go here
$upd = mysql_query("INSERT INTO session VALUES ('" . $i['id'] . "','$ctime')") or die('Error2');
Header("Location: /content.php?justlogged=1");
die;
?>
content.php
<?php
include_once 'configuration.inc.php';
include_once 'functions.inc.php';
//many thing go here
echo "content";
?>
test.php
<?php
include_once 'configuration.inc.php';
include_once 'functions.inc.php';
if (isset($_GET['tid'])&&(is_numeric($_GET['tid']))){
$result = mysql_query("delete from some_table where something = '" . $_GET['tid'] . "'") or die('Error123a');
Header("Location: /test.php");
die;
}
//file content
?>

In your function.inc.php you call online() - session time is changed every second. But can it be that you're switching between pages (login, content, test) more faster than 1 second? In that case time would be the same and you'd get session destroy because of unaffected rows
Edit:
Yes. As I thought.
See how it comes:
you call login.php: after successful login it creates new session with time X. After this you're immediately redirected to content.php (time is still X) which calls online again. And of course, as you redirected immediately - time is the same.. so already at point of content.php session is already destroyed, because time wasn't changed.

Related

How do I reset a MySQL column in a table every year?

I have a column named lv_casual in a table called tbl_employees. I need to reset the column to 0 at a specific date every year.
You can use MySQL event schedule. Providing an example below.
You have to enable the schedular first
SET GLOBAL event_scheduler = ON;
Then create the event
CREATE EVENT your_event_name
ON SCHEDULE EVERY 1 YEAR
STARTS '2021-10-12 00:00:00'
DO
UPDATE table SET column=0;
Check MySQL document for creating event
You can use a cron job to run once per year at end of the year, create a script that will reset all the records on that column to 0.
/usr/local/bin/ea-php99 /home2/accounname/https://example.com/cron_execute_file
okay bro this how your execute file should look like cron_execute_file.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection to db
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE employees SET leaves='12' WHERE leaves >= 0";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
N/B: [#Shaido][1] and any dauche bag thinking of, Please stop editing my answers, just give your own answers, adding fullstops and grammar to my answers to gain budges is a lame thing note this is not a English grammar class. Stay away from my answers, give your own answers. Polite Notice failure to I'll send some visitors to you machines.
[1]: https://stackoverflow.com/users/7579547/shaido

PHP Session Variable Not Passing with Header and Ob_Start Function

This is my code:
<?php
ob_start();
session_start();
include("index.php");
if (isset($_POST['user'],$_POST['pass'])):
$con=mysqli_connect("connect info");
if ( !$con ){
die('Could not connect to Database: '.mysqli_error());}
$pass=($_POST['pass']);
$query0 = "SELECT * FROM user WHERE username = '" . $_POST['user'] ."' AND password = '" . $pass . "'";
$resource0 = mysqli_query($con,$query0);
if(!$resource0):
die("Error conducting query. ".mysqli_error($con));
endif;
if(mysqli_num_rows($resource0) == 0){
echo "Username not find";
header("Location: /login.php");}
$result0 = mysqli_fetch_row($resource0);
$_SESSION['ID'] = $result0[0];
$_SESSION['userType'] = $result0[3];
if(!isset($_SESSION['ID'])):
//header("Location: ...");
else:
header("Location: ....");
endif;
else:
if(isset($_POST['from'])):
$_SESSION['from'] = $_POST['from'];
endif;
?>
<?php endif; ?>
This code takes a user's username and password information and stores and searching the database for the userID. Once is finds the information it stores in the session variable 'ID'.
PROBLEM: When the session 'ID' variable is passed to the next page it is not set. Surprisingly, this code without the ob_start function was working yesterday morning but wasn't working by the afternoon. I know it's not setting because two things: When I echo on the next page, nothing appears and because when I try to run a query with the session 'ID' variable I get a mysql error saying the query could not be conducted.
This is the code on the next page that is not working. At first I thought, it might be something wrong with my query because I was getting this error:
"Error conducting query. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1"
But when I tried printing the session 'ID' variable nothing is printed.
<?php session_start;
// Create connection
$con=mysqli_connect(connect info....);
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query0 = "SELECT * FROM studentProfile WHERE sID = ".$_SESSION['ID'];
$resource0 = mysqli_query($con,$query0);
if(!$resource0):
echo $_SESSION['ID'];
die("Error conducting query. ".mysqli_error($con));
endif;
.......(rest of code)
Solutions Already Tried: I have tried them all...session_write_close(), session_regenerate_id(true), session_commit(), ob_end_flush(). I have tried initially setting the session variable on the home page but once the functions are performed in the session 'ID' variable is no longer set at all.
Please help! I have read all the forums I could find on this problem but nothing seems to work.
what you have written on the next page that your code is not working. Please provide me with detail.
try this on the page which you have directed by header location. May be your session can work.
<?php
include('config.php');
if(!isset($_SESSION['ID']))
{
header("Location: ../index.html");
}
else{
$user_id=$_SESSION['ID'][0];
$user_name=$_SESSION['ID'][1];
?>
and end the else part at the last of the page

MySQL Query not updating database

Perhaps I am just being a complete idiot but I am trying to insert a record into a MySQL table but it doesn't seem to be working. When I test it (i.e. get the script to echo the values so I can check that they are being posted by the form), they are being sent but the query isn't posting to the database. Like I said, perhaps I am being a complete idiot but I felt that perhaps a fresh set of eyes might speed up my troubleshooting because I have been fighting with this issue for the past 2 hours!
Here is the code:
// Connects to your Database
mysql_connect("localhost", "dbuser", "dbpword") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());
// Get Variables
$sectorid = $_POST['sectorid'];
$parentid = $_POST['parentid'];
$sectorname = $_POST['sectorname'];
$status = $_POST['status'];
$creon = $_POST['creon'];
$creby = $_POST['creby'];
$modon = $_POST['modon'];
$modby = $_POST['modby'];
//Insert Record
mysql_query("INSERT INTO cand_emp_sector (sectorid, parentid, sectorname, status, creon, creby, modon, modby)
VALUES ('$sectorid', '$parentid', '$sectorname', '$status', '$creon', '$creby', '$modon', '$modby)");
//On completion, redirect to next page
header("Location: canddb.new.7i.php");
Any assistance would be greatly appreciated.
Thanks
you are missing a quote at the end
, '$modby')");
^---------here
Check the result for errors:
$result = mysql_query("INSERT INTO cand_emp_sector (sectorid, parentid, sectorname, status, creon, creby, modon, modby)
VALUES ('$sectorid', '$parentid', '$sectorname', '$status', '$creon', '$creby', '$modon', '$modby)");
if($result === false) die('query failed..');

mySQL insert HTML form posting problem on results... Need help

I am stumped!! I can't figure this out.
I created an HTML form that inserts a record into mySQL. It works and I can see the new records I add/insert. BUT, I get the wrong confirmation page: I get a the FAIL PAGE instead of the SUCCESS page. I see the new record but I always get taken to the fail page. Why?
Is there something wrong with the script or a setting inside mySQL?
Here is my form post script:
<?
$host="XXXXXXXXXXXX";
$username="XXXXXXXX";
$password="XXXXXXXX";
$db_name="XXXXXXXXX";
$tbl_name="cartons_current";
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$order = "INSERT INTO cartons_current (type, part_no, description, count,
size, min, max, qty)
VALUES
('$_POST[type]', '$_POST[part_no]', '$_POST[description]', '$_POST[count]',
'$_POST[size]', '$_POST[min]', '$_POST[max]', '$_POST[qty]')";
$result = mysql_query($order);
$result = mysql_query($order); //order executes
if ($result) {
$part_no = $_REQUEST['part_no'] ;
header("location: inv_fc_result_new_success.php?part_no=" . urlencode($part_no));
}
else {
header("location: inv_fc_result_new_fail.php");
}
?>
Your code looks OK, except for the possibility that mysql_query() gets called twice. If that is actual code, then I suspect the first call loads the record you are seeing, and the subsequent call returns the error message.
$result = mysql_query($order);
$result = mysql_query($order); //order executes
You appear to be calling mysql_query twice. If it's not a typo in copying the code onto stackoverflow then this could be the issue.
The first call is returning true but second call is returning 'false' hence the fail page is displayed

mysql_fetch_array fails sometimes

I'm trying to implement the connection to a online payment framework.
One of the files is giving me some trouble, because sometimes the code works, sometimes it doesn't... And I can't understand why...
Here's where the code is failing...
$sql = "select transidmerchant,totalamount from nsiapay where transidmerchant='".$order_number."'and trxstatus='Verified'";
$result = mysql_query($sql);
**$checkout = mysql_fetch_array($result);**
echo "sql : ".$sql;
$hasil=$checkout['transidmerchant'];
echo "hasil: ".$hasil;
$amount=$checkout['totalamount'];
echo "amount: ".$amount;
// Custom Field
if (!$hasil) {
echo 'Stop1';
} else {
if ($status=="Success") {}
}
It's just part of the code but I think it's enough for you to try to see the problem... It fails on the bold line, $checkout = mysql_fetch_array($result);
The weird thing is that the "echo sql" works, and it shows the right values, but then when I put them on the array, sometimes the variables are passed, sometimes they're not... And so, when getting to if (!$hasil) it fails because the value is empty... but sometimes it works...
Any ideas on what might be happen?
Thans
Luis
The only way this fail is when query doesn't return anything.
The correct way would be to check if there is something returned:
$sql = "select transidmerchant,totalamount from nsiapay where transidmerchant='".$order_number."'and trxstatus='Verified'";
$result = mysql_query($sql);
if($checkout = mysql_fetch_array($result)){
$hasil = $checkout['transidmerchant'];
echo "hasil: ".$hasil;
$amount=$checkout['totalamount'];
echo "amount: ".$amount;
// Custom Field
if (!$hasil) {
echo 'Stop1';
} else {
if ($status=="Success") {}
}
}else{
echo "Empty query result";
}