<?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
.
Related
I have this code -
$previous_date = date('Y-m-d',strtotime("-14 days"));
$conn = testdb_connect ();
$getfamilydate= get_family_date ($previous_date);
if (! $row)
{
echo "No testcase being executed in the selected duration";
} else { while($row = $getfamilydate->fetch(PDO::FETCH_ASSOC))
{
foreach($row as $key)
{
$twoWeekfamily[] = $key;
}
}
}
Here I am trying to check wether the query returns any result for the specified duration(previous date), and if not it should display the msg else return the array.
I have duration like -
1day, 2ay, 1week, 2 week.. etc., and I am using the same code for all the duration. This logic works fine for 1day, i.e, if no data than it shows the msg but for all others if query returns no data than it throws Undefined variable: row notice.
What is wrong with the logic here ?
Do something like -
while($row = $getfamilydate->fetch(PDO::FETCH_ASSOC))
{
foreach($row as $key)
{
$twoWeekfamily[] = $key;
}
}
if(empty( $twoWeekfamily))
{
echo "No testcase being executed in the selected duration";
}
Change you code like below
if (! $getfamilydate){
echo "No testcase being executed in the selected duration";
}
else {
$count = $getfamilydate->rowCount();
if($count > 0){
while($row = $getfamilydate->fetch(PDO::FETCH_ASSOC))
{
var_dump($row);
}
}
else{
echo "No rows found";
}
}
In your code you are checking $row before setting the values to the $row
if (!$getfamilydate->rowCount()){
echo "No testcase being executed in the selected duration";
}else { while($row = $getfamilydate->fetch(PDO::FETCH_ASSOC))
{
foreach($row as $key)
{
$twoWeekfamily[] = $key;
}
}}
Use $getfamilydate->rowCount() instead of $row in if statement.
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. =)
I'm a beginner in PHP5 and I'would like to have some help to get the code correct. Check the code and I'will be grateful for your support.
index.php:
if ($tag == 'AfficherMesAnnonce')
{
$Id_Utilisateur= $_GET['Id_Utilisateur'];
$annonce = $db->MesAnnonces($Id_Utilisateur);
if ($annonce)
{
$response["success"] = 1;
$response["annonce"]["Departure_place"] =$annonce["Departure_place"];
$response["annonce"]["Departure_date"] = $annonce["Departure_date"];
$response["annonce"]["Arrival_place"] = $annonce["Arrival_place"];
$response["annonce"]["Path_type"] = $annonce["Path_type"];
echo json_encode($response);
// annonce stored successfully
}else
{
$response["error_msg"] ="No annonce found";
return false;
echo json_encode($response);
}
}
DB_Function.php:
public function MesAnnonces($Id_Utilisateur)
{
$result = mysql_query("SELECT * FROM annonce WHERE Utilisateur_Id_Utilisateur = $Id_Utilisateur") or die(mysql_error());
// check for result
while($row = mysql_fetch_assoc($result))
{
$dd[]=$row;
}
$response=array('annonce'=> $dd);
return $response;
}
and thank you in advance.
You DB function is creating the dd array as a collection of rows, and then nesting that as an element of what's returned. But in your calling script you're assigning
$response["annonce"]["Departure_place"] = $annonce["Departure_place"]
--but the right side of that doesn't exist. You could instead assign:
$response["annonce"]["Departure_place"] = $annonce[0][0]["Departure_place"]
which would be the first row. You're not iterating through the rows in the client script, or using any kind of index to select a row.
I want to fetch the userid from my php code for this I create a class for fetch record this is my code
My database Manager Class
public function executeQuery($query) {
$result = mysql_query($query);
if ($result === false) {
$this->closeConnection($this->conn);
exit;
}
// extract data from results, returning an associative array
$rows = Array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
Class for Fetch records
function checkLogin($arr)
{
require_once(FRONT_ROOT_PATH.'DatabaseManager.php');
$query ="Select * from tbusers where username='".$arr['username']."'and
password='".$arr['password']."'";
$db= new DatabaseManager();
$result=$db->executeQuery($query);
return $result;
}
and this function i am calling here
if(isset($_POST['addlogin']))
{
$obj= new LoginManager();
$userlist=$obj->checkLogin($_POST);
if(Count($userlist)>0)
{
header('location:/ProjectDream/view/home/home.php');
}
else
{
echo "Login Failed";
}
Now from here I want to add userid in session
Please tell me how can i do it?
first session on the start of the code and replace this your code
if(Count($userlist)>0)
{
$userlist['id']=$_SESSION['your_var_name']; //setting your userid to session var
header('location:/ProjectDream/view/home/home.php');
}
<?php session_start();
if(Count($userlist)>0)
{
$_SESSION['username']=$userlist['username'];
header('location:/ProjectDream/view/home/home.php');
}
else
{
echo "Login Failed";
}
?>
You can fetch particular record from $userlist array and store it in session variable.
<?php
if(Count($userlist)>0)
{
session_start();
$_SESSION['username']=$userlist['username'];
header('location:/ProjectDream/view/home/home.php');
}
else
{
echo "Login Failed";
}
?>
<?php
include "../../settings.php";
include "$basepath/includes/conn.php";
/*$receiptnum='';*/
$submittedby='';
$statementno='';
$amount='';
$accno='';
$dateofpayment='';
if(isset($_POST['submit'])) { /*$receiptnum=$_POST['receiptnum']; */
$statementno=$_POST['statementno']; $amount=$_POST['amount'];
$accno=$_REQUEST['accountnum']; $submittedby=$_POST['submitby'];
$dateofpayment=$_REQUEST['dateofpayment']; }
/*$query= "CALL newreceipt('$reciptnum','$statementno','$amount',#doj1,'$accno','$submitedby')";*/
$query="INSERT into statement(statementno) VALUES('".$statementno."')";
$query.="INSERT into
receipt(statementno,accountnum,dateofpayment,amount,submittedby)
VALUES('".$statementno."','".$accno."','".$dateofpayment."','".$amount."','".$submittedby."')";
$result=mysqli_multi_query($con,$query); {
if($result) {
die ("An unexpected error , Please try again!");
} else {
header('Location: receipt.php');
}
}
?>
According to the official documentation, you have 2 ways to do it. Since you are not using the object oriented way, I'll nearly-copy-paste an example (from the doc, as I said) of the procedural way:
// Your queries
$query="INSERT into statement(statementno) VALUES('".$statementno."')";
$query.="INSERT into
receipt(statementno,accountnum,dateofpayment,amount,submittedby)
VALUES('".$statementno."','".$accno."','".$dateofpayment."','".$amount."','".$submittedby."')";
/* execute multi query */
if (mysqli_multi_query($con, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($con)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]); // Or whatever...
}
mysqli_free_result($result); // Free in order to store the next
}
}
} while (mysqli_next_result($con));
}