I am assigning a loop to a function so it's working fine when not enrolled in a function but when it's enrolled in function so it's not showing the echo on success please as :
function questions_query() {
global $mysqli;
global $form_name;
$questions = $_POST['questions'];
for($i=0;$i<count($questions);$i++){
$i_query = $i+1;
$query_2 = mysqli_query($mysqli,"UPDATE forms SET question$i_query='$questions[$i]' WHERE form_name='$form_name'") or die(mysqli_connect_error());
}
}
if (questions_query()) {
echo "All Questions Are Done!";
}
So if you people can please take a look at my code that what is going wrong in there..so I will be thankful to you for that please..!
The function doesn't return anything. There's no return true; or return false; statement.
If it's not successful it never returns, it calls die(), which terminates the whole script. So there's no reason to use if() around the call, just do:
questions_query();
echo 'All Questions Are Done!';
Want to use return
function questions_query() {
global $mysqli;
global $form_name;
$questions = $_POST['questions'];
for($i=0;$i<count($questions);$i++)
{
$i_query = $i+1;
$query_2 = mysqli_query($mysqli,"UPDATE forms SET question$i_query='$questions[$i]' WHERE form_name='$form_name'") or die(mysqli_connect_error());
}
return true;
}
if (questions_query()) {
echo "All Questions Are Done!";
}
else {
//something happened
}
If you want to check MySQL query result, then you need to return error check.
function questions_query() {
global $mysqli;
global $form_name;
$questions = $_POST['questions'];
$has_errors = 0;
for($i=0;$i<count($questions);$i++)
{
$i_query = $i+1;
$query_2 = mysqli_query($mysqli,"...");
if (mysqli_errno($mysqli) > 0) {
$has_errors ++;
}
}
return $has_errors;
}
$errors = questions_query();
if ($errors == 0) {
echo "All Questions Are Done!";
} else {
echo "Errors in questions: $errors times!";
}
Related
Got some code here. Been stuck on it for ages and I can't seem to get around the error.
<?PHP
error_reporting(E_ALL);
ini_set('display_errors',1);
$mysqli = new mysqli('localhost', 'username', 'password', 'table');
$statsObjects = array();
$collatedObjects = array();
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
Global $areRows;
$areRows = 2;
if( $result = $mysqli->query("SELECT * FROM stats WHERE collated = 0", MYSQLI_USE_RESULT) )
{
while($row = $result->fetch_assoc())
{
array_push($statsObjects,
new Statistic(
$row['ID'],
$row['player_GUID'],
$row['shots_fired'],
$row['shots_hit'],
$row['damage_done'],
$row['damage_taken'],
$row['friendly_damage_done'],
$row['friendly_damage_taken']
));
}
$success = true;
} //end if
$result->free_result();
if($success)
{
foreach($statsObjects as $stat)
{
$statsGuid = $stat->getGuid();
$query = "SELECT COUNT(*) AS total FROM collatedStats WHERE player_GUID = '" . $statsGuid . "'";
if( $result2 = $mysqli->query($query, MYSQLI_USE_RESULT) )
{
$value = $result2->fetch_assoc();
$rows = $value['total'];
if($rows > 0)
{
$areRows = 1;
}
else
{
$areRows = 0;
}
}
else
{
echo("Error <br/>");
echo($mysqli->error);
}
if($areRows == 1)
{
echo("Found a row! <br/>");
}
elseif($areRows == 0)
{
Echo("No rows found. =) <br/>");
}
} //end foreach
}
//OBJECT
class Statistic
{
var $GUID;
var $shotsfired;
var $shotshit;
var $damagedone;
var $damagetaken;
var $friendlydamagedone;
var $friendlydamagetaken;
var $ID;
function Statistic($ID, $GUID, $fired, $hit, $ddone, $dtaken, $fddone, $fdtaken)
{
$this->id = $ID;
$this->GUID = $GUID;
$this->shotsfired = $fired;
$this->shotshit = $hit;
$this->damagedone = $ddone;
$this->damagetake = $dtaken;
$this->friendlydamagedone = $fddone;
$this->friendlydamagetaken = $fdtaken;
}
function getID()
{
return $this->ID;
}
function getGuid()
{
return $this->GUID;
}
function getShotsFired()
{
return $this->shotsfired;
}
function getShotsHit()
{
return $this->shotshit;
}
function getDamageDone()
{
return $this->damagedone;
}
function getDamageTaken()
{
return $this->damagetaken;
}
function getFriendlyDDone()
{
return $this->friendlydamagedone;
}
function getFriendlyDTaken()
{
return $this->friendlydamagetaken;
}
function getAccuracy()
{
if($shotsfired == 0)
{
$accuracy = 0;
}
else
{
$accuracydec = $shotshit / $shotsfired;
$accuracy = $accuracydec * 100;
}
return $accuracy;
}
}
Basically every time i run the code, it keeps coming up with the error "Commands out of sync; you can't run this command now". I've spent 2 days trying to fix it - following peoples instructions about freeing the result before running the next one. I even used a prepared statement in previous code however it didn't work either - this is newly written code in an attempt to get it working. All the reading i've done suggests that this error happens when you try to run an sql command while another one is still receiving data - however i've called my first query, stored it all in an array - and then i'm looping through the array to get the next lot of data..and that's giving me an error, which is where i'm getting confused.
Any help would be appreciated!
Thank You to #andrewsi for his help - it turns out that having the MYSQLI_USE_RESULT inside SELECT * FROM stats WHERE collated = 0", MYSQLI_USE_RESULT was giving me the error. Removing that allowed me to do my code normally.
Hopefully this helps others that may have the same problem. =)
This is a really simple one, I just can't get my head around it sorry. I have this PHP code which picks up my form value, then compares it with the value stored in the database. That works fine.
However I am not sure how to write this logic in terms of this query:
If posted value = database value {
// do something } else { // do something else }
if (empty($_POST['order_id']) === false) {
// prepare data for inserting
$order_id = htmlentities(trim($_POST['order_id']));
$order_id = preg_replace("/[^0-9]/","", $order_id);
$result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
$row = mysqli_fetch_assoc($result);
echo $row['order_id'];
}
SOLVED:
Solved the question, was a silly one I know! Just needed this at the end of the code:
if($order_id === $row['order_id']) {
echo 'found';
} else {
echo 'not found';
}
Try
If ($result->num_rows === 1) { do something } else { do something else }
Since you did the business logic in your query you can just use
if( ! is_null($row)) {
// do
} else {
// nothing
}
Did I read too much into "If posted value = database value "? Are you just referring to the order_id?
if ($row['listingName'] == $_POST['frm_listingName']) {
// something
}
else {
//something else
}
Check this code:
if (empty($_POST['order_id']) === false) {
// prepare data for inserting
$order_id = htmlentities(trim($_POST['order_id']));
$order_id = preg_replace("/[^0-9]/","", $order_id);
$result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
if(mysqli_num_rows($result)>0)
{
//Match found. do something.
}
else
{
//No match found. do something.
}
}
N.B. In place of mysqli_num_rows($result) you can also use $result->num_rows
I've to check whether the end user is admin or not, I've done right (I hope) but it fails to check. Here is what I'm using;
function checked_already($pid,$input)
{
global $db;
if ($mybb->user['usergroup'] != "4")
{
error_no_permission();
}
$query = $db->simple_select("users", "username", "uid='{$input}' OR username='{$input}'");
$user = $db->fetch_array($query);
if (!$user['username'])
{
echo "Nothing found!!";
exit;
}
}
But it fails to check if the end user is admin. :/ No error at all. What is missing here?
You've not used $mybb in global. Try this;
function checked_already($pid,$input)
{
global $db, $mybb;
if ($mybb->user['usergroup'] != "4")
{
error_no_permission();
}
$query = $db->simple_select("users", "username", "uid='{$input}' OR username='{$input}'");
$user = $db->fetch_array($query);
if (!$user['username'])
{
echo "Nothing found!!";
exit;
}
}
I have a function that tells me if an email is in or not in the database. What I would like to know if it is found how could I also pass the variables like id,name etc along with it for the particular email that has been found in the DB.
function candidateInsert()
{
if($this->checkEmail($email))
{
echo 'found in db';
echo $email['id'];
}else{
echo 'error';
}
}
function checkEmail($email)
{
$email = $POST('Email');
if($email)
{
$candemail ="SELECT * FROM {table} WHERE email=?",$email"";
if(isset($candemail['email']))
{
return TRUE;
} else {
return FALSE;
}
}
}
if you want to echo something of the mail, you need to return the values from CheckMail() function, as like this:
function candidateInsert() {
$newmail = $this->checkEmail($email);
if($newmail != FALSE ) {
echo 'found in db';
echo $newmail['id'];
}else{
echo 'error';
}
}
function checkEmail($email)
{
$email = $POST('Email');
if($email)
{
$candemail ="SELECT * FROM {table} WHERE email=?",$email"";
$result = result($candemail ) // Don't know which sql functions u use
if(isset($result['email'])) {
return $result;
} else {
return FALSE;
}
}
}
I will assume that aside from boolean value, you also want to return the id and name. In this case, pass parameters by reference:
function candidateInsert()
{
$id = "";
$name;
if($this->checkEmail($email, $id, $name))
{
echo 'found in db';
echo $id;
echo $name;
}else{
echo 'error';
}
}
function checkEmail($email, &$id, &$name)
{
$email = $POST('Email');
if($email)
{
$candemail ="SELECT * FROM {table} WHERE email=?",$email"";
if(isset($candemail['email']))
{
$id = $candemail['id'];
$name = $candemail['name'];
return TRUE;
} else {
return FALSE;
}
}
}
By adding & at the beginning of the parameter, you can edit the content of the variables you pass as argument.
<?php
$mysqli=mysqli_connect("localhost","root","","politicalforum");
$query="SELECT query_title FROM administrator";
$query.="SELECT thread_id FROM threads";
if($mysqli->multi_query($query))
{
do
{
if($result=$mysqli->store_result())
{
while($row=$result->fetch_row())
{
printf("%s\n",$row[0]);
}
$result->free();
}
if($mysqli->more_results())
{
print("-------------------------------");
}
}while($mysql->next_result());
}
$mysqli->close();
?>
It doesnt work.. it doesnt go to the first if condition that identifies if it is a multiquery..
I have other question, ..why are multi_query() is useful..,
UPDATE:
Strict Standards: mysqli::next_result() [mysqli.next-result]: There is
no next result set. Please, call
mysqli_more_results()/mysqli::more_results() to check whether to call
this function/method in C:\xampp\htdocs\PoliticalForum2\test.php on
line 42
SOLVED:
<?php
$mysqli=mysqli_connect("localhost","root","","politicalforum");
$query="SELECT query_title FROM administrator;";
$query.="SELECT thread_id FROM threads;";
if($mysqli->multi_query($query))
{
do
{
if($result=$mysqli->store_result())
{
while($row=$result->fetch_row())
{
printf("%s<br/>",$row[0]);
}
$result->free();
}
if($mysqli->more_results())
{
print("-------------------------------<br/>");
}
else
{
echo '<br/>';
}
}while($mysqli->more_results() && $mysqli->next_result());
}
$mysqli->close();
?>
You need a semicolon at the end of the first query.
$query="SELECT query_title FROM administrator;";
$query.="SELECT thread_id FROM threads";
mysqli::multi_query
The reason why you get this warning, is simply because you use a do...while loop that evaluates the condition after running the command block. So when there are no more results, the contents of the loop are ran one additional time, yielding that warning.
Using a while ($mysql->next_result())...do loop should fix this. (On a general note: Using post-test loops like you did is quite uncommon in database programming)
If code is poetry, I am trying to be Shakespeare!
You can fix it like this:
if ($res) {
do {
$mycon->next_result(); //// instead of putting it in a while, put it here
if ($result = $mycon->store_result()) {
while ($row = $result->fetch_row()) {
foreach ($row as $cell)
$flag = $cell;
}
///$result->close();
}
$sale=$sale+1;
} while ($sale > 2);
}
I got the answer for the same.
please find my function below.
public function executeStoredProcedureMulti($strQuery)
{
$yml = sfYaml::load(sfConfig::get('sf_config_dir').'/databases.yml');
$params = $yml['all']['doctrine']['param'];
$dsnName = $params['dsn'];
$arrDsn = explode(";",$dsnName);
$hostName = explode("=",$arrDsn[0])[1];
$schemaName = explode("=",$arrDsn[1])[1];
$this->dbconn = mysqli_connect($hostName, $params['username'], $params['password'], $schemaName);
//return if connection was created successfully
if($this->dbconn)
{
mysqli_set_charset($this->dbconn,"utf8");
//return true;
}
else
{
$this->nErrorNumber = mysqli_connect_errno();
$this->strErrorDesc = mysqli_connect_error();
return false;
}
//check if connection exists
if($this->dbconn)
{
/* close connection */
//execute the query
if($this->dbconn->multi_query($strQuery))
{
//create table array in dataset object
$dataSet = array();
do {
//store first result set
if ($result = $this->dbconn->store_result())
{
//create data table passing it the column data
$dataTable = new CDataTable($result->fetch_fields());
//parse through each row
while ($row = $result->fetch_row())
{
$dataTable->AddRow($row);
}
$result->free();
$dataSet[] = $dataTable;
}
if (!$this->dbconn->more_results()) {
break;
}
} while ($this->dbconn->next_result());
$this->dbconn->close();
//return the complete dataset
return $dataSet;
}
else//save the error to member variables
{
$this->nErrorNumber = $this->dbconn->errno;
$this->strErrorDesc = $this->dbconn->error;
}
}
return false;
}
This is working Need to create a Class CTableData. Please make one and it will work great
.