<?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));
}
Related
This is the 1st part of the code, plz look at the variable $Tno.
if(isset($_POST['submit']))
{
$Tno=$_POST['Tno'];
$query="SELECT * FROM docs WHERE Tno='$Tno'";
$result=mysql_query($query) or die('Data not selected');
while ($row = mysql_fetch_array($result))
{
$Tassign = $row["Tassign"];
}
}
if(isset($_POST['submit2']))
{
$ti="INSERT INTO approval(Tno, approval)values('$Tno','Approved')";
$tj=mysql_query($ti) or ('Data Not Inserted');
if($tj){
echo "All set!!!!!!!!!!!!!!!!!!!!!";
}
}
Now the problem is, I need $Tno value in this part of the code also to insert in the DB. But its storing ZERO. Any solutions??
You can do this in the following ways
1)Session
You can store data in the session and than you can use it to insert the data in the database
session_start();
if(isset($_POST['submit']))
{
$Tno=$_POST['Tno'];
$_SESSION['Tno'] = $Tno
$query="SELECT * FROM docs WHERE Tno='$Tno'";
$result=mysql_query($query) or die('Data not selected');
while ($row = mysql_fetch_array($result))
{
$Tassign = $row["Tassign"];
}
}
if(isset($_POST['submit2']))
{
$Tno = $_SESSION['Tno'];
$ti="INSERT INTO approval(Tno, approval)values('$Tno','Approved')";
$tj=mysql_query($ti) or ('Data Not Inserted');
if($tj){
echo "All set!!!!!!!!!!!!!!!!!!!!!";
}
}
2) By using GET Method
You can also use $_GET method to get the value of Tno and than you can insert into your database
if(isset($_POST['submit2']))
{
$Tno = $_GET['Tno'];
$ti="INSERT INTO approval(Tno, approval)values('$Tno','Approved')";
$tj=mysql_query($ti) or ('Data Not Inserted');
if($tj){
echo "All set!!!!!!!!!!!!!!!!!!!!!";
}
}
The problem is with the statement
$query="SELECT * FROM docs WHERE Tno='$Tno'";
instead use
$query="SELECT * FROM docs";
while ($row = mysql_fetch_array($result))
{
$Tassign=$row["Tassign"];
*// Now perform the matching*
**If ($Tassign==$Tno)**
{
*// enter your functionality here
}
}
Now the values would be fetched from database and You can perform specific operation on the data fetched
Well there are 2 ways you could go about it.
Either using GET, or Session. I don't know how you're directing over from Page 1 to 2. So I will just rather use Session to be safe.
if(isset($_POST['submit']))
{
$Tno=$_POST['Tno'];
// Store the TNO value in the session
$_SESSION['Tno'] = $Tno;
$query="SELECT * FROM docs WHERE Tno='$Tno'";
$result=mysql_query($query) or die('Data not selected');
while ($row = mysql_fetch_array($result))
{
$Tassign = $row["Tassign"];
}
}
if(isset($_POST['submit2']))
{
// Now get the TNO value here
$Tno = $_SESSION['Tno'];
$ti="INSERT INTO approval(Tno, approval)values('$Tno;,'Approved')";
$tj=mysql_query($ti) or ('Data Not Inserted');
if($tj){
echo "All set!!!!!!!!!!!!!!!!!!!!!";
}
}
i wrote a PHP Function but it does nothing at a specific point.. im new to php and my english is bad, sorry for that.
<?php
function SQLwriteRecent($id, $title, $link) {
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$count = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
if(!isset($count)) {
try {
mysqli_query($con,"INSERT INTO recent (title, link, sc_stream, count) VALUES ('$title', '$link', '$id',$count)");
mysqli_close($con);
return 1;
} catch(Exception $e) {
return 0;
}
} else {
try {
// ------ SHOW HERE!!!! ------------ //
mysqli_query($con,"UPDATE recent SET count=$count WHERE sc_stream='$id'");
mysqli_close($con);
return 2;
} catch(Exception $e) {
return 0;
}
}
}
?>
the code runs every time until a specific point (i marked it in the code with // ------ SHOW HERE!!!! ------------ //)
in the sql table, currently there is no entry. so i should create a new row
whats wrong with that code?! :(
Your script wont insert a new row, because you have defined $count, it is a mysqli_result object. You have to check if there is a row, something you could do like this;
Instead of
if(!isset($count))
use
if(mysqli_num_rows($count) == 0)
Some explanation:
You have this in your code:
if(!isset($count)) {
This checks that your variable has been set, nor is empty, false, or 0. This condition ALWAYS return true because the variable is setted in line before, use mysqli_nuw_rows instead
Combining what other people have said, and looking at the logic of what you're doing, it looks like you have a few fundamental issues:
I've tweaked some variable names to make it clearer what you're getting an peppered the code with comments that describe the issues.
I've ignored the SQL injection issues.
<?php
function SQLwriteRecent($id, $title, $link) {
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$countQuery = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
$numberOfRowsReturnedByQuery = mysqli_num_rows($count);
if ( $numberOfRowsReturnedByQuery > 0 ) {
$valueOfCountInQuery = $countQuery [0]['count'];
}
if( $numberOfRowsReturnedByQuery == 0) {
try {
// In this situation it looks like you want to set up a value in "recent" - I.E. you didn't have a record.
// But think about it for a second - if you had no record in "recent" then how could "$valueOfCountInQuery" possibly be set?
mysqli_query($con,"INSERT INTO recent (title, link, sc_stream, count) VALUES ('$title', '$link', '$id',$valueOfCountInQuery )"); // makes no sense to use "$valueOfCountInQuery" - maybe you mean "0" (zero)
mysqli_close($con);
return 1;
} catch(Exception $e) {
return 0;
}
} else {
try {
// In this situation it looks like you want to update the value in "recent" - I.E. you DID have a record and you want to change it.
// But think about it for a second - the value of "$valueOfCountInQuery" is the value that you got from "count" on "recent". You are setting it to the same value that's already in there!
// ------ SHOW HERE!!!! ------------ //
mysqli_query($con,"UPDATE recent SET count=$valueOfCountInQuery WHERE sc_stream='$id'"); // redundant
mysqli_close($con);
return 2;
} catch(Exception $e) {
return 0;
}
}
}
?>
You did a mistake here, query returns array
try this
mysqli_query($con,"UPDATE recent SET count=$count[0]['count'] WHERE sc_stream='$id'");
You have set:
count=$count
but
$count = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
Specify a proper value for count not a resource
to retrieve the actual result of the query you have to do something like
if ( $result = $con->query($sql)){ //perform the query
if ($result->num_rows == 1){
if ($row = $result->fetch_assoc()){
$count = $row['count'];
}
else{
echo "couldn't fetch result row";
}
else {
echo "expected one result row, got ".$result->num_rows;
}
}
else {
echo "query failed:".$sql;
echo $con->errno.' '.$con->error;
}
// if you have more than one result row
if ( $result = $con->query($sql))
while ($row = $result->fetch_assoc()){ //loop through the result(s)
$count = $row['count']
}
// procedural style
if ( $result = mysqli_query($con,$sql))
while($row = mysqli_fetch_assoc($result)){
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";
}
?>
Database connecting is working. The SELECT AND UPDATE FUNCTION in the class is not working at all.It is not even showing errors to help me sort out the problem. I am trying to learn how to use the prepare ,bind-param and execute statement. Please can someone help look at the codes and advise what may be wrong with it. Just spent loads of hours on this and just cant figure where the problems is. please can some help me.I am a novice and writing my very first codes . Many thanks in advance
<?php class connect_dbase{
public $mysqli;
public function connection($host="localhost",$user="root",$password="london",$db_name="users")
{
$this->mysqli=new mysqli($host,$user,$password,$db_name);
if ($this->mysqli->connect_error) {
die('Connect Error: ' . $this->mysqli->connect_error);
}
else{
echo " Database connection successful";
}
}
public function display_all($id){
if($stmt = $this->mysqli->prepare("SELECT * FROM user WHERE id =?")){
/* bind parameters for markers */
$stmt->bind_param('i',$id);
/* execute query */
$stmt->execute();
if($stmt->num_row() >0){
echo 'Total results: ' . $resultrol->num_rows;
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['name'];
echo $row['email'];
echo $row['address'];}
}
else { echo "no result found";}
}
else
{
echo "cant prepare result";
}
}
public function update_post($name, $address,$email,$mob,$id)
{
$up="UPDATE user SET name=?, address =?,email=?,mobile=? WHERE id =?";
if($stmt=$mysqli->prepare($up))
{
$stmt->bind_param("sssii", $name, $address,$email,$mob,$id);
if($stmt->excute()) {
echo " post updated";
header('location:index.php');
}
else
{
echo "post not executed";
}
}else{ echo " cannot prepare statement";}
}
}
$connect_dbase=new connect_dbase();
$connect_dbase->connection();
$connect_dbase->display_all(2);
$connect_dbase-> update_post("john","kkkkk","kkk#yahoo.com",98765,2);
// These 2 functions- $connect_dbase->display_all(2); and
$connect_dbase-> update_post("john","kkkkk","kkk#yahoo.com",98765,2); are not working when called from the class above .
?>
I agree with #MikeBrant's comments. You should make the connection happen in the constructor if you want to be assured that the connection is successful before you try to call it.
Here's another tip:
if($stmt->num_row() >0){
Note that num_rows() doesn't return anything useful until after the client has fetched the rows. So calling it right after execute() is pretty much guaranteed to make it return the wrong number.
You need to use mysqli::store_result() to transfer the result set from the server to the client, and then num_rows() will work. But be careful if the result set is very large, it could use too much memory.
Taking into account the input from Mike and Bill I have modified your code to make it functional. It could use some more work but it should give you a starting point at the very least. I created a test database with three fields, id, name and email but you should be able to plug in your own database and fields and have it still work.
<?php
class connect_dbase {
public $mysqli;
public function connection($host="localhost",$user="root",$password="",$db_name="test")
{
$this->mysqli=new mysqli($host,$user,$password,$db_name);
if ($this->mysqli->connect_error) {
die('Connect Error: ' . $this->mysqli->connect_error);
} else {
// return a true value here if successful, that way you can check
// if your connection was established
return true;
}
}
public function display_all($id){
if($stmt = $this->mysqli->prepare("SELECT * FROM test WHERE id =?")) {
// some minor changes to the bind and execute statments. I
// wrapped them in an if just to make sure there were no errors
// if i had more time i might make these more elegant rather than just
// echoing them out
/* bind parameters for markers */
if(!($stmt->bind_param('i',$id))) {
echo $stmt->error;
}
/* execute query */
if(!($stmt->execute())) {
echo $stmt->error;
}
// You could also bind the results to specific variables here and return those
//$stmt->bind_result($id,$name,$email);
//$stmt->fetch();
//$result = $name;
//assign the results to a variable and then return that variable
//rather than processing the results here
$result = $stmt->get_result();
return $result;
} else {
// if an error occurs return the error, once again another place for
// improvement but at the very least will show you an error
echo $this->mysqli->error;
}
}
public function update_post($name, $email, $id)
{
$up="UPDATE test SET name=?, email=? WHERE id =?";
// originally had $mysqli->prepare($up), fixed syntax
if($stmt = $this->mysqli->prepare($up))
{
//$stmt->bind_param("sssii", $name, $address,$email,$mob,$id);
$stmt->bind_param("ssi", $name, $email,$id);
// execute was spelled wrong
if($stmt->execute()) {
return true;
} else {
return $stmt->error;
//return false;
}
} else {
return false;
}
}
}
// set up database connection
$connect_dbase = new connect_dbase();
if($connect_dbase->connection()) {
// if connection was successful, call display_all
// and assign the results to $result
$result = $connect_dbase->display_all(2);
// you could do a foreach here also but since there
// was only one result i just echoed the values
while($row = $result->fetch_array()) {
echo $row['id'] . "<br/>";
echo $row['name'] . "<br/>";
echo $row['email'] . "<br/>";
}
// then call update_post
$update_result = $connect_dbase->update_post("asdf","asdf#yahoo.com",2);
// show a message if the update_post was successful
if($update_result) {
echo "Update successful";
}
}
?>
I commented the areas I switched around so you have an idea of what I did.
<?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
.