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'];
}
}
}
Related
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.
staff table
code
<?php
//db configuration
$q = "select * from staff";
$r = mysqli_query($dbc, $q);
$num_rows = mysqli_num_rows($r);
$staffID = array();
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$staffID[] = $row['staffID'];
}
for($i = 0; $i < $num_rows; $i++)
{
if($staffID[$i] == $staffID[$i+1])
{
$remark = "Not OK. Multiple staff ID selected.";
$i++;
}
else
{
$remark = "OK.";
}
$data[$i] = $staffID[$i].','.$remark.'<br />';
}
$list = array($data);
print_r($list);
?>
From above code, I want to check whether the staffID got duplicate.
Expected output
0001, OK.
0002, Not OK. Multiple staffID.
0003, OK.
0004, OK.
However, I get another error as below:
Undefined offset: 5 in play.php on line X.
How do I solve it?
By performing the correct query in the first place.
SELECT staffID
FROM staff
GROUP BY staffID
HAVING COUNT(staffID) > 1
Or if you need to know about all staff IDs:
SELECT staffID, COUNT(staffID) as qty
FROM staff
GROUP BY staffID
Just updating your code and i think you have to check the existence first :
if (isset($staffID[$i]) && isset($staffID[$i+!])) {
if($staffID[$i] == $staffID[$i+1])
{
$remark = "Not OK. Multiple staff ID selected.";
$i++;
}
else
{
$remark = "OK.";
}
$data[$i] = $staffID[$i].','.$remark.'<br />';
}
You get the error at this line:
if($staffID[$i] == $staffID[$i+1])
Say for example your $num_rows variable is 3. Then the $staffID array would have indexes 0, 1 and 2. But what happens at this line I noted is that once $i reaches 2 (which is a valid since it's less than 3) you go and do $i+1 which equals 3. And, as you can see, the index 3 is out of the bounds of the array.
If you wish to do this like you wrote your for loop should be like this:
for($i = 0; $i < $num_rows-1; $i++)
But, there is a better way without even doing the for loop. You can do it all in the while loop by making use of the in_array function. Or as Ignacio pointed out, you could do it all on the SQL level.
Not a good way to solve this problem. You should use GROUP BY query for this.
SELECT staffID, COUNT(staffID) as count
FROM staff
GROUP BY staffID
HAVING count > 1
And also about your error. It's because of
if($staffID[$i] == $staffID[$i+1])
on last iteration $i is equal 4 and $i+1 is 5. But $staffID array has no element with such key
I want the program to ignore zero totals. I'm trying to stop auto awards to non-participants with zero totals. I added the >= expression after the && operators. Is this correct for kills and networth?
$fetch_nor_killers = mysql_query("SELECT wk,bk,hk,dk,pk,mk, code, p, (wk+bk+hk+dk+pk+mk) as totalKills FROM r$round[round]_p WHERE status = '". normal ."' ORDER BY totalKills DESC LIMIT 3");
$killa_rank = 0;
while($killa = mysql_fetch_array($fetch_nor_killers))
{
$killa_rank++;
if($killa_rank == 1 && $killa['totalKills'] >= 1)
{
$killa_award = "freeopkiller1";
}
else
if($killa_rank == 2 && $killa['totalKills'] >= 1)
{
$killa_award = "freeopkiller2";
}
else
if($killa_rank == 3 && $killa['totalKills'] >= 1)
{
$killa_award = "freeopkiller3";
}
Same thing here with networth. Just trying to avoid awarding a inactivate user. #Jagrut
$fetch_top_subs = mysql_query("SELECT * FROM r$round[round]_p WHERE subscription != '". none ."' ORDER BY networth DESC LIMIT 3");
$sub_rank = 0;
while($sub = mysql_fetch_array($fetch_top_subs))
{
$sub_rank++;
if($sub_rank == 1 && $sub_rank['networth'] >= 1)
{
$sub_award = "first_sub";
}
else
if($sub_rank == 2 && $sub_rank['networth'] >= 1)
{
$sub_award = "second_sub";
}
About to test these.
First, i would like you to be more clear with the question. But from what i have understood, this can be the problem with your code:
You are using the $totalKills directly. You can either assign it to a variable and then use it or you need to use $killa for accessing $totalKills, i.e.
Use it as:
$anyVar = $killa['totalKills'];
and then use $anyVar for your operations or directly use $killa['totalKills'] in place of $totalKills.
Hope this helped.
<?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)){
I am trying to create a class registration system for a client that utilizes PHP and MySQL. I have the database and table all set up and that part works just fine, however, the client has requested that upon registration, if there are 3 or fewer students enrolled to warn that the class may not run.
I'm trying to use the count() function as well as passing a dynamic variable from a cookie, set from the registration PHP script. However, I've hit a roadblock. I can't seem to get the count() function to actually count the rows. My select statement is below. Any help would be greatly appreciated.
$class = $_COOKIE["class"];
$min_check = "SELECT class_list, COUNT(class_list) as count
FROM T_Student WHERE class_list = '$class'
GROUP BY class_list
HAVING count < 20";
$result = mysql_query($min_check);
$count = mysql_num_rows($result);
if ($count < 4)
{
echo "IF THERE ARE 3 OR FEWER PEOPLE SIGNED UP FOR THIS CLASS, IT MAY NOT RUN.\n";
echo "THERE ARE CURRENTLY " . $count . " PEOPLE SIGNED UP.\n";
}
else if ($count > 4)
{
echo "There are currently " . $count . " people signed up for this class.";
}
?>
Your SQL query is returning a list of the class_list values, along with a count of each specific instance, where there are less than 20 people registered.
$count = mysql_num_rows($result);
...is getting the number of records returned in the resultset, not the alias count value, which is why you aren't seeing the output you expect. You need to read into your resultset to get the value:
while ($row = mysql_fetch_assoc($result)) {
$count = $row['count'];
if($count < 4) { ... }
}
The count that you want is returned in the row of the query. the mysql_num_rows will count the rows returned, which is not what you want. Use this instead.
$result = mysql_query($min_check);
$count = mysql_fetch_row($result);
$count = $count[0];
On a first glance, the HAVING count < 20 is unnecessary.
You use the MySQL-count-function, but never retrieve it's value!? Use:
$firstRow = mysql_fetch_row($result);
$count = $firstRow[1]; // 1 indicates the second column (0 being the first)
I don't recommend using known MySQL identifiers like count. It's confusing.
$class = mysql_real_escape_string($_COOKIE["class"]);
$min_check = "SELECT class_list, COUNT(class_list) as mycount
FROM T_Student WHERE class_list = '$class'
GROUP BY class_list
HAVING mycount < 20";
Don't forget to escape the contents of that cookie!
The error is that count is a reserved word. You need to either surround it in backticks `count` or even better, use a different moniker. It's not an error per se, but it's just too confusing.
Next up, you are not actually retrieving the mycount result from the database. I suggest using code something like this:
$result = mysql_query($min_check);
while( $row = mysql_fetch_assoc($result) ) {
$people_count = $row['mycount'];
if ($people_count < 4) { echo "this" }
else { echo "that" }
}