adding further conditions to mysql loop - php

<?php
$query = $_GET['query'];
// gets value sent over search form
$min_length = 6;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM cwnational WHERE (`postcode` = '$query') OR (`structure` LIKE '%".$query."%')") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
echo "<p><h3>".$results['postcode']."</h3>".$results['structure']."</p>";
}
while($results = mysql_fetch_array($raw_results)){
if($results['structure'] = "National") {
echo "print national_table";
} else {
echo "print local_table";
}
}
else{ // if there is no matching rows do following
echo "No results";
}
}
else{ // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
?>
</body>
I'm totally stumped now..
When I successfully match a $query, I want to use the 2nd part of the array which should be a column called structure and use that as a switch to either print table_local or table_national from the db.
re-wrote it after getting to grips with the correct approach,
if (empty($searchTerm)) {
echo "<h1>Empty search term</h1>";
$sqlQuery = false;
} elseif (strlen($searchTerm) < $minQueryLength) {
echo "<h1>Search term must be at least ".$minQueryLength." characters long.";
$sqlQuery = false;
} else {
if (strlen($firstPart) + strlen($secondPart) == 7) {
$sqlQuery = $mysqli->query("SELECT `postcode`, `structure` FROM `cwnational` WHERE `postcode` LIKE '".$firstPart." ".$secondPart."'");
} else {
$sqlQuery = $mysqli->query("SELECT `postcode`, `structure` FROM `cwnational` WHERE REPLACE(`postcode`, ' ', '') LIKE '".$searchTerm."%'");
}
}
if (is_object($sqlQuery) && $sqlQuery->num_rows >= 1) {
$resultArr = array();
while($row = $sqlQuery->fetch_assoc()) {
$resultArr[$row['postcode']] = array();
$priceQuery = $mysqli->query("SELECT `base_rate`, `commit_mbps` FROM `pricing` WHERE `structure` = '".$row['structure']."'");
if ($priceQuery->num_rows >= 1) {
while ($price = $priceQuery->fetch_assoc()) {
$resultArr[$row['postcode']][$price['commit_mbps']] = ((float)$price['base_rate'] + $transit[$price['commit_mbps']] ) + ( ( $transit[$price['commit_mbps']] + (float)$price['base_rate'] ) * ((float)$apiUser['margin']/100) ) ;
}
}
}

You're reading the result set twice. This will work for the first loop, but won't execute the second because you've already reached the end. If you need to read the results twice, use this:
mysql_data_seek ($raw_results , 0 )
immediately before the second loop to set the pointer to the beginning again.
Of course, you should be using mysqli...

what's going wrong now? I see you need to add an equals sign here:
if($results['structure'] == "National") {
note: double equals for php conditional
It also looks like you have an "else" coming out of a "while", that won't work. And you did this "while" loop twice, I'd combine them into a single "While":
while($results = mysql_fetch_array($raw_results)){

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'];
}
}
}

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{
}
}

Date comparison inside a "for loop" in php

I have a set of rows with five fields. My requirement is if "Internal_Deadline" field is greater than "Client_Deadline" in any of the rows, then it has to display a alert saying "Internal Deadline should not be greater than Client Deadline". Now it's checking only with the first row. I need to check with all the rows. Thanks
<?php
for( $i = 1; $i <= 100; $i++ )
{
$task = $_POST['task'.$i];
$Description = $_POST['Description'.$i];
$Internal_Deadline = $_POST['Internal_Deadline'.$i];
$Client_Deadline = $_POST['Client_Deadline'.$i];
$Actual_Deadline = $_POST['Actual_Deadline'.$i];
if(strtotime($Internal_Deadline) > strtotime($Client_Deadline)){
?>
<script>alert('Internal Deadline should not be greater than Client Deadline');</script>
<?php
}
else{
$result_task=mysql_query("select * from project_plan where p_id='$p_id' and task_no='$i'", $dbconnect1);
$row_task=mysql_fetch_array($result_task);
$id=$row_task['id'];
if(mysql_num_rows($result_task)!=0){
$update_result=mysql_query("update project_plan set Task='$task',Description='$Description',Internal_Deadline='$Internal_Deadline',Client_Deadline='$Client_Deadline',Actual_Deadline='$Actual_Deadline' where id='$id'", $dbconnect1);
}
else{
if($task!=""){
$que = mysql_query("insert INTO project_plan(task_no,Task,Description,Internal_Deadline,Client_Deadline,Actual_Deadline,Created_Date,p_id) VALUES ('".$i."','".$task."','".$Description."','".$Internal_Deadline."','".$Client_Deadline."','".$Actual_Deadline."','".$current_date."','".$p_id."')", $dbconnect1);
}
}
}
}
First of all the length of your for loop is not correct.
You need to run this loop exact same times to the post data count.
secondly i have tried locally with your given data(in your comment). it seems that is not met the condition:
if(strtotime($Internal_Deadline) > strtotime($Client_Deadline)){
try like this:
it will skip unnecessary loops. if you have task1,task2,task3 set in post data then it will run for 3 times not 100 times as your implementation.
$i=1;
while(isset($_POST['task'.$i]))
{
$task = $_POST['task'.$i];
$Description = $_POST['Description'.$i];
$Internal_Deadline = $_POST['Internal_Deadline'.$i];
$Client_Deadline = $_POST['Client_Deadline'.$i];
$Actual_Deadline = $_POST['Actual_Deadline'.$i];
if(strtotime($Internal_Deadline) > strtotime($Client_Deadline)){
?>
<script>alert('Internal Deadline should not be greater than Client Deadline');</script>
<?php
}
else{
$result_task=mysql_query("select * from project_plan where p_id='$p_id' and task_no='$i'", $dbconnect1);
$row_task=mysql_fetch_array($result_task);
$id=$row_task['id'];
if(mysql_num_rows($result_task)!=0){
$update_result=mysql_query("update project_plan set Task='$task',Description='$Description',Internal_Deadline='$Internal_Deadline',Client_Deadline='$Client_Deadline',Actual_Deadline='$Actual_Deadline' where id='$id'", $dbconnect1);
}
else{
if($task!=""){
$que = mysql_query("insert INTO project_plan(task_no,Task,Description,Internal_Deadline,Client_Deadline,Actual_Deadline,Created_Date,p_id) VALUES ('".$i."','".$task."','".$Description."','".$Internal_Deadline."','".$Client_Deadline."','".$Actual_Deadline."','".$current_date."','".$p_id."')", $dbconnect1);
}
}
}
$i =$i +1;
}

Two elements but only one inserted into database (even in a loop)

for ($i = 0; $i < count($cart); $i++) {
$proid = $cart[$i]["proid"]; //1
$prodName = $cart[$i]["prod_name"]; //2
$price = $cart[$i]["unit_price"]; //3
$taken = $cart[$i]["taken"]; //4
if ($cart[$i]['taken'] > 0) {
$sql = "INSERT INTO `tblchitiethoadon`(`Ma_HD`, `Ma_SP`, `Ten_SP`, `SoLuong`, `Gia`)";
$sql.=" VALUES ({$mahd},{$proid},'{$prodName}',{$taken},{$price})";
$result = mysql_query($sql);
/* $mahd i got it before */
}
}
I got 3 elements in array $cart,2 of them got cart[$i]['taken'] > 0 (i also echo $cart with $cart[$i]['taken'] > 0 condition for sure ) but in the database i just got the first and only one element.
Typo/Syntax Error
$sql.=" VALUES ({$mahd},{$proid},'{$prodName}',{$taken},{$price})";
----------------------------------------------------------------------------------------------------------^(semicolon missing)
correct:
$sql.=" VALUES ({$mahd},{$proid},'{$prodName}',{$taken},{$price});";
-----------------------------------------------------------------------------------------------------------^
Reason:
Since you are using for loop to form the query.your query will look like
insert into table1(a,b,c) values(1,1,1)insert into table1(a,b,c) values(2,3,4)
which is wrong syntactically.
see here
you can echo your $sql and run it in phpmyadmin
Better Approach:
The better approach to your code(it will reduce the unwanted overhead,form the string inside the loop and execute it outside the loop):
$sql1 = "INSERT INTO `tblchitiethoadon`
(`Ma_HD`, `Ma_SP`, `Ten_SP`, `SoLuong`, `Gia`) VALUES";
for ($i = 0; $i < count($cart); $i++) {
$proid = $cart[$i]["proid"]; //1
$prodName = $cart[$i]["prod_name"]; //2
$price = $cart[$i]["unit_price"]; //3
$taken = $cart[$i]["taken"]; //4
if ($cart[$i]['taken'] > 0) {
$sql11.=" ({$mahd},{$proid},'{$prodName}',{$taken},{$price}),";
}
}
$sql=$sql1.$sql11;
$sql=trim($sql,",");//to remove the extra semicolon at the end of the string.
$result = mysql_query($sql);
Please Dont use mysql_* as these are depracated and you are prone to sql injections.
Loop will execute count($cart) times and the insertion action will occure if ($cart[$i]['taken'] > 0) is true.Make sure the condition is true for each time.
Try these this coding:
$sql = "INSERT INTO tblchitiethoadon (Ma_HD, Ma_SP, Ten_SP, SoLuong, Gia) VALUES ('$mahd','$proid','$prodName','$taken','$price')";
$result = mysql_query($sql);

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!

Categories