How to break a for loop from inside of a fuction - php

i have the following code
function do_function($name, $value, $age){
$sql = mysql_fetch_array(mysql_query("INSERT into `table` Values('','$name','$value','$age')"));
if (!$sql) {
// basicly will return false on duplicate key
//do something to break the calling for_loop ?
//i`ve tried break(); and continue(); but this will break/skip just the
//function not the for loop
}
}
$presetnumber = 25;
for($x = 0; $x <= $presetnumber; $x++){
do_function($name[$x], $value[$x], $age[$x]);
//return something on duplicate key to break the for loop ???
}
so i wannt to be able to just skip the entire loop if there is a duplicate key not just the function?
How can i do this, i don`t seem to understand quite entirely why break(); or continue(); is not working.
Please note that this is just a sample code to give you an ideea what i am trying to achieve.

Just return TRUE or FALSE in your function and then you can do a simple check in your loop like this:
(Pseudo code):
function do_function($name, $value, $age) {
//your stuff
if(!$sql)
return TRUE;
return FALSE;
}
for($x = 0; $x <= $presetnumber; $x++){
if(do_function($name[$x], $value[$x], $age[$x])) //breaks the loop if you return TRUE
break;
}

break will not work outside of the for loop. It must be inside the loop to be activated. So you could add a function like:
for(foo; bar; baz) {
if (checkForBreak()) {break};
}
Also, if you're working in PHP then break is a statement, not a function. So it's break;, not break();.

I believe your SQL query is always returning TRUE. Replace this:
$sql = mysql_fetch_array(mysql_query("INSERT into `table` ... "));
With this:
$sql = mysql_query("INSERT into `table` Values('','$name','$value','$age')");
I would also suggest for you to start using mysqli rather than mysql since it is deprecated

Related

While statement skips fist row

I think that because of the if statement, the while statment skips the first one.
But i need the IF and i need the WHILE.
here is my code:
if($row_antwoorden_select = mysqli_fetch_array($results_antwoorden_select)){
while($row_antwoorden_select = mysqli_fetch_array($results_antwoorden_select)){
$antwoorden .= "".$row_antwoorden_select['naam']."".$row_antwoorden_select['methode']." <a href='".$row_antwoorden_select['url']."'>Open</a><br>";
$once_info = "<h4>Antwoorden:</h4>".$select_menu."<br>";
}
}
It looks like your if statement is just checking to see if there are results from the query. If that's true and you really want to keep the if statement, you could update it to use mysqli_num_rows() instead:
if(mysqli_num_rows($results_antwoorden_select) > 0) {
while($row_antwoorden_select = mysqli_fetch_array($results_antwoorden_select)){
$antwoorden .= "".$row_antwoorden_select['naam']."".$row_antwoorden_select['methode']." <a href='".$row_antwoorden_select['url']."'>Open</a><br>";
$once_info = "<h4>Antwoorden:</h4>".$select_menu."<br>";
}
}
Note: mysqli_fetch_array() will return null if there aren't any results, so technically just eliminating the if block entirely will let your sample code work perfectly fine.
Alternatively, if you really want to keep the mysqli_fetch_array() in the if block, you could update your loop to be a do/while instead:
if($row_antwoorden_select = mysqli_fetch_array($results_antwoorden_select)) {
do {
$antwoorden .= "".$row_antwoorden_select['naam']."".$row_antwoorden_select['methode']." <a href='".$row_antwoorden_select['url']."'>Open</a><br>";
$once_info = "<h4>Antwoorden:</h4>".$select_menu."<br>";
} while($row_antwoorden_select = mysqli_fetch_array($results_antwoorden_select));
}
You're using $row_antwoorden_select = mysqli_fetch_array($results_antwoorden_select) in your if statement which is absolutely wrong because you must check available number of rows in your table using num_rows function You should try this will resolve your issue
if($results_antwoorden_select->num_rows > 0){
while($row_antwoorden_select = mysqli_fetch_array($results_antwoorden_select)){
$antwoorden = "".$row_antwoorden_select['naam']."".$row_antwoorden_select['methode']." <a href='".$row_antwoorden_select['url']."'>Open</a><br>";
$once_info = "<h4>Antwoorden:</h4>".$select_menu."<br>";
}
}

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!

as of now it just ignores the if statement and gives them a ticket everytime.php, mysql, If else

Alright so i'm trying to put value in an array and shuffle them to be random, then have it use that random value in a query. I know my code is bad and not to use mysql anymore lets stay off that topic please.
I don't understand why this isn't working I have other things like it that work just fine.
right now it ignores the if statement and gives them a ticket each time.
if(isset($_POST['Submit'])) {
$ticket = array("0","0","0","0","0","0","0","1");
shuffle($ticket);
if ($ticket >= 1) {
echo "You have Found a Shop Ticket!" ;
mysql_query("UPDATE users SET ticket=ticket+1 WHERE username = '".$_SESSION['username']."'")
or die(mysql_error());
} else {
echo "";
}
}
You're checking if the entire array is >= 1, which is obviously TRUE all the time.
Pick a value instead:
$ticket = array_shift($ticket); // do this after you shuffle
try
if (current(shuffle($ticket)) >= 1) {
# yay
} else {
# ney
}
$ticket is an array, not a number.
u could use foreach or array_map to do this.
example:
function foo($n){
if($n >= 1){//do something}
}
$ticket = array("0","0","0","0","0","0","0","1");
shuffle($ticket);
array_map('foo', $ticket);

goto equivalent for php version < 5.3.0?

I need to use the goto operator in my code as I can't seem to think of a way around it. However the problem is my host only has PHP version 5.2.17 installed.
Any ideas?
Below is my code:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
goto skip;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
skip:
There are a few anti-patterns in your code. Let's clean it up. I'll explain what's been changed in a jiffy.
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
}
}
First things first: There is no need to perform a query, fetch all of the results, then loop through those results (in_array) looking for a specific value. Let the database do that for you by expressly looking only for rows where inserted is the string literal "n".
Because we know that we're only getting "n" records back, we just need to check if there are any results. If so, run the query. If there are no "n" records, the UPDATE isn't run.
If you need to know that the UPDATE ran, add a check for it:
$ran_update = false;
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
$ran_update = true;
}
}
if($ran_update) {
// ...
}
You want to use the correct control word to break from the loop:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
break;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
The break keyword will do exactly what you want: End the execution of the while loop. Never ever ever use a goto!
As a direct response to the title of this post:
do{
if (!$condition){
break;
}
// Code called if conditions above are met
}while(0);
//Code always called
In some circumstances, this, or a goto, can make for very tidy and readable code.
First, you could use a break to exit your initial loop. Second, if you need to test for anything, set a variable (must be global not local) as a flag or indicator before calling break, then do a conditional test statement where your skip line is to perform any additional steps you need.

I need to have a variable IN my variable name, not AS my variable name

How would I do that?
According to PHP.net,
$a = "hi";
$hi = 2;
$$a; // returns 2
However, I need:
$i = 2;
$_POST['link$i']; // I need this to return the same thing as $_POST['link2']
Here is how I have my code.
for ($i = 1; $i <= 40; $i++)
{
if(!empty($link$i))
{
$link$i = mysql_real_escape_string($_POST['link$i']);
mysql_query("
INSERT INTO links (link, rimageid) VALUES
('".$link$i."', '".$id."') ");
} else { }
}
The reason I'm doing this is because I have a lot of text input fields posting their values to this file, and I'd like to define and insert each of their values via a for loop instead of manually inserting each single link into mysql.
Right now, I get:
Parse error: syntax error, unexpected T_VARIABLE, expecting ')' in C:\xampp\htdocs\new2.php on line 22
How would I go about doing this?
Thanks!
For array index concatenation, ok, but this code
for ($i = 1; $i <= 40; $i++)
{
if(!empty($link$i))
{
$link$i = mysql_real_escape_string($_POST['link$i']);
mysql_query("
INSERT INTO links (link, rimageid) VALUES
('".$link$i."', '".$id."') ");
} else { }
}
won't work as you expect, i.e. name a variable like the result it's not necessary, why would you want to do that? PHP doesn't care about the variable name and if it's coordinated with the result.
Just do:
for ($i = 1; $i <= 40; $i++)
{
if(!empty($_POST['link'.$i]))
{
$regular_variable_name = mysql_real_escape_string($_POST['link'.$i]);
mysql_query("INSERT INTO links (link, rimageid) VALUES ('".$regular_variable_name."', '".$id."') ");
} else { }
}
How about string concatenation?
$_POST['link'.$i];
You are receiving a syntax error because $link$i is not valid.
if you want the end value to be link2 then you need a solution like Nick Shepherd suggested.
It could be easier to see what is going on if you create the string that you want for the key first.
$key = 'link' . $i;
After that you can use the key whenever you want, in a conditional like
if (!empty($_POST[$key])) {
and again in your mysql_escape
mysql_real_escape_string($_POST[$key]);
$_POST['link' . $i];
This should solve your problem. For indexes of an array you can simply concatenate the string for the index that you are trying to resolve.
yep... you can do the following
$ = 2;
$link = "link" . $i;
if(isset($_POST[$link])){
//do something
}
or
$_POST[$link.$i]
the same goes for methods
$type = "Something";
$method = "get" . $type;
$this->$method(); //calls method -> getSomething()

Categories