php mysql check previous row - php

I have output from a select query as below
id price valid
1000368 69.95 1
1000369 69.94 0
1000370 69.95 0
now in php I am trying to pass the id 1000369 in function. the funciton can execute only if the valid =1 for id 1000368. if it's not 1 then it will throw error. so if the id passed is 1000370, it will check if valid =1 for 1000369.
how can i check this? I think it is logically possible to do but I am not able to code it i tried using foreach but at the end it always checks the last record 1000370 and so it throws error.
regards

Use a boolean variable:
<?php
$lastValid=false;
while($row = mysql_fetch_array($result))
{
if ($lastValid) {
myFunction();
}
$lastValid = $row['valid'];
}
?>
(Excuse possible errors, have no access to a console at the moment.)

If I understand correctly you want to check the if the previous id is valid.
$prev['valid'] = 0;
foreach($input as $i){
if($prev['valid']){
// Execute function
}
$prev = $i;
}

<?php
$sql = "SELECT * FROM tablename";
$qry = mysql_query($sql);
while($row = mysql_fetch_array($qry))
{
if ($row['valid'] == 1)
{
// do some actions
}
}
?>

I really really recommend walking through some tutorials. This is basic stuff man.
Here is how to request a specific record:
//This is to inspect a specific record
$id = '1000369'; //**some specified value**
$sql = "SELECT * FROM data_tbl WHERE id = $id";
$data = mysql_fetch_assoc(mysql_query($sql));
$valid = $data['valid'];
if ($valid == 1)
//Do this
else
//Do that
And here is how to loop through all the records and check each.
//This is to loop through all of it.
$sql = "SELECT * FROM data_tbl";
$res = mysql_query($sql);
$previous_row = null;
while ($row = mysql_fetch_assoc($res))
{
some_action($row, $previous_row);
$previous_row = $row; //At the end of the call the current row becomes the previous one. This way you can refer to it in the next iteration through the loop
}
function some_action($data, $previous_data)
{
if (!empty($previous_data) && $condition_is_met)
{
//Use previous data
$valid = $previous_data['valid'];
}
else
{
//Use data
$valid = $data['valid'];
}
if ($valid == 1)
{
//Do the valid thing
}
else
{
//Do the not valid thing
}
//Do whatever
}
Here are some links to some good tutorials:
http://www.phpfreaks.com/tutorials
http://php.net/manual/en/tutorial.php

Related

Premature End of Script Headers?

I have a problem with the code, it is the premature execution error when using header.
Code:
<?php
session_start();
require 'config.php';
$prepend = "<span class='welcome'>";
$append = "</span>";
if (!isset($_SESSION['name'])) {
header("Location: login.php");
}
echo $prepend."Здравей ".$_SESSION['name'].$append."</br>";
if (isset($_POST['submit']))
{
$newname = mysql_real_escape_string($_POST['newname']);
$newpass = mysql_real_escape_string($_POST['newpass']);
$oldpass = mysql_real_escape_string($_POST['oldpass']);
$checkPass = "SELECT pass from admin WHERE pass = '$_POST[oldpass]'";
$rs = mysqli_query($connect,$checkPass);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if ($data > 0)
{
$query = "UPDATE admin SET pass ='".$_POST['newpass']."',name ='".$_POST['newname']."'" ;
$result = mysqli_query($connect, $query);
if ($result === true)
{
echo "Update sucessfuly!";
}
}
else {
header('Location: admin.php?failed=1');
}
}
?>
The first time when you open the page the else part is performed immediately and I can not understand why.
First you have 2 weird lines in your code:
$rs = mysqli_query($connect,$checkPass);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
Those function don't exist, in fact you probably used the mysql_...() ones, as it seems confirmed by the previous statements.
Now when you execute
$data = mysql_fetch_array($rs, MYSQLI_NUM);
then $data is an array (the next record returned) or FALSE (when no more record exist. And this statement should belong to a loop.
Anyway, in the current form of your code, when you execute if ($data > 0), it can't return anything significative since $data is an array.
So you must refactor all this piece of code according to your need (I guess you want to control that pass was really found by the previous query).
the first time you open page, the else part is executed because the session variables are not set, you need to set session variables first.
$_SESSION['sessionName']= $value;
you must have done this on some other page, if so, then please share the code.
and try using
if(mysqli_num_row($data)>0)
{
$query = "UPDATE admin SET
pass='".$_POST['newpass']."',name='".$_POST['newname']."'" ;
$result = mysqli_query($connect, $query);
if ($result === true)
{
echo "Update sucessfuly!";
}
}
else{
header('Location: admin.php?failed=1');
}
}
?>

PHP $result = mysql_query($query) returns true even if there is no value in database

I have the following code.
$query = "SELECT HealthStatus FROM healthstatus where HealthStatus=$HealthStatus";
$result = mysql_query($query);
echo $HealthStatus;
if($result = false)
{
//do something
}
else
{
//print value already exists
}
I don't get any error or warning when the code is executed. But, even if $HealthStatus exists in database, the if part gets executed. When I give echo $HealthStatus, the value fetched is printed correctly.
I have tried using if(!$result). That doesn't work either. Can someone help me.
You have to use mysql_num_rows to know if the query returned any rows, eg:-
if($result && mysql_num_rows($result))
{
// a row exists
}
else
{
// do something
}
also if HealthStatus is a string it needs to be enclosed in quotes eg:-
$query = "SELECT HealthStatus FROM healthstatus where HealthStatus='".$HealthStatus."'";
$result = mysql_query($query);
if($result && mysql_num_rows($result))
{
// a row exists
$row=mysql_fetch_array($result);
echo "Health status was ".$row["HealthStatus"];
}
else
{
// do something
echo "There were no rows found";
}
To understand how much rows were received use mysql_num_rows function.
if(mysql_num_rows($result) > 0) {
} else {
}
Also, you have error in your if:
if($result = false)
{
//do something
}
else
{
//print value already exists
}
You assign false to $result in your if statement.
You have to use if($result == false).
To avoid such mistakes you can change order:
if(false == $result)
This will work, but this:
if(false = $result)
Will cause error.
Hope, this will help.

PHP MYSQL compare database value to POST value

This is a really simple one, I just can't get my head around it sorry. I have this PHP code which picks up my form value, then compares it with the value stored in the database. That works fine.
However I am not sure how to write this logic in terms of this query:
If posted value = database value {
// do something } else { // do something else }
if (empty($_POST['order_id']) === false) {
// prepare data for inserting
$order_id = htmlentities(trim($_POST['order_id']));
$order_id = preg_replace("/[^0-9]/","", $order_id);
$result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
$row = mysqli_fetch_assoc($result);
echo $row['order_id'];
}
SOLVED:
Solved the question, was a silly one I know! Just needed this at the end of the code:
if($order_id === $row['order_id']) {
echo 'found';
} else {
echo 'not found';
}
Try
If ($result->num_rows === 1) { do something } else { do something else }
Since you did the business logic in your query you can just use
if( ! is_null($row)) {
// do
} else {
// nothing
}
Did I read too much into "If posted value = database value "? Are you just referring to the order_id?
if ($row['listingName'] == $_POST['frm_listingName']) {
// something
}
else {
//something else
}
Check this code:
if (empty($_POST['order_id']) === false) {
// prepare data for inserting
$order_id = htmlentities(trim($_POST['order_id']));
$order_id = preg_replace("/[^0-9]/","", $order_id);
$result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
if(mysqli_num_rows($result)>0)
{
//Match found. do something.
}
else
{
//No match found. do something.
}
}
N.B. In place of mysqli_num_rows($result) you can also use $result->num_rows

While parsing xml/json, skip page if error message received

I have following issue. I am parsing an xml feed with multiple pages and there is no way to understand how many they are (I have a variavle set in the xml url, so for each variable there are random number of pages). All I know is that the number can not exceed 50. Now I have a script that autoincrement the variable for the page number starting at 1 and up to 50.
Let's say, that the link has total of 26 pages. With my script I will continue to send requests until the scripts gets to page 50. Than it changes the first variable and starts again from 1 to 50. For the first link, from page 27 forward the xml will return followwing:
<response>
<status>error</status>
<code>400</code>
<message>Incorrect Request Headers</message>
</response>
How can I make so when the scipt receive this message, to stop the autoincrement and continue by changing the first variable and start again at 1? The code now is:
$query = "SELECT * FROM table_name ORDER BY id ASC";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
if($row['row_name'] == '') {
$variable1 = 0;
}
else {
$variable1 = $row['row_name'];
}
$page = 0;
do {
$page++;
$result = apiCall('option1', 'option2', array('option3' => $variable1, 'page' => $page));
usleep(1000);
$res = json_decode($result);
foreach ($res->node1->node2 as $item) {
//define variable for insertion in MySQL
$sql1 to insert the variables
if (!mysql_query($sql1,$con1))
{
die('Error: ' . mysql_error());
}
}
}
while ($page<=50);
}
In the above code, only the $variable1 and $page are variables. All options (1, 2 and 3) are predefined and stay the same. I.e. I need when the script gets the error message to start again from 1 with next value of $variable1.
OK. Here is the code I played around:
$query = "SELECT * FROM table_name ORDER BY id ASC";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
if($row['row_name'] == '') {
$variable1 = 0;
}
else {
$variable1 = $row['row_name'];
}
$page = 1;
do {
$result = apiCall('option1', 'option2', array('option3' => $variable1, 'page' => $page));
usleep(1000);
$res = json_decode($result);
if ($res->status == 'error') {
break 2;
}
foreach ($res->node1->node2 as $item) {
//define variable for insertion in MySQL
$sql1 to insert the variables
if (!mysql_query($sql1,$con1))
{
die('Error: ' . mysql_error());
}
}
$page++;
}
while (0);
}
The problem is that it stops the script execution at some point. Can not understand why.

php if else statement within a select box

I am working on a piece that allows user to create an article, but there are some restricted for an admin, which i identify as SgroupId 1. Now when I log in with my admin code, i realize i still cant post everything, except for what I identified in loadTypeUsers. I know i get the value of Sgroup1 with me, since the admin panel loads in the bar below. Also when I echo the value I get the return of 1, which should be fine.
But when I try to load the dropdown in my popup, it wont give me the full list. Instead, it loads just the list I specified in the LoadTypeUsers. Can somebody help me out here?
Thanks in advance.
~Dorv
function MakeArticleTypeDropdown(){
echo "<select name='ArticleTypeId'>";
if($SgroupId == 1 || $SgroupId == 1){
$results = LoadType();
}
else
{
$results = LoadTypeUsers();
}
while($row = mysql_fetch_array($results)){
echo "<option value='".$row['ArticleTypeId']."'>"
.$row['ArticleTypeName']."</option>";
}
echo "</select>";
}
This is tucked in the ArticleFunction.php file
function LoadTypeUsers(){
$query = "SELECT * FROM Articletype limit 1,3;";
$resultaat=SendQuery($query);
return $resultaat;
}
function LoadType(){
$query = "SELECT * FROM Articletype;";
$resultaat=SendQuery($query);
return $resultaat;
}
This is tucked in the Sentry.php file
session_start();
$UserName = $_SESSION['username'];
$result = mysql_query("select * from user where username='".$UserName."'");
while($row = mysql_fetch_array($result)){
$UserId = $row['UserId'];
$CharacterName = $row['CharacterName'];
$UserName = $row['UserName'];
$SgroupId = $row['SgroupId'];
};
$SgroupId is not defined in the function MakeArticleTypeDropdown() so it will always goes in else condition .Try something as follows
MakeArticleTypeDropdown($SgroupId)
{
//-----------your code
}
first of all, I don't see you passing the value of $SgroupId to MakeArticleTypeDropdown(). Maybe you have an scope problem and you're checking a variable $SgroupId that isn't set inside the function?
second: ($SgroupId == 1 || $SgroupId == 1) What is that || for?
I think that the LIMIT clause should be a WHERE clause.
i.e.
SELECT * FROM Articletype WHERE SgroupId = 1 OR SgroupId = 3
and perhaps the line
if($SgroupId == 1 || $SgroupId == 1){
should read
if($SgroupId == 1 || $SgroupId == 3){

Categories