IF Statement Inside Function - php

I am writing a if statement that if the two dates listed are equal it echo's the first date and if the they aren't(else statement) it echoes "date1-date2" I have it inside a function and I do not know if I am alowed to do that.Here is the error I am getting
Parse error: syntax error, unexpected T_IF
Here is my function:
function getfevent ($conn) {
$sql = "SELECT `name` FROM `event` WHERE `featured` = 0 LIMIT 0, 30 ";
$statement=$conn->prepare($sql);
$statement->execute();
while($row=$statement->fetch()) {
$eventname = $row['name'];
$row_id=geteventid ($conn,$eventname);
$row_end=geteventend ($conn,$eventname);
$date=if ($row_id == $row_end){
echo $row_id;
}
else {
echo $row_id " - " $row_end;
}
?>
<?php echo "<td>$eventname</td><td>$date</td></tr>"; ?>
<?php
}
}
getfevent($conn);

Probably you want this.
$date = $row_id == $row_end ? $row_id : $row_id . " - " . $row_end;
echo $date;
Don't forget. Use . to concat.
It's the same of
if ($row_id == $row_end) {
$date = $row_id;
} else {
$date = $row_id . " - " . $row_end;
}

Yes, of course If statements are allowed inside functions. Your problem is that you are setting your variable $date's value to the value of a T_IF, which is illegal.
Rather, you could do something like this:
$date=($row_id == $row_end);
if($date)
{
echo $row_id;
}
else {
echo $row_id." - ".$row_end;
}

Instead of:
$date=if ($row_id == $row_end){
echo $row_id;
}
else {
echo $row_id " - " $row_end;
}
Try:
$date;
if ($row_id == $row_end)
$date=$row_id;
else
$date=$row_id." - ".$row_end;
What you're doing in the original code is essentially telling PHP to set the value of variable $date to an if statement, which is, well, not possible.
The alternate piece of code creates a new variable $date, and then sets its value to $row_id or $row_id." - ".$row_end; depending on how the if statement evaluates.

The echo statement is used to print something to the output buffer.
you have to do this instead:
if ($row_id == $row_end) {
$date = something
} else {
$date = somethingElse
}
//do whatever you want with $date

try
$date=$row_id;
if ($row_id != $row_end)
{
$date.=" - ".$row_end;
}
which should be much shorter i gues

Related

Repeat an if/elseif/else to completion

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.

Php flip the echo result

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

php while loop running only once

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.

PHP verification data error

I have an problem with my PHP verification data.
This my code so far
$cek_saldo=mysql_query
("SELECT * FROM t_balance");
while ($data_cek = mysql_fetch_array($cek_saldo));
{
$b_id = $data_cek['badge_id'];
$mon = $data_cek['month'];
$bal = $data_cek['balance_type'];
}
if ($b_id == '$badge_id' AND $mon == '$date_month' AND $b_type == '$jns_saldo')
{
echo "<div class='emp_err warn'>Balance for this month has been added before.</div>";
}
else
{
if($_POST)
{
$query = "INSERT INTO t_balance(badge_id, balance_amount, month, balance_type, date_transaction)
VALUES ('$badge_id', '$saldo', '$bulan', '$jns_saldo', '$date_transaction')
";
$hasil = mysql_query($query);
if($hasil)
{
echo "<div class='emp_err success'>Balance transaction successfully added.</div>";
}
else
{
echo "<div class='emp'>Gagal menambahkan saldo.</div>";
}
}
}
The rule is :
Tabungan Wajib can be submit for 1 time per month. So if twice, it will give error : "Balance for this month has been added before."
Tabungan Tambahan can be submit more than 1 time per month. So if submit more than 1 time, it will saved.
Anyone have a suggestions ?
if ($b_id == "$badge_id" AND $mon == "$date_month" AND $b_type == "$jns_saldo")
{
echo "<div class='emp_err warn'>Balance for this month has been added before.</div>";
}
Your code failed due to the single quotes in the comparison using variables try to learn the difference between single and double quoted strings in php
You don't need to quote.I suppose $badge_id $date_month $jns_saldo come from your form with $_POST
if ($b_id == $badge_id AND $mon == $date_month AND $b_type == $jns_saldo)
This validation will no work
reason being you are selecting multiple rows from database and assigning only the last on e to $b_id .. $mon etc
and you are using single quotes for comparison
RESOLUTION
select data based on some id if you can
$cek_saldo=mysql_query("SELECT * FROM t_balance where id = 'someid'");
while ($data_cek = mysql_fetch_array($cek_saldo));
{
$b_id = $data_cek['badge_id'];
$mon = $data_cek['month'];
$bal = $data_cek['balance_type'];
}
set the error flag
$error = false;
while ($data_cek = mysql_fetch_array($cek_saldo));
{
$b_id = $data_cek['badge_id'];
$mon = $data_cek['month'];
$bal = $data_cek['balance_type'];
if($b_id == $badge_id AND $mon == $date_month AND $b_type == $jns_saldo)
{
$error = true;
break
}
}
if($error)
{
echo "<div class='emp_err warn'>Balance for this month has been added before.</div>";
}
Hope it helps
Use this.
$cek_saldo= mysql_query("SELECT * FROM t_balance");
while ($data_cek = mysql_fetch_array($cek_saldo));
{
$b_id = $data_cek['badge_id'];
$mon = $data_cek['month'];
$bal = $data_cek['balance_type'];
if ($b_id == "$badge_id" && $mon == "$date_month" && $b_type == "$jns_saldo")
{
echo "<div class='emp_err warn'>Balance for this month has been added before.</div>";
}
else
{
if($_POST)
{
$query = "INSERT INTO t_balance(badge_id, balance_amount, month, balance_type, date_transaction)
VALUES ('".$badge_id."', '".$saldo."', '".$bulan."', '".$jns_saldo."', '".$date_transaction."')";
$hasil = mysql_query($query);
if($hasil)
{
echo "<div class='emp_err success'>Balance transaction successfully added.</div>";
}
else
{
echo "<div class='emp'>Gagal menambahkan saldo.</div>";
}
}
}
}

Javascript confirm() function cannot pass parameters properly

I'm using PHP and JavaScript, and I got a problem when deal with the confirm() function in JavaScript.
Say I have a page add.php, firstly I receive some parameters passed from another page, and I check to see if they are valid or not. If yes, I just insert the data into db and return to another page, if they are not valid, there'll be a confirm() window popped up and let the user to choose whether to continue or not. If the user still choose to continue, I want the page to be reloaded with all the parameters sent again. But the problems is that I cannot get the parameter the second time add.php is loaded.
Previously I didn't use a window.onload function and confirm() pop up, but an < a href> link instead, everything worked fine (Please see the attached code at the end). But when I tried to use the following code, the same url stopped working
echo "<script type=\"text/javascript\">";
echo "window.onload = function() {
var v = confirm(\"$name is not alive, do you want to add it into system?\");
if (v) {
window.location.href= \"add.php?type=room&name=$name&area\"
+ \"=$area&description=$description&\"
+ \"capacity=$capacity&confirm=Y\";
} else {
window.location.href= \"admin.php?area=$area\";
}
}";
echo "</script>";
Following is the previous version, instead of using window.onload(), I used < a href="..." /> link, everything worked fine at that time. get_form_var is a function in functions.inc, which is to get the parameter using $_GET arrays.
<?php
require_once "functions.inc";
// Get non-standard form variables
$name = get_form_var('name', 'string');
$description = get_form_var('description', 'string');
$capacity = get_form_var('capacity', 'string');
$type = get_form_var('type', 'string');
$confirm = get_form_var('confirm','string');
$error = '';
// First of all check that we've got an area or room name
if (!isset($name) || ($name === ''))
{
$error = "empty_name";
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location: $returl");
}
// we need to do different things depending on if its a room
// or an area
elseif ($type == "area")
{
$area = mrbsAddArea($name, $error);
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location: $returl");
}
elseif ($type == "room")
{
if (isset($confirm)){
$dca_osi = getOsiVersion($name);
$room = mrbsAddRoom(
$name,
$area,
$error,
$description,
$capacity,
$dca_osi,
1
);
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location:$returl");
}
else {
$dca_status= pingAddress($name);
$dca_osi = getOsiVersion($name);
if( $dca_status == 0){
$room = mrbsAddRoom(
$name,
$area,
$error,
$description,
$capacity,
$dca_osi,
0
);
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location:$returl");
}
else {
print_header(
$day,
$month,
$year,
$area,
isset($room) ? $room : ""
);
echo "<div id=\"del_room_confirm\">\n";
echo "<p>\n";
echo "$name is not alive, are you sure to add it into system?";
echo "\n</p>\n";
echo "<div id=\"del_room_confirm_links\">\n";
echo "<a href=\"add.php?type=room&name"
. "=$name&area=$area&description"
. "=$description&capacity=$capacity&confirm"
. "=Y\"><span id=\"del_yes\">"
. get_vocab("YES") . "!</span></a>\n";
echo "<a href=\"admin.php?area=$area\"><span id=\"del_no\">"
. get_vocab("NO") . "!</span></a>\n";
echo "</div>\n";
echo "</div>\n";
}
}
}
function pingAddress($host)
{
$pingresult = exec("/bin/ping -c 1 $host", $outcome, $status);
if ($status==0) {
return $status;
}
else {
return 1;
}
}
function getOsiVersion($host)
{
$community = 'public';
$oid = '.1.3.6.1.4.1.1139.23.1.1.2.4';
$sysdesc = exec("snmpwalk -v 2c -c $community $host $oid");
$start = strpos($sysdesc, '"');
if ($start!==false) {
$sysdesc = substr($sysdesc, $start+1,$sysdesc.length-1);
return $sysdesc;
}
else {
return "not available";
}
}
I've solved the problem, just simply by using "&" instead of " & amp;" in the url link... it works fine now...
You try location.reload() javascript call?

Categories