Replacing PHP condition with row value from database - php

PHP code:
$query = mysqli_query($mysqli, "SELECT * FROM `calculations`") or die(mysqli_error($mysqli));
while($parts = mysqli_fetch_assoc($query))
{
$apples = "yellow";
$a = 1;
$b = 2;
if($parts['part_condition'])
{
echo $parts['part_if_true'] . "<br>";
} else
{
echo $parts['part_if_false'] . "<br>";
}
}
Database:
Please observe my code. I am trying to get the condition from part_condition column and echo results from part_if_true and part_if_false tables, but it does not work. It only returns me values from part_if_true column.
I need this code to create an universal code for a few hundreds of conditions.
Am I getting close by doing this?
For id 1 the result should be:
False
For id 2:
'A is smaller than B'
For id 3:
False
I need to do this in order for the user to edit and create conditions.

Related

Undefined variable array

I get an error on line 15 that says "Undefined variable: row2". How can I resolve this?
$limit = 20;
$res1 = mysql_query('SELECT *
FROM contact
WHERE name = "Greg"');
$res2 = mysql_query('SELECT name
FROM contact c, passport p
ON c.idNum = p.iNum
WHERE date >= "2015-03-03" AND t< "2015-03-21');
if(!$res1 && !$res2) {
die('Query no valid: ' . mysql_error());
}
else {
while(($row1 = mysql_fetch_array($res1)) || ($row2 = mysql_fetch_array($res2))) {
$sub = $row1['num'] - $row2['num'];
if($sub <= $limit) {
echo '<br>row name is: ', $row2['name'];
}
}
}
What I'm trying to do is get a number from the first table (it only results to just Greg's row). Then subtract it with the numbers from the results of the second table. The result of this is placed into the sub variable and it's check to see if it's <= 20. If yes, it prints out the row. If not, it goes back to while loop to check another row. Am I going about the right way so far?
You need to change the while() loop's condition. Consider this example:
$a = 1;
if ($a == 1 || $b = 2) {
var_dump(isset($b));
}
Output of var_dump() will be boolean false because $b does not exist, which is the same case why your $row2 is undefined.
The thing is, while evaluation conditions with ||, PHP will stop evaluating other conditions once the match is found, so other comparisons or assignments on the right side will not be performed.
Change your while to be like this, you need both $row1 and $row2 anyway:
while(($row1 = mysql_fetch_array($res1)) && ($row2 = mysql_fetch_array($res2))) {
(note the && instead of ||)
Also, looks like you may want to use SELECT c.* in your second query, too, because you're only selecting the name column, and trying to use num too.
Note : Select all columns in your 2nd Query if num is already available in your columns so your problem will be solved then.!
Note : Try to replace || with && and you will be good to go.
By using || or OR as in conceptional language as I would say it.You are making the code like in a way that either and only one will pass but if you are passing both ones so then you should replace || with && so that's why your $row2 will be already created then so it will be available for more operation.!
$limit = 20;
$res1 = mysql_query('SELECT *
FROM contact
WHERE name = "Greg"');
$res2 = mysql_query('SELECT *
FROM contact c, passport p
ON c.idNum = p.iNum
WHERE date >= "2015-03-03" AND t< "2015-03-21');
if(!$res1 && !$res2) {
die('Query no valid: ' . mysql_error());
}
else {
while(($row1 = mysql_fetch_array($res1)) && ($row2 = mysql_fetch_array($res2))) {
$sub = $row1['num'] - $row2['num'];
if($sub <= $limit) {
echo '<br>row name is: ', $row2['name'];
}
}
}

Creating a loop that checks several tables and counts the results depending on value

I'm not sure what to do when my if statement is true and how to count each hit.
My code first checks a table to get all the companies that are active.
I then want to go to each table for that company that is active, get the last entry, and count how many values for Status are either not equal to 3(!=3) or equals 2(==2).
I have no problems with this code giving me values from the row for each company but I'm not sure how to count this.
// Get a list of active companies
$sql_companyinfo="SELECT Name FROM Company_Info Where Active=True ORDER BY Name";
$result_companyinfo = mysqli_query($conn, $sql_companyinfo);
// Create variables and Loop for each active Company
while($prop_info = mysqli_fetch_assoc($result_companyinfo)) {
$prop_name = $prop_info["Name"];
$company_table = ("Company_" . "$prop_name");
// Query Table and get the last record added
$result_company = mysqli_query($conn,"SELECT * FROM $company_table WHERE ID=(SELECT MAX(ID) FROM $company_table)");
$row1 = mysqli_fetch_array($result_company);
//Status from Last Row Inserted
$Row_Status = $row1['Status'];
// This is where I get lost. For each company I need to know how many companies where $Row_Status != 3 or == 2
if ($Row_Status != '3') {
// Start with 0 and add 1 for each match
for($n3 = 0; $array[$n3]; $n3++) {
$n3_result = $n3;
}
} elseif ($Row_Status == '2') {
// Start with 0 and add 1 for each match
for($e2 = 0; $array[$e2]; $e2++) {
$e2_result = $e2;
}
{
echo "ERROR: Could not execute";
}
}
}
echo $n3_result;
echo $e2_result;
How to creating a loop that checks several tables and counts the results depending on value?
See you can do like this na:-
$Row_Status = '2';
if ($Row_Status != '3') {
echo 'ok1';
} else {
if ($Row_Status == '2') {
echo 'ok2';
} else {
echo 'ok3';
}
}

PHP Recursion -- Increment query variables

I have a database where each row contains a unique userid number, and a referralid number that links them to the person that referred them to the site. I am trying to create a recursive function that will search the database as long as it continues to find users, and perform several calculations as it goes. Below is what I have so far - I am getting stuck on trying to create incrementing query variables - PLEASE HELP!
function findrepsloop($refidnum, $num){
echo "FINDREPSLOOP STARTED<br><br>";
if(strlen($refidnum) > 0){
echo "FIRST STRLEN IF LOOP PASSED: $refidnum<br><br>";
$totalreps++;
$query{$num} = "SELECT * FROM user WHERE (refidnum = '$refidnum' && active = 'YES') ";
$result{$num} = mysql_query($query{$num});
$line{$num} = mysql_fetch_array($result{$num}, MYSQL_NUM);
$total{$num} = mysql_num_rows($result{$num});
echo "QUERY $num found $total{$num} rows in the database. LINE 0: '$line{$num}[0]<br><br>";
$totaltemp = 0;
if($total{$num} > 2){ $totaltemp = $total{$num} / 3; $totaltemp = floor($totaltemp); }else{}
$numberofthrees = $numberofthrees + $totaltemp;
while(strlen($line{$num}[0]) > 0){
$refidnum = $line{$num}[0];
$num++;
findrepsloop($refidnum, $num);
$line{$num} = mysql_fetch_array($result{$num}, MYSQL_NUM);
}
}else{
}
}

Give another random int if number exists in database (PHP)

I am trying to make a script to check if an int is already added to my database. If so, it will re-generate another random number and check again. If it doesn't exist, it'll insert into the database.
However, I am having troubles. If a number exists, it just prints out num exists, how would I re-loop it to check for another and then insert that? I have tried to use continue;, return true; and so on... Anyway, here is my code; hopefully someone can help me!
<?php
require_once("./inc/config.php");
$mynum = 1; // Note I am purposely setting this to one, so it will always turn true so the do {} while will be initiated.
echo "attempts: ---- ";
$check = $db->query("SELECT * FROM test WHERE num = $mynum")or die($db->error);
if($check->num_rows >= 1) {
do {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')")or die($db->error);
echo "$newnum - CAN INSERT#!#!#";
break;
}
} while(0);
}
?>
I think the logic you're looking for is basically this:
do {
$i = get_random_int();
} while(int_exists($i));
insert_into_db($i);
(It often helps to come up with some functions names to simplify things and understand what's really going on.)
Now just replace the pseudo functions with your code:
do {
$i = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $i")or die($db->error);
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
$db->query("INSERT test (num) VALUES ('$i')") or die($db->error);
Of course, you can do a little more tweaking, by shortening...
// ...
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
...to:
// ...
$int_exists = $newcheck->num_rows >= 1;
} while($int_exists);
(The result of the >= comparison is boolean, and as you can see, you can assign this value to a variable, too, which saves you 4 lines of code.)
Also, if you want to get further ahead, try to replace your database calls with actual, meaningful functions as I did in my first example.
This way, your code will become more readable, compact and reusable. And most important of all, this way you learn more about programming.
The logic is incorrect here. Your do-while loop will get executed only once (as it's an exit-controlled loop) and will stop on the next iteration as the while(0) condition is FALSE.
Try the following instead:
while($check->num_rows >= 1) {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if ($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')") or die($db->error);
echo "$newnum - CAN ISNERT#!#!#";
break;
}
}
Sidenote: As it currently stands, your query is vulnerable to SQL injection and could produce unexpected results. You should always escape user inputs. Have a look at this StackOverflow thread to learn how to prevent SQL injection.
Here is an example of some code that I threw together using some of my previously made scripts. You will notice a few changes compared to your code, but the concept should work just the same. Hope it helps.
In my example I would be pulling the database HOST,USER,PASSWORD and NAME from my included config file
require_once("./inc/config.php");
echo "attempts: ---- ";
$running = true;
while($running == true) {
//create random number from 1-5
$newnum = rand(1,5);
//connect to database
$mysqli = new mysqli(HOST, USER, PASSWORD, NAME);
//define our query
$sql = "SELECT * FROM `test` WHERE `num` = '".$$newnum."'";
//run our query
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//check results, if num_rows >= our number exists
if (mysqli_num_rows($check_res) >= 1){
echo $newnum . " exists! \n";
}
else { //our number does not yet exists in database
$sql = "INSERT INTO `test`(`num`) VALUES ('".$newnum."')";
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
if ($check_res){
echo $newnum . " - CAN ISNERT#!#!#";
// close connection to datbase
mysqli_close($mysqli);
}
else{
echo "failed to enter into database";
// close connection to database
mysqli_close($mysqli);
}
break;
}
}
I would also like to note that this will continue to run if all the numbers have been used, you may want to put in something to track when all numbers have been used, and cause a break to jump out of the loop.
Hope this helps!

Syntax to check if there is data in table according to a condition

I have an MySQL syntax where I return some data for a user. Is any better way of executing the following query, where I just want to know if there is data for user X in category y.
$search_sql = " SELECT id FROM sn_news WHERE id_category = $category AND id_client = $client ";
$search_query = mysql_query($search_sql);
$search_query_result = mysql_fetch_assoc($search_query);
if($search_query_result)
{
$search_result = TRUE;
}
else
{
$search_result = FALSE;
}
I just what to get a TRUE if there is data for my query, or a FALSE if not, to later use that result in a $.post() to know what to print out and what to remove.
Note: I haven't tried the code, but I guess it works
$search_sql = " SELECT id FROM sn_news WHERE id_category = $category AND id_client = $client ";
if ($search_query = mysql_query($search_sql))
{
$search_result=(mysql_num_rows($search_query) ? TRUE : FALSE);
}
or, to actually retrieve the data too
$search_sql = " SELECT id FROM sn_news WHERE id_category = $category AND id_client = $client ";
$search_query_result=array(); // initialise empty return array
if ($search_query = mysql_query($search_sql))
{
switch mysql_num_rows($search_query)
{
case 0:
$search_result=FALSE;
break;
default: // got something
$search_result=TRUE;
while ($row=mysql_fetch_assoc($search_query)
{
$search_query_result[]=$row;
}
break;
}
}
This checks the number of returned rows and sets the variable accordingly using the useful little side effect that a integer value of 0 is equivalent to FALSE.
I would also add some checks to see if the query worked in the first place. It's always useful to check in case you've got a syntax error in your SQL or there's a problem with the server itself (see my code)
mysql_fetch_assoc() returns FALSE when there is no row to fetch. You can check the return value like this:
$search_result = mysql_fetch_assoc($search_query) !== FALSE;
Tell you what, this is essentially the same as what you are doing in your original code.

Categories