I'm wrapping up my website, but I've an issue with breaking
if statement inside foreach statement,
I want when a student try to pick a job that he/she already had chosen, the if() fail and break from the WHOLE foreach() loop, this is my code,the break inside the if() only break out the if(), not the whole foreach
please please help me.
thank you
foreach($_POST['JobId'] AS $i){
$sqlCheckingBeofrAdding ="SELECT * FROM JobsLists WHERE JobId = '".$i."' AND SSU = '".$SSU."' ";
$rs = mysqli_query($dbCIE ,$sqlCheckingBeofrAdding);
$row1 = mysqli_fetch_assoc($rs);
if($row1 > 0){
echo "You Already Have this Job In your List";
break;
}
//insert into junction table..
$sqlUpdate = "UPDATE Jobs SET NoStudent=NoStudent-1 WHERE JobId = '" . $i . "'";
$resultUpdate = mysqli_query($dbCIE,$sqlUpdate) or die(mysqli_error($dbCIE));
$sqlInsert ="INSERT INTO JobsLists(`JobID` , `SSU`) VALUES(".$i.",'".$SSU."' )";
$MyQuery= mysqli_query($dbCIE, $sqlInsert) or die(mysqli_error($dbCIE));
}
If your query is only return the single student record than you can use return and this will not execute the further code inside the loop.
If your query returns multiple students record than you can use continue
For point 1:
if($row1 > 0){
echo "You Already Have this Job In your List";
return;
}
For point 2:
if(condition){
echo "You Already Have this Job In your List";
continue;
}
You can use break; OR return; (if this is a function.) Let me know if you need code.
The break statement in PHP accepts a numeric argument.
Try changing your break; to break 2; or use a return;
The php manual says:
break ends execution of the current for, foreach, while, do-while or switch structure.
I do not think your break is breaking out of the if. I suspect a different problem with your code.
Break does not break ifs. This is how the language works.
Ensure you have a debug line before and after the if instead of simple MySQL operations. This seems to be a problem with the code.
For example, add some echo lines before and after the if and you'll have a better idea on what's going on.
The code itself seems to have a lot of problems:
1-You don't need to retrieve all fields (select *) in order to see if at least one entry exists. This is a misuse of the database layer.
2-In case you need to check if one entry exists, add LIMIT 1 to your SQL query. This will avoid MySQL to scan the entire table in case the query is not using any unique key, which is very likely.
3-mysqli_fetch_assoc returns an associative array, but then you compare the array against "> 0". Would you confirm that Array() > 0 ?
4-You seem to be using camelCased variables, but then all of the sudden you have $MyQuery, when it should be $myQuery to match the convention you're using.
5-You're storing the result of the query, in a variable named $MyQuery. This is a bad practice, as the variable name should describe what it contains. Therefore you'll want to call it $myResult or $rs as you did in the first query.
6-None of the variables used in the SQL statements are escaped.
Double check your code using the rubber duck technique and I'm sure you'll find the issue is not related to the if/break; but to something else. Not to offend, but this code seems very immature.
Related
So let me explain my problem, lets assume that I run query like so:
$myquery = sql_query("SELECT name FROM table WHERE name='example' LIMIT 0,1");
Now.. I want to store the retrieved name into a variable so I would do something like this:
while ($myrow = sql_fetch_assoc($myquery)) {
transfer_row($myrow);
print"Name: $row_name";
}
$stored_name = $row_name;
NOTE: transfer_row() is just a function I wrote that takes $myrow['name'] and stores it in $row_name, for easier reference
Now, all is fine at this stage, here is where it gets interesting. Note that at this stage I still have a name assigned to $row_name. Further down the page I run another query to retrieve some other information from the table, and one of the things I need to retrieve is a list of names again, so I would simply run this query:
$myquery = sql_query("SELECT name, year FROM table WHERE DESC LIMIT 0,10");
while ($myrow = sql_fetch_assoc($myquery)) {
transfer_row($myrow);
$year = $row_year;
$link = "/$year";
print "<li style=\"margin-bottom: 6px;\">$row_name\n";
}
Now, I want to write an if statement that executes something if the $row_name from this query matches the $row_name from the old query, this is why we stored the first $row_name inside the variable.
if ($row_name == $stored_name){
// execute code
}
However as most of you know, this WONT work, the reason is, it simply takes $stored_name again and puts the new $row_name into $stored_name, so therefore the value of the first $row_name is lost, now it is crucial for my application that I access the first $row_name and compare it AFTER the second query has been run, what can I do here people? if nothing can be done what is an alternative to achieving something like this.
Thanks.
EDIT, MY transfer_row() function:
function transfer_row($myrow) {
global $GLOBALS;
if(is_array($myrow)) {
foreach ($myrow as $key=>$value) {
$key=str_replace(":","",$key);
$GLOBALS["row_$key"] = $value;
}
}
}
Without you posting the code for the function transfer_row, we won't be able to give you an answer that exactly matches what you request, but I can give you an answer that will solve the problem at hand.
When matching to check if the names are the same, you can modify the if statement to the following.
if ($row_name == $myrow['name']){
// execute code
}
What I suggest you do though, but since I don't have the code to the transfer_row function, is to pass a second variable to that function. The second variable will be a prefix for the variable name, so you can have unique values stored and saved.
Refrain from using the transfor_row function in the second call so your comparison becomes:
if ($myrow['name'] == $row_name)
If you need to use this function, you could do an assignment before the second database call:
$stored_name = $row_name;
...
transfer_row($myrow);
In your first query you are selecting the name field WHERE name='example' , Why are you quering then? You already have what you want.
Your are querying like:
Hey? roll no 21 what is your roll no?
So perform the second query only and use the if condition as :
if ($row_name == 'example'){
// execute code
}
Does it make sense?
Update
//How about using prefix while storing the values in `$GLOBAL` ??
transfer_row($myrow, 'old_'); //for the first query
transfer_row($myrow, 'new_'); //for the second query
function transfer_row($myrow, $prefix) {
global $GLOBALS;
if(is_array($myrow)) {
foreach ($myrow as $key=>$value) {
$key=str_replace(":","",$key);
$GLOBALS["$prefix"."row_$key"] = $value;
}
}
}
//Now compare as
if ($new_row_name == $old_row_name){
// execute code
}
//You'll not need `$stored_name = $row_name;` any more
We have a table vehicle and a simple php form. Before inserting data I do check if the vehicle registration number exist but some client pc could enter duplicate entries. Below is the code snippet. What else could be causing this ?
$vehicleRegistrationNumber=$_POST['vehicleRegistrationNumber'];
$selectQuery1 ="Select vehicleRegistrationNumber From Vehicle Where vehicleRegistrationNumber='".$vehicleRegistrationNumber."'";
$result1 = mysqli_query($link,$selectQuery1);
$row1 = mysqli_fetch_array($result1, MYSQL_ASSOC);
$n1 = mysqli_num_rows($result1);
if($n1 > 0) {
$status="<span class=\"statusFailed\">: Vehicle ".$vehicleRegistrationNumber." Already Exist.</span>";
}
else {
//insert codes
}
First of all your code is vulnerable to SQL injection. This check can be bypassed by submitting something like XYZ0001' AND 1='0 or even more malicious values. To prevent this, use prepared statements and param binding instead of string concatenation.
Other possibility is simply user mistake, for example trailing space ("XYZ001" != "XYZ0001 ") that is hard to spot on the first glance ad records in DB. Before checking its existence in DB you should check with PHP if submitted value includes only allowed chars and is free from common mistakes.
try this with group by
$selectQuery1 ="Select vehicleRegistrationNumber From Vehicle Where vehicleRegistrationNumber='".$vehicleRegistrationNumber."' GROUP BY vehicleRegistrationNumber";
The best way is to handle it on the SQL side. Just define the field as UNIQUE INDEX.
Now when trying to insert a duplicate index an error will be thrown and you can catch it like this:
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
Like this you can avoid the select query before every insert query. Just handle the error as you want.
HI everyone i tried for 3 days and i'm not able to solve this problem. This is the codes and i have went through it again and again but i found no errors. I tried at a blank page and it worked but when i put it inside the calendar it has the syntax error. Thanks a million for whoever who can assist.
/** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/
$testquery = mysql_query("SELECT orgid FROM sub WHERE userid='$userid'");
while($row4 = mysql_fetch_assoc($testquery))
{
$org = $row4['orgid'];
echo "$org<br>";
$test2 = mysql_query("SELECT nameevent FROM event WHERE `userid`=$org AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'") or die(mysql_error());
while($row5=mysql_fetch_assoc($test2))
{
$namethis = $row5['nameevent'];
$calendar.=$namethis;
}
}
First question: what calendar are you talking about?
And here are my 2-cents: does the EXTRACT function returns a string or a number?
Are the "backticks" (userid) really in your query? Try to strip them off.
Bye!
It's a guess, given that you haven't provided the error message you're seeing, but I imagine that userid is a text field and so the value $org in the WHERE clause needs quotes around it. I say this as the commented out testquery has quotes around the userid field, although I appreciate that it works on a different table. Anyway try this:
SELECT nameevent FROM event WHERE userid='$org' AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'
In such cases it's often useful to echo the sql statement and run it using a database client
First step in debugging problems like this, is to print out the acutal statement you are running. I don't know PHP, but can you first build up the SQL and then print it before calling mysql_query()?
EXTRACT() returns a number not a character value, so you don't need the single quotes when comparing EXTRACT(YEAR FROM startdate) = 2010, but I doubt that this would throw an error (unlike in other databases) but there might be a system configuration that does this.
Another thing that looks a bit strange by just looking at the names of your columns/variables: you are first retrieving a column orgid from the user table. But you compare that to the userid column in the event table. Shouldn't you also be using $userid to retrieve from the event table?
Also in the first query you are putting single quotes around $userid while you are not doing that for the userid column in the event table. Is userid a number or a string? Numbers don't need single quotes.
Any of the mysql_* functions can fail. You have to test all the return values and if one of them indicates an error (usually when the function returns false) your script has to handle it somehow.
E.g. in your query
mysql_query("SELECT orgid FROM sub WHERE userid='$userid'")
you mix a parameter into the sql statement. Have you assured that this value (the value of $userid) is secure for this purpose? see http://en.wikipedia.org/wiki/SQL_injection
You can use a JOIN statement two combine your two sql queryies into one.
see also:
http://docs.php.net/mysql_error
http://docs.php.net/mysql_real_escape_string
http://www.w3schools.com/sql/sql_join.asp
Example of rudimentary error handling:
$mysql = mysql_connect('Fill in', 'the correct', 'values here');
if ( !$mysql ) { // some went wrong, error hanlding here
echo 'connection failed. ', mysql_error();
return;
}
$result = mysql_select_db('dbname', $mysql);
if (!$result ) {
echo 'select_db failed. ', mysql_error($mysql);
return;
}
// Is it safe to use $userid as a parmeter within an sql statement?
// see http://docs.php.net/mysql_real_escape_string
$sql = "SELECT orgid FROM sub WHERE userid='$userid'";
$testquery = mysql_query($sql, $mysql);
if (!$testquery ) {
echo 'query failed. ', mysql_error($mysql), "<br />\n";
echo 'query=<pre>', $sql, '</pre>';
return;
}
I'm using Drupal's db_fetch_array to fetch rows from my db_query. However, every row returned is equal to NULL. Typing the query into PHP myadmin works, so I have no idea whats going on. db_num_rows returns the number of rows as well. Here is the code:
if(count($rebuild_ids))
{
$ids=implode(",",$rebuild_ids);
$type_stmt = "SELECT * from {" . ItemType::$type_table_name . "} where id IN ($ids)";
$new_items=db_query($type_stmt);
if(!$new_items || db_num_rows($new_items) == 0)
{
return;
}
while($row = db_fetch_array($new_items));
{
if ($row!=NULL)
{
echo "I work!"
$game_items[] = $row['id'];
ItemInstance::$nid_to_item_type_code[$row['nid']] = $row['id'];
}
}
}
However, it never gets into the third if statement (i.e. never echos "I work!") Any ideas?
Friendly advice: Drupal has a coding standards http://drupal.org/coding-standards -- it helps to keep them. This error would have been a lot more obvious that way....
Also putting variables in a query is a huge no-no see http://drupal.org/writing-secure-code
$row is not NULL by definition, otherwise it wouldn´t even reach the third if statement.
There is no need to check if $row contains information, the while loop already takes care of that, but if you want to check anyway, use something like empty($row) or count($row) > 0; don´t compare an array with NULL.
The checking is completely unnecessary though...
K figured it out. It was the semicolon after the while loop!
im having trouble getting data from two seperate tables
so far i have this
<?
include('config.php');
$xid = $_GET['xid'];
$result = mysql_query("SELECT * FROM `config`") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$result = mysql_query("SELECT * FROM `utinfo` WHERE `xid` = $xid") or trigger_error(mysql_error());
while($row2 = mysql_fetch_array($result)){
foreach($row2 AS $key => $value) { $row2[$key] = stripslashes($value); }
$un = urldecode($row2['un']);
};
switch ($row['module'])
{
case 1:
echo "Function 1 for user $uid on account $un";
break;
case 2:
echo "Function 2 for user $uid on account $un";
break;
case 3:
echo "Function 3 for user $uid on account $un";
break;
default:
echo "No module defined.";
};
};
?>
The config table config has the row named modules, and its populated by 2 entries, one of which is 1, the other 3. So i should be seeing case 1 and then case 3. But all im getting is the default echo.
(This is not an answer to the OP, but something you really should care about, so I think it's worth writting it)
It seems there is a enormous SQL-injection in your code.
The normal way of calling your page would be with something like "xid=5" in the URL, to get informations of user #5.
Now, suppose someone give "xid=5 or 1=1". The resulting query would be :
SELECT * FROM `utinfo` WHERE `xid` = 5 or 1=1
The condition is always true ; you'd get informations of ALL users as an output, as you iterate through the resultset.
Another possibility : "xid=5; delete from utinfo;" ; which would give this query :
SELECT * FROM `utinfo` WHERE `xid` = 5; delete from utinfo;
That would empty your table :-(
You must always escape / check / sanitize / whatever you data before putting them in a SQL query, especially (but not only) if they come from a user of the application.
For strings, see the mysql_real_escape_string function.
For data that sould be integers, you could use intval (worst case, if data was not valid, you'll get 0, which might get no result from the DB, but, at least, won't break it ^^ )
Another solution would be to use prepared statements ; but those are not available with mysql_* function : you have to switch to either
mysqli_*
or PDO
Anyway, for a new application, you shouldn't use mysql_* : it is old, and doesn't get new functionnalities / improvements that mysqli and PDO get...
stripslashes() is used on strings. Your case values are integers. It seems like you have a type mismatch here?
Why are you not using PDO? You should really standardis on PDO if you can.
Table names in SQL select should not be quoted.
You should consider using prepared statements in order to avoid SQL Injection and then you don't have to worry about having to quote your paramaters
The first answer is probably correct regarding type mismatches, you should be able to fix the issue by using the following code:
switch ((integer) $row['module'])
See the following:
http://us.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting
Alternatively, you could try this:
settype($row['module'], "integer");
switch ($row['module'])
See:
http://us.php.net/manual/en/function.settype.php
I would also suggest echo'ing the value of $row['module'] onto the page just to check that it is indeed an integer.