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.
Related
I have a very simple PHP function which checks the DB if the post is saved in the user's bookmarks or not. If it is saved as a bookmark in the table 'bookmarks', it should return a link to the bookmarks, if not, it should return a simple button.
This is the code that calls the function:
echo bookmark($id,'stories');
This is the PHP function:
function bookmark($id,$column) {
global $db_conx;
if($column = 'stories') { $col = 'storid'; }
elseif($column = 'discussions') { $col = 'discid'; }
elseif($column = 'articles') { $col = 'articleid'; }
elseif($column = 'videos') { $col = 'videoid'; }
else $col = 'resid';
$result = mysqli_query($db_conx, "SELECT * FROM bookmarks WHERE '$col'='$id' AND username='$log_username' LIMIT 1");
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
return "<a class='rllink' title='Saved in your bookmarks' href='https://hangar.flights/bookmarks'><i class='fa fa-bookmark'></i></a>";
}
else return "<a class='rllink' href="xxxx" title='Save this in your bookmarks'><i class='fa fa-bookmark-o'></i></a>";
};
For some weird reason, this doesn't seem to be working, although my other similar functions do work. Everywhere I call this function (with the correct parameters) it returns the else statement, even if the specific id is saved in the bookmarks and should return the first statement with a link to the bookmarks.
Anyone who sees what's wrong with it? I have tried adapting and changing it but nothing works.
You are using assignment-in-if:
if($column = 'stories')
When executed, this is what happens:
the value of $column becomes the string 'stories'
the if statement checks whether the new value of $column is truthy
This is almost certainly not what you want, and you'll probably want to do comparing-if statements that don't change the value(s) of the things you check:
if($column == 'stories')
This will check whether $column is currently equal to the string 'stories' without changing the value.
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!
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);
I have a PHP page with 3 dropdownlists on it. Everytime with an 'onchange' event a javascript docs get's the selected value's and transfers it to a php function, where I can transfer them to my mysql-database and get results out of them. This thing works perfect, but not when I apply my logic to define which function I should call
My php page contains the effective logic (see code-box) and underneed there are the 2functions with the actions. The function do work, but the problem is this. There's the possibility in the if-else construction that the functions can be called on 2 different moments. The first time in the if-else construction both of the calls are succesfull and the result is what it should be, the second moments it seems that the $result parameter is empty?
$result = mysql_query($sql) or die("Query failed with error: ".mysql_error());
$aantal = mysql_num_rows($result);
if($amount == 0){
echo "<p>This combination does not exist</p>";
}
else {
// lists are empty
if($soort == 'Empty' && $land == 'Empty' && $jaar == 'Empty'){
}
else {
if ($aantal > 2){
maketable($aantal, $result); // -> **succesfull call**
}
else if($aantal == 1){
makedetails($result); // -> **succesfull call**
}
else {
$first = mysql_result($result, 0);
$second = mysql_result($result, 1);
if (($second - $first) == 1){
makedetails($result); // -> **does not work**
}
else {
maketable($aantal, $result); // -> **does not work**
}
}
}
}
function maketable($aantal, $result) { … }
function makedetails($result){ … }
greetings
You don't show your query, so we can't tell what's going on. But mysql_result by default returns the FIRST field in the specified row, if you don't explicitly state which field to use, so unless your query is
SELECT somenumber FROM yourtable ...
then your mysql_result is going to be fetching who knows what. Note that you're also comparing that default 'first' value from two different rows - are you sure the query is actually returning 2+ rows of data?
$aantal is the number of rows affected by the query. Your logic does not work because you're trying to use query results when there are no rows affected.
Your logic:
$result = mysql_query($sql);
$number_of_rows = mysql_num_rows($result);
if ($number_of_rows > 2)
{
//do something
}
else if ( $number_of_rows == 1)
{
//Do something else
}
else if( $number_of_rows == 2 OR $number_of_rows == 0)
{
// Do something else (the part which fails)
}
The only way to reach that part and not fail is if the rows affected are exactly 2. When they are 0, the query didn't return anything and you are trying to access an empty result set.
Had to fetch my result once more to make it possible to loop through my array once again.
$first = mysql_result($result, 0);
$second = mysql_result($result, 1);
$result = mysql_query($sql) or die("Query failed with error: ".mysql_error());
But thanks for the help!
greetings
I code a weekly trivia program for one of my clients through facebook.
I have a bit of code commented out where we display the winner when we need to. Currently I just remove the comment brackets and update when it's time to display. I'm trying to make this so someone non-savvy can handle updates so I've moved my code into an include:
winner-display.php
I am trying to write a function so that if the winner is set in MySQL, it includes the file in-line, and if the winner field is empty in the database, it does not.
Here is what I have so far, any ideas?
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != 'null') {
include('../includes/winner-display.php');
} else {
}
?>
Ok, thanks for helping guys, got it to work as:
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
foreach ($row as $field) {
if ($field != null) {
include('../includes/winner-display.php');
}
}
}
?>
You can definitely put an include within an if. That solution that you posted should work as you would like it to, although I personally would have used a function instead of a completely separate file to include (although that is personal preference).
All you have to do to make it work is remove the quotes around 'null'.
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = $target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != null) {
include('../includes/winner-display.php');
}
?>
Keep in mind that if your query returns more than one row, only the last row will be retained. I don't know if that is the functionality you want (in which case, there are some changes you could make, just ask me to edit my answer), but I didn't change that.