Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm not 100% comfortable with a PHP class defined here: mysqli
I stripped out the guts to shorten it somewhat and get a parse error at runtime.
<?php
function query($x)
{
if ($x > 8) {
return 'greater than eight!';
} else {
return true;
}
} else {
exit();
}
}
print query(7);
It's the same construct (I think) as the original, isn't it? Apart from the signature and the body of the method of course. I haven't come across an if else else clause before and it somehow doesn't 'feel right' for me at least logically wise. Moreover my code won't compile. Maybe you can set me straight?
Do you have any examples of how it may be used?
Secondly, from the original class - where or how does the $resource variable come into it? In what context would the object get passed a $resource variable?
My client code may be:
$db = new MySQLi;
$db->query("SELECT * FROM my_table");
but I don't see how $resource comes into play?
I assume you're trying to do something different but I hope this helps to explains how you can tie three conditions together.
function query($x) {
if ($x > 8) { // If $x is greater than 8
return 'greater than eight!';
} else if ($x < 8) { // If $x is lower than 8
return true;
} else {
return "The number is 8!";
}
}
print query(7);
You have a second else construct, it should look like:
if($x > 8) {
// your if(true) code
} else {
// your if(false) code
}
there is a missing if else block which is highlighted with ** here that's y you are getting the parser error as same is the problem with your code
<?php
final class MySQLi {
private $mysqli;
public function __construct($hostname, $username, $password, $database) {
$this->mysqli = new mysqli($hostname, $username, $password, $database);
if ($this->mysqli->connect_error) {
trigger_error('Error: Could not make a database link (' . $this->mysqli->connect_errno . ') ' . $this->mysqli->connect_error);
}
$this->mysqli->query("SET NAMES 'utf8'");
$this->mysqli->query("SET CHARACTER SET utf8");
$this->mysqli->query("SET CHARACTER_SET_CONNECTION=utf8");
$this->mysqli->query("SET SQL_MODE = ''");
}
public function query($sql) {
$result = $this->mysqli->query($sql);
if ($this->mysqli->errno) {
//$mysqli->errno
}
if (is_resource($resource)) {
$i = 0;
$data = array();
while ($row = $result->fetch_object()) {
$data[$i] = $row;
$i++;
}
$result->close();
$query = new stdClass();
$query->row = isset($data[0]) ? $data[0] : array();
$query->rows = $data;
$query->num_rows = $result->num_rows;
unset($data);
return $query;
} else {
return true;
}
***} else {
trigger_error('Error: ' . mysql_error($this->link) . '<br />Error No: ' . mysql_errno($this->link) . '<br />' . $sql);
exit();
}***
}
public function escape($value) {
return $this->mysqli->real_escape_string($value);
}
public function countAffected() {
return $this->mysqli->affected_rows;
}
public function getLastId() {
return $this->mysqli->insert_id;
}
public function __destruct() {
$this->mysqli->close();
}
}
?>
There is something missing in your code. If you someone runs your code.
Parse error: syntax error, unexpected T_ELSE on line 8
So your function should look like below
function query($x)
{
if ($x > 8)
{
//runs when $x value is greater than 8
return 'greater than eight!';
}
else
{
// if the condition didnt meet, according to my knowledge you should return false here
return true;
}
exit();
}
print query(7);
If you want to have a else if,
if (condition)
{
code to be executed if condition is true;
}
else if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
Related
I have a controller working like this'
public function indexAction() {
// some stuff cut out
$openEntries = $this->checkOpenEntries($position);
if($openEntries === 0) {
//do some stuff
}
elseif ($openEntries === -1) {
//Sends email to notify about the problem
$body = 'Tried to create position log entry but found more than 1 open log entry for position ' . $position->getName() . ' in ' . $position->getACRGroup()->getName() . ' this should not be possible, there appears to be corrupt data in the database.';
$this->email($body);
return new response($body . ' An automatic email has been sent to it#domain.se to notify of the problem, manual inspection is required.');
} else {
//do some other stuff
}
}
private function checkOpenEntries($position) {
//Get all open entries for position
$repository = $this->getDoctrine()->getRepository('PoslogBundle:Entry');
$query = $repository->createQueryBuilder('e')
->where('e.stop is NULL and e.position = :position')
->setParameter('position', $position)
->getQuery();
$results = $query->getResult();
if(!isset($results[0])) {
return 0; //tells caller that there are no open entries
} else {
if (count($results) === 1) {
return $results[0]; //if exactly one open entry, return that object to caller
} else {
return -1; //if more than one open entry, null will signify to caller that we have a problem.
}
}
}
But I would like to put that response-returning-business already in the private function to clean up my indexAction, but that is not possible, the indexAction will keep going past the point of
$openEntries = $this->checkOpenEntries($position);
even if checkOpenEntries attempts to return a HTTP response.
Ideally I would like it to look like this, is there a way to accomplish that:
public function indexAction() {
// some stuff cut out
$openEntries = $this->checkOpenEntries($position);
if($openEntries === 0) {
//do some stuff
} else {
//do some other stuff
}
}
private function checkOpenEntries($position) {
//Get all open entries for position
$repository = $this->getDoctrine()->getRepository('PoslogBundle:Entry');
$query = $repository->createQueryBuilder('e')
->where('e.stop is NULL and e.position = :position')
->setParameter('position', $position)
->getQuery();
$results = $query->getResult();
if(!isset($results[0])) {
return 0; //tells caller that there are no open entries
} else {
if (count($results) === 1) {
return $results[0]; //if exactly one open entry, return that object to caller
} else {
//Sends email to notify about the problem
$body = 'Tried to create position log entry but found more than 1 open log entry for position ' . $position->getName() . ' in ' . $position->getACRGroup()->getName() . ' this should not be possible, there appears to be corrupt data in the database.';
$this->email($body);
return new response($body . ' An automatic email has been sent to it#domain.se to notify of the problem, manual inspection is required.');
}
}
}
IMHO, it is not clean the way you mix up the type of method. However, you could do something like this, to make it work.
In addition, I think it would be better if functions and parameters have type, it would be easier to read.
public function indexAction() {
// some stuff cut out
$openEntries = $this->checkOpenEntries($position);
if ($openEntries instanceOf Response) return $openEntries;
if($openEntries === 0) {
//do some stuff
} else {
//do some other stuff
}
// you might also want to add some response here!
return new Response('...');
}
Let's say I have a simple code:
while(1) {
myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) break;
}
This will not work with error code 'Fatal error: Cannot break/continue 1 level on line'.
So is there any possibility to terminate the loop during a subfunctin execution?
Make the loop condition depend upon the return value of the function:
$continue = true;
while( $continue) {
$continue = myend();
}
Then, change your function to be something like:
function myend() {
echo rand(0,10);
echo "<br>";
return (rand(0,10) < 3) ? false : true;
}
There isn't. Not should there be; if your function is called somewhere where you're not in a loop, your code will stop dead. In the example above, your calling code should check the return of the function and then decide whether to stop looping itself. For example:
while(1) {
if (myend())
break;
}
function myend() {
echo rand(0,10);
echo "<br>";
return rand(0,10) < 3;
}
Use:
$cond = true;
while($cond) {
$cond = myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) return false;
}
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.
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 9 years ago.
I am working on a php method that giving me a syntax error on the third line of the method body. Commenting out the line does not do anything for me. Only by commenting out the entire method, does it actually go away. Am I missing something here?
public function get(Array $array) {
if(array_key_exists('data', $array)) {
if($array['data'] == '*') {
$fieldString = '*';
} else {
$fieldString = '';
for($x=0; $x < count($array['data']); $x++) {
if($x == count($array['data']) - 1 ) {
$fieldString .= $array['data'][$x].' ';
} else {
$fieldString .= $array['data'][$x].', ';
}
}
}
if(array_key_exists('table', $array)) {
$table = $array['table'];
}
if(array_key_exists('conditions', $array)) {
$condition = $array['conditions'];
$filter = '';
foreach($condition['cond'] as $cond) {
if(array_key_exists('type', $cond)) {
$filter .= $cond['type'].' ';
}
if(array_key_exists('field', $cond)) {
$filter .= $cond['field']. ' = ';
}
if(array_key_exists('value', $cond)) {
$filter .= $cond['value'];
}
}
}
$result = $mysqli->query("SELECT ".$fieldString." FROM ".$table. " ".$filter);
$response = $result->fetch_assoc();
if(!empty($response)) {
return $response;
} else {
echo 'response array from get model is empty';
}
} else {
echo '<h3>array data not set for _get() in model </h3>';
}
}
Is the method contained within the class. Sometimes I accidentally put a class function at the end of the class file but outside the ending }. If it is not a class method, remove 'public'.
Change $mysqli->query() to $this->mysqli->query()
I am presuming you created a class method mysqli but you are calling it without '$this'.
If mysqli is the php function, it should be mysqli_query($this->token, "query")
Although, you should be getting ' Undefined variable' with this. In any event $mysqli is undefined in this method.
i m getting an error in the php code..
Fatal error: Call to undefined function msg()
but the function is already defined in the code here
whenever i click on a login button this login script runs
<?php
mysql_select_db("elunika", $con);
$a = $_POST['em'];
$b = $_POST['pwd'];
$c = $_POST['log'];
$b = md5($b);
if (isset($c)) {
$q = mysql_query("select * from registeration where email='$a' and password='$b'");
$r = mysql_num_rows($q);
if ($r) {
$_SESSION["Authenticated"] = 1;
$_SESSION['id'] = $a;
}
else {
$_SESSION["Authenticated"] = 0;
}
if ($_SESSION["Authenticated"] === 0) {
die(msg(0, "Incorrect Information"));
}
else {
session_write_close();
echo msg(1, "profile.php");
}
function msg($status, $txt)
{
return '{"status":' . $status . ',"txt":"' . $txt . '"}';
}
}
?>
Only unscoped functions are defined at compile-time (prior to execution). Your msg function however is just going to be defined if the if branch (the if (isset(…)) on line 9) is entered; so it's only going to be defined at the moment where the executor reaches it.
But in your code msg() is already called before the function declaration was encountered at run-time. Moving the function declaration up (= before the msg() call) should help:
function msg ($status, $txt) {
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
if($_SESSION["Authenticated"] === 0) {
die(msg(0,"Incorrect Information"));
} else {
session_write_close();
echo msg(1,"profile.php");
}