I'd like to be able to loop the if/elseif/else statement if it falls onto any of the statement that is not else.
$names is an array with a couple of names that the user will select.
Right now, the code does work but if the condition falls into any of the elseifs then the loop will stop. From the user's perspective it's almost like nothing has happened.
if($names[0] == $poster) {
shuffle($names);
} elseif($names[1] == $entertainer) {
shuffle($names);
} elseif($names[2] == $tunar) {
shuffle($names);
} elseif($names[3] == $keeper) {
shuffle($names);
} elseif($names[4] == $feeder) {
shuffle($names);
} elseif($names[5] == $provider) {
shuffle($names);
} else {
echo "This week's roles are:";
while($row = mysqli_fetch_assoc($this_week_result) ) {
$poster = $row['poster'];
$entertainer = $row['entertainer'];
$tunar = $row['tunar'];
$keeper = $row['keeper'];
$feeder = $row['feeder'];
$provider = $row['provider'];
}
echo $names[0] . " is the Poster <br>";
echo $names[1] . " is the Entertainer <br>";
echo $names[2] . " is the Tunar <br>";
echo $names[3] . " is the Keeper <br>";
echo $names[4] . " is the Feeder <br>";
echo $names[5] . " is the Provider <br>";
$sql = "INSERT INTO funroles
(poster,entertainer,tunar, keeper, feeder, provider, date)
VALUES ('$names[0]','$names[1]','$names[2]','$names[3]','$names[4]','$names[5]','$date')";
$result = mysqli_query($conn, $sql);
mysqli_close($conn);
}
It looks like you want to keep shuffling until none of the names in $names is in the same position it previously was. If I understand it correctly, you can do it without the if/elseif/else structure.
Create an array of the current names that matches the key position of $names like this:
$current = [$poster, $entertainer, $tunar, $keeper, $feeder, $provider];
Then use array_intersect_assoc to check if any key/value pairs match, and shuffle until none of them do (it will return an empty array).
while (array_intersect_assoc($current, $names)) {
shuffle($names);
}
Then do the stuff with your database afterward.
Related
I want to display a specific value from key value list..
here is my code:
if (isset($_POST) && count($_POST)>0 )
{
foreach($_POST as $paramName => $paramValue) {
echo "<br/>" . $paramName . " = " . $paramValue;
}
}
ouput
ORDERID = ORDS3700373
TXNAMOUNT = 200.00
CURRENCY = INR
TXNID = 32221284
BANKTXNID = 475815
STATUS = TXN_SUCCESS
RESPCODE = 01
RESPMSG = Txn Successful.
TXNDATE = 2017-01-10 18:13:25.0
GATEWAYNAME = WALLET
BANKNAME =
PAYMENTMODE = PPI
CHECKSUMHASH =
here I want to display only ORDERID and TXNID.. How do I get that value?
You can easily access post values by it's field name instead of looping through all post elements. Simply access that elements directly as below:
if(isset($_POST['ORDERID'])) {
echo 'ORDERID = '.$_POST['ORDERID'];
}
if(isset($_POST['TXNID'])) {
echo 'TXNID= '.$_POST['TXNID'];
}
Moving comments to an answer.
You do not need to loop post it is just a global array. You can access the values at any of the keys like any associative array because that is what it is. Likewise these value can be used like any other
if(isset($_POST['ORDERID'])){
$orderid = $_POST['ORDERID'];
}
if(isset($_POST['TXNID'])){
$txnid = $_POST['TXNID'];
}
// Should use htmlspecialchars() or htmlentities() here
// but didn't want to confuse OP. It is for security.
echo "ORDERID is: " . $orderid . " and TXNID is: " . $txnid;
A note for security never trust user input and sanitize all $_POST variables before echoing or persisting. There are far better article out on the internet than I can summarize here.
You can use if condition in the loop like this
if (isset($_POST) && count($_POST)>0 )
{
foreach($_POST as $paramName => $paramValue) {
if($paramName == 'ORDERID' || $paramName == 'TXNID')
echo "<br/>" . $paramName . " = " . $paramValue;
}
}
add an if like
if($paramName == "ORDERID" || $paramName == "TXNID") {
after foreach, remeber to close it after echo statement line
Don't overcomplicate a trivial task with a loop.
Just drop the loop and echo the two values directly:
// Assuming the two values are expected to come in pair:
if(isset($_POST['ORDERID']) && isset($_POST['TXNID'])) {
echo "<br/>ORDERID = " . $_POST['ORDERID'];
echo "<br/>TXNID = " . $_POST['TXNID'];
}
If you insist on having a loop, then you can go through the property names which you need
foreach(array('ORDERID', 'TXNID') as $paramName) {
if(isset($_POST[$paramName])) {
echo "<br/>" . $paramName . " = " . $_POST[$paramName];
}
}
I confused the method to flip the place of the echo result, below is my code
while ($looptools == 0) {
$mysqlihelper = " SELECT * FROM soal WHERE nomorsoal = $numberofmysqli ";
$mysqliquery = mysqli_query($konek, $mysqlihelper);
$resultquery = mysqli_fetch_assoc($mysqliquery);
$resulttextjudul = $resultquery['judul'];
if ($resulttextjudul == null) {
unset($resulttextjudul);
$resulttextjudul = "Tunggu Soal Berikutnya ! ..";
$nullerror = true;
} else {
}
if ($nullerror == true) {
echo "<div class=\"head-main-recenttest-result\" style=\"text-decoration:none\">" . $resulttextjudul . "</div>";
} else {
echo "<div class=\"head-main-recenttest-result\" style=\"text-decoration:none\">" . $resulttextjudul . "</div>";
}
if ($nullerror == true) {
mysqli_close($konek);
break;
} elseif ($looptools == 10) {
mysqli_close($konek);
break;
} else {
}
}
As you see in the "while", it's echo the first result and the second result below it, but I want the first result in below of the second result, can anyone tell me the method to do it?
I assume you mean you want to print all successes followed by all errors, or something like that. Here's how:
if($nullerror == true){
$errors .= "<div class=\"head-main-recenttest-result\" style=\"text-decoration:none\">".$resulttextjudul."</div>";
}else{
$successes .= "<div class=\"head-main-recenttest-result\" style=\"text-decoration:none\">".$resulttextjudul."</div>";
}
Then, when the while loop is done:
echo $successes ;
echo $errors ;
If you really want to work your way backwards through the results in $mysqliquery, that's a different answer.
UPDATE: to reverse the order of successes / errors on display, just put the latest additions in front:
if($nullerror == true){
$errors = "<div class=\"head-main-recenttest-result\" style=\"text-decoration:none\">".$resulttextjudul."</div>" . $errors;
}else{
$successes = "<div class=\"head-main-recenttest-result\" style=\"text-decoration:none\">".$resulttextjudul."</div>" . $successes ;
}
sorry if i answer my own question because i found it out myself
use mysqli_num_rows or often called mysqli count
http://php.net/manual/en/mysqli-result.num-rows.php
I want to check if a certain field of all rows match a criteria.
So if all rows has in the Status field 'RUN' as value then echo "Success".
If there is one row with END as value then echo "Fail":
I'm guessing I need a loop and an IF statement ?
I was thinking something like this but it doesnt return anything:
while($source_row = mysqli_fetch_array($source_selection)){
if ( ($source_row['Stat']) == ("Run" ) {
echo "Success<br />";
} else
echo "Fail";
}
I don't want to echo each row, I want all rows to match a criteria then echo, if one doesn't match a criteria then echo as well.
This should work for you:
First of all you have to fetch all rows with mysqli_fetch_all(). After this I extract only the Stat column with array_column(). Then I just simply array_fill() an array with X values as you have in $states with the value "Run". And check if every value is equals.
$result = mysqli_fetch_all($source_selection, MYSQLI_ASSOC);
$states = array_column($result, "Stat");
if($states == array_fill(0, count($states), "Run")) {
echo "Success";
} else {
echo "Fail";
}
There are some error in the code and you can use the count to match -
$count = 0;
while($source_row = mysqli_fetch_array($source_selection)){
if ($source_row['Stat'] == "Run" ) {
$count++;
}
}
if($count != mysqli_num_rows($source_selection)) {
echo "Fail";
} else echo "Success";
For best performance you can do it directy on the SQL:
select count(*) from table where Stat <> 'Run';
And then test the returning value to check that is greater than zero.
To do it with php you should know that when you find an error you can stop the iterations. The code would look like that:
while($source_row = mysqli_fetch_array($source_selection)){
if ( $source_row['Stat'] != "Run" ){
$fail = true;
break;
}
}
if ($fail) {
echo "Fail";
} else
echo "Success";
}
Try this
$success=true;
while($source_row = mysqli_fetch_array($source_selection)){
if ( ($source_row['Stat']) != ("Run" ) {
$success=false;
}
}
if ($success) {
echo "Success";
} else {
echo "Fail";
}
I have a php script for check the availability of some data. I call this script from external jquery. the jquery is running fine. here is my php:
<?php
$avares = checkAva($fi_nm, $tbl_nm, $txtval);
echo $avares;
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table . "") or die("query failed");
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
if ($curval == $dbval) {
return "no";
} else {
return "yes";
}
}
}
?>
$curval is the variable coming from external jquery. my problem is that the while loop seems to run only once though there are lot of entries in the DB. I checked it with an integer variable and the while loop seems to run only once. can you help me to solve that?
Look at your code.
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
if ($curval == $dbval) {
return "no";
} else {
return "yes";
}
}
you have used return, if its true it returns and false then also returns change those according to your needs. The return statement immediately ends execution of the current function
It will by design as you have a return statement. From what you have said your not actually wanting it to return but to set a variable that at end of execution will return no or yes. I could be wrong on this but hey ho.
<?php
echo checkAva($fi_nm, $tbl_nm, $txtval);
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table) or die("query failed");
$noOrYes = "yes";
while ($a_row = mysql_fetch_array($avres)) {
if($curval == $a_row[$field]) {
$noOrYes = "no";
}
}
return $noOrYes;
}
?>
The possible issue that can cause Loop to iterate once are:
Error in the Variable used for the $query and $result
Same name Variable inside and outside of the Loop
Incorrect placement of Return statement
Invalid Mysql Statement
Directly put the condition in your Query like
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table . "
WHERE `".$field."` = '".$curVal."'");
$res = mysql_fetch_array($avres);
if(is_array($res) && count($res) > 0)
return "Yes";
else
return "No";
}
Instead of getting all the results and checking with each one of the result you directly put a condition to extract the results which satisfies your condition.This will be suggestable if you have many records.
You need to put one of the return outside of the while loop.
For example if you just wanted to check if $curval == $dbval
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
//If the condition was met return with a no
if ($curval == $dbval) {
return "no";
}
}
//If the condition was not met return yes
return yes;
That's basically what you need to do so the loop will run until your condition was met or not at all.
I'm working on a little project and I've gone brain dead, so I'm hoping someone here can help me defeat my coders block.
I'm trying to create a page using php that changes its content display depending on what (if any) value is passed to the page (Locations). I have created a safelist array which I've stored the different locations. First I check any value passed against the safe list, if its a match I display one set of content.
If it doesn't match I'm running a similarity test to check if theres maybe a simple typo and can still navigate people to the page I think they wanted but this is where I'm getting stuck.
I'm hoping that someone could type
www.example.co.uk/location.php <---- to load a generic location page
www.example.co.uk/location.php?loc=Bishops-Stortford <---- to load a targeted location page
www.example.co.uk/location.php?loc=Bishop-Stortford <---- to load a targeted location page despite mispelling providing its a 90% or more match
www.example.co.uk/location.php?loc=?php echo "I hacked your site"; ?> ---- hopefully my system will disarm nasty code injection
I'll post my code below so you can see what I've got.
<?php
$loc = "";
$safelist = array("Bishops Stortford", "Braintree", "Chelmsford", "Dunmow", "Harlow", "Hertford", "Saffron Walden", "Sawbridgeworth", "Stansted", "Ware",
"Essex", "Hertfordshire");
if(isset($_GET["loc"])) {
/* Gets the value of loc if set, replaces hyphens with spaces and capitalises first letters of words converting the rest to lowercase. */
$loc = ucwords(strtolower(str_replace("-", " ", $_GET["loc"])));
}
/* Is word in safelist */
if (in_array($loc, $safelist)) {
/* Yes */
if (($loc == "Essex") or ($loc == "Hertfordshire")) {
$county = True;
} else {
$county = False;
}
if ($county == False) {
echo "\"" . $loc . "\" is not a county";
}else{
echo "\"" . $loc . "\" is a county";
}
} else {
/* No, Is string 90% similar to any entry within the safelist? */
foreach ($safelist as $safeword) {
similar_text($safeword, $loc, $percent);
echo $safeword . " " . $loc . " " . $percent . "<br />";
if ($percent >= 90) {
}
}
?>
I can't think what to do for the if ($percent >=90). I know I want to exit the loop and get the result from the first 90% or more match I find but am not 100% sure how to do this.
Also whats the best way to deal with code injection like www.example.co.uk/location.php?loc=?php echo "I hacked your site"; ?>
I think this is what you want:
foreach ($safelist as $safeword) {
similar_text($safeword, $loc, $percent);
echo $safeword . " " . $loc . " " . $percent . "<br />";
if ($percent >= 90) {
$loc = $safeword;
$county = true;
break;
}
}
As long as you don't call eval() on user input, you don't have to worry about them injecting PHP statements. When you echo something, it's sent to the browser, it's not executed again by PHP. However, you should still sanitize the output, because it might contain HTML markup, perhaps even Javascript, which could hijack the user's browser. When displaying output on the page, use htmlentities() to encode it:
echo "Greetings, " . htmlentities($first_name);
To answer the second part of your question, I use htmlentities to output data directly to the screen from input and something like this function on the data before a save to a database:
function escape_value($value)
{
if($this->real_escape_string_exists)
{
if($this->magic_quotes_active){$value = stripslashes($value);}
$value = mysql_real_escape_string($value);
}
else
{
if(!$this->magic_quotes_active){$value = addslashes($value);}
}
return $value;
}
I think I would restructure it, something like this:
$loc = "";
$safelist = array("Bishops Stortford", "Braintree", "Chelmsford", "Dunmow", "Harlow", "Hertford", "Saffron Walden", "Sawbridgeworth", "Stansted", "Ware",
"Essex", "Hertfordshire");
if(isset($_GET["loc"])) {
/* Gets the value of loc if set, replaces hyphens with spaces and capitalises first letters of words converting the rest to lowercase. */
$loc = ucwords(strtolower(str_replace("-", " ", $_GET["loc"])));
}
$good = '';
if (in_array($loc, $safelist)) {
$good = $loc;
} else {
foreach ($safelist as $safeword) {
similar_text($safeword, $loc, $percent);
echo $safeword . " " . $loc . " " . $percent . "<br />";
if ($percent >= 90) {
$good = $safeword;
}
}
}
if ( ! empty($good)){
/* Yes */
if (($good == "Essex") or ($good == "Hertfordshire")) {
$county = True;
} else {
$county = False;
}
if ($county == False) {
echo "\"" . $good . "\" is not a county";
}else{
echo "\"" . $good . "\" is a county";
}
//And whatever else you want to do with the good location...
}
Like Barmar said, since you're not doing anything with the input value except for comparing it to an array, there's no risk of an attack in that way.