mysql_fetch_array fails sometimes - mysql

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

Related

Strange behaviour of preg_replace and sql select

preg_match_all('#\<td id=\"(.*)\" class=\"(.*)column(.*)\>(.*)\<\/td\>#i', $htmlcontent, $matches);
$output = $htmlcontent;
foreach ($matches[1] as $match) {
echo $match.",";
$ressql = "SELECT * FROM var WHERE varimportedindex = '".$match."' AND projectid = '".$pid."' AND sheetName = '".$sheetName."'";
$result2 = $db->query("SELECT * FROM var WHERE varimportedindex = '".$match."' AND projectid = '".$pid."' AND sheetName = '".$sheetName."'");
$rowoperation = $result2->fetch_assoc(); //<-- HERE
#echo $rowvalue = $rowoperation['varvalue'];
$output = preg_replace("#\<td id=\"(.*)\" class=\"(.*)column(.*)\>(.*)\<\/td\>#i", "<td id='\\1' class=\"\\2column\\3\"><input type='input' id='\\1' name='\\1' value='".$rowvalue."'>\\4</td>", $output);
}
echo $output;
Ok, i can not find PROBLEM there, but if i deactivate replacement row HERE everything works fine. But when i activate it, replacement is not working anymore.
Can someone find the problem with these lines?
Thank you so much.
Regards,
Olaf
// Olaf, please edit your question to display a sample input value for $htmlcontent
if(!preg_match_all('#\<td id=\"(.*)\" class=\"(.*)column(.*)\>(.*)\<\/td\>#i',$htmlcontent,$matches)){
echo "<div>No match</div>";
}else{
$where_ext=implode("' OR `varimportedindex`='",$matches[1]);
$query="SELECT * FROM `var` WHERE projectid='{$pid}' AND `sheetName`='{$sheetName}' AND (`varimportedindex`='{$where_ext}') ORDER BY varimportedindex;"; // only run one query
if($result=$db->query($query)){
$pattern="#\<td id=\"(.*)\" class=\"(.*)column(.*)\>(.*)\<\/td\>#i";
while($row=$result->fetch_assoc()){
echo "<div>vii={$varimportedindex} & vv={$row["varvalue"]}</div>";
// Olaf, please state what $varvalue's value might be
$replace="<td id='\\1' class=\"\\2column\\3\"><input type='input' id='\\1' name='\\1' value='{$row["varvalue"]}'>\\4</td>";
$output=preg_replace($pattern,$replace,$output);
}
echo "<div>{$output}</div>";
// Olaf, please edit your question to display your expected result based on your sample $htmlcontent
}else{
echo "<div>{$db->error}</div>";
}
}

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

Save SQL result to variable

Is it possible to save SQL result in variable and then use that to echo data anywhere on my site.
for example
$result=mysqli_query("SELECT * FROM table");
and then use that variable to show that data anywhere else on site and even repeat it in some loop
$show=mysqli_fetch_assoc($result)
I tried that in for while loop and it echo my result only once.
my full code
$result=mysqli_query("SELECT * FROM table");
$r=mysqli_query("SELECT * FROM table2");
while($x=mysqli_fetch_assoc($r))
{
echo $x["ID"];
while( $show=mysqli_fetch_assoc($result))
{echo $show["ID"];}
}
Make a $table1_array and a $table2_array and instead of echo $x use $table1_array[] = $x. Since the table2 - select needs nothing from table1 you should read it only once. Make no inner loop, make two separate loops.
EDIT:
to clarify:
$result=mysqli_query("SELECT * FROM table");
$table_array = array();
while( $show=mysqli_fetch_assoc($result)){
$table_array[] = $show;
}
$r=mysqli_query("SELECT * FROM table2");
while($x=mysqli_fetch_assoc($r))
{
echo $x["ID"];
foreach($table_array as $show){
echo $show["ID"];
}
}

how use mysql_data_seek with PDO?

I want use mysql_data_seek with PDO from google search I found that it should looks like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
however it's not work, what I do wrong?
this is my code:
$query = "SELECT name,age FROM users";
$q = $db->prepare($query);
$q->execute();
$q->setFetchMode(PDO::FETCH_ASSOC);
$arrayData = $q->fetchAll();
foreach ($arrayData as $row){
echo $row['name'] ." ";
echo $row['age'] ."<br>";
}
$result = $q->fetch(PDO::FETCH_OBJ,PDO::FETCH_ORI_ABS,4);
var_dump($result);
I just want get the 5th row in object form from the last run query. I don't want run this query again (as some guys told me) I just want the results from sql buffer.
the var_dump result is: bool(false)
any ideas?
EDIT:
thanks for your answers and sorry but maybe I don't explain myself as well. I like the trick with JSON but the point is that the 5th row is example. I just want use the result of the query from the buffer with PDO exactly as I did it with mysql_data_seek in regular mysql (change the cursor). is it possible? I like all the tricks but that not what I look for.
the PDO 'cursor' default is PDO::CURSOR_FWDONLY that means that cursor can't back to zero like it happens with mysql_data_seek to allow cursor back to zero it necessary define use 'scrollable cursor'
example:
$db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
before use it like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
$result = $arrayData[4];
is all you need.
If you want the 5th row result you can do like this:
$result = json_decode(json_encode($arrayData[4]), FALSE);
var_dump($result);
or something like this:
$object = new stdClass();
foreach ($array as $key => $value)
{
$object->$key = $value;
}
Just curious! why do you need the object form?
EDIT (this will give the object form of the 5th row):
$index = 0;
$fifthRow = new stdClass();
while($row = $q->fetch())
{
if($index++==4)
$fifthRow = json_decode(json_encode($row), FALSE);
}
You could do it like this:
$c = 1;
$saved=null;
while($row = $q->fetch()){
if($c==4){
$saved = clone $row;
};
$c++;
somethingelse;
}
$saved will then contain the 4th element as an object with almost no extra overhead calculations.

mysql_affected_rows sometimes returns 0 instead of 1

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.