php stored procedure error while in query - php

Here's the code:
<?php
$sql = mysql_query($db, "CALL selectproducts()");
if( $sql === FALSE ) {
die('Query failed returning error: '. mysql_error());
} else {
while($row=mysql_fetch_array($sql))
{
$id=$row['prodname'];
$name=$row['proddescription'];
$desc=$row['prodsupplier'];
$supp=$row['proddate'];
$date=$row['prodprice'];
$qtyleft=$row['prodquantity'];
Getting this Error:
Warning: mysql_query() expects parameter 2 to be resource, string given in C:\xampp\htdocs\inventory\tableedit.php on line 166
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in C:\xampp\htdocs\inventory\tableedit.php on line 170
Why is it has errors when in fact i have no parameters in call procedure?

Should be:
mysql_query("CALL selectproducts()", $db);
Documentation
Note that the mysql_ functions are now depreciated.

Try this method:
<?php
$link = mysqli_init();
mysqli_options($link, MYSQLI_INIT_COMMAND, "SET AUTOCOMMIT=0");
mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5);
mysqli_real_connect($link, $hostname, $username, $password, $dbName);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "CALL simpleproc()";
if (mysqli_real_query($link,$query)) {
if ($result2 = mysqli_store_result($link)) {
while ($row = mysqli_fetch_assoc($result2)) {
$q = $row["login"];
echo $q;
}
}
}
mysqli_close($link);
?>

I do believe you're getting your mysql_query arguments getting mixed up, where was $db is the second parameter, and the first is the MySQL query to be executed.
Although furthermore, you're probably better off using mysqli instead for future proofing:
<?php
$mysqli = new mysqli('username', 'username', 'password', 'database' );
$result = $mysqli->query("CALL selectproducts()");
if( !$result ) {
die('Query failed returning error: '. $mysqli->connect_errno );
} else {
while( $row = $result->fetch_array(MYSQLI_ASSOC)) {
$id = $row['prodname'];
$name = $row['proddescription'];
$desc = $row['prodsupplier'];
$supp = $row['proddate'];
$date = $row['prodprice'];
$qtyleft = $row['prodquantity'];
}
}
?>
From checking the mysqli PHP Docs for calling stored procedure:
<?php
/**
* Prepare Stored Procedure
**/
if (!($result = $mysqli->prepare("CALL selectproducts()"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$result->execute()) {
echo "Execute failed: (" . $result->errno . ") " . $result->error;
}
/**
* Iterate through each result
**/
do {
if ($res = $result->get_result()) {
printf("---\n");
var_dump(mysqli_fetch_all($res));
mysqli_free_result($res);
} else {
if ($result->errno) {
echo "Store failed: (" . $result->errno . ") " . $result->error;
}
}
} while ($result->more_results() && $result->next_result());
?>

Related

mysqli::query() expects parameter 1 to be string in PHP

I have below Query in my Php, it outputs result but at the same time giving an error mysqli::query() expects parameter 1 to be string what is wrong in below code
$con = #mysqli_connect("localhost","$dbname","$dbpass","$dbuser");
if (!$con)
{
die('Connect Error: ' . mysqli_connect_error());
}
$sql_uid=$con->prepare("SELECT id From $dtUsi Where mobile_number='$umobile' and user_type='$user_type'");
$stmti = $con->query($sql_uid);
while($rowi = $stmti->fetch_assoc()) {
$ur_id= $rowi['id'];
}
echo $ur_id;
You can't use prepare and query at the same time. You are giving $sql_uid to query function like it's a query string while it isn't. Use one the these approaches.
Either
$con = #mysqli_connect("localhost","$dbname","$dbpass","$dbuser");
if (!$con)
{
die('Connect Error: ' . mysqli_connect_error());
}
$stmti=$con->query("SELECT id From $dtUsi Where mobile_number='$umobile' and user_type='$user_type'");
while($rowi = $stmti->fetch_assoc()) {
$ur_id= $rowi['id'];
}
echo $ur_id;
or
$con = #mysqli_connect("localhost","$dbname","$dbpass","$dbuser");
if (!$con)
{
die('Connect Error: ' . mysqli_connect_error());
}
$stmti=$con->prepare("SELECT id From $dtUsi Where mobile_number='?' and user_type='?'");
$stmt->bind_param("ss", $umobile, $user_type);
$stmt->execute();
while($rowi = $stmti->fetch_assoc()) {
$ur_id= $rowi['id'];
}
echo $ur_id;
These links might be helpful:
PHP MySQL Prepared Statements
Select Data With MySQLi

Could not be able to print Mysqli query result in php

I want to print result of a Mysqli query, But when I try to do as following way, It does not return any values or error. The code does not go through the while loop. What would be the wrong with my code, Please help me!
<?php
$mysqli = new mysqli("localhost", "root", "", "domains");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$part = explode(".", $str);
$part1 = $part[0];
$part2 = $part[1];
$sql = "SELECT
DomainCategory.Name
FROM
DomainName_Client,
DomainNameType,
DomainCategory,
OrderDomain_Client
WHERE
DomainName_Client.Name = '$part1'
AND DomainNameType.Name = '$part2'
AND DomainName_Client.TypeID = DomainNameType.ID
AND DomainCategory.ID = DomainName_Client.DomainCategoryID
AND OrderDomain_Client.DomainNameID = DomainName_Client.ID";
$result = $mysqli->query($sql);
if (!$result = $mysqli->query($sql)) {
die('There was an error running the query ' . $mysqli->error . ']');
}
while ($row = $result->fetch_assoc()) {
echo 'Total results: ' . $result->num_rows;
}
?>
First you check the number of results returning in the sql query using the following code and after that you print it using while or for loop.
echo $result->num_rows;

Warning: mysqli_query(): Couldn't fetch mysqli in my code

I know this question has been asked many times , I tried lot of other answers but it didn't work for me
Here is my class
<?php
class saveexceltodb
{
var $inputFileName;
var $tableName;
var $conn;
var $allDataInSheet;
var $arrayCount;
/**
* Create a new PHPExcel with one Worksheet
*/
public function __construct($table=0)
{
$this->initiatedb();
}
private function initiatedb(){
//var_dump($allDataInSheet);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyx";
// Create connection
$this->conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$this->conn) {
die("Connection failed: " . mysqli_connect_error());
}
}
public function updateIntermidiate(){
$allocationeventwise=array();
mysqli_query($this->conn,"DELETE FROM `allocationeventwise` WHERE 1");
$sql = "INSERT INTO `allocationeventwise` (`empid`, `event1`, `event2`, `event3`, `event4`, `event5` `event6`, `event7`) VALUES ";
$result = mysqli_query($this->conn, "SELECT usdeal.empid , usdeal.event1 , usdeal.event2, usdeal.event3, usdeal.event4, usdeal.event5, usdeal.event6, usdeal.event7 , salary.salary from usdeal INNER JOIN salary ON usdeal.empid = salary.empid where usdeal.allocated=0");
$i=0;
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$i++;
$totaleventDays = $row["event1"]+$row["event2"]+$row["event3"]+$row["event4"]+$row["event5"]+$row["event6"]+$row["event7"];
$allocationeventwise[$row["empid"]]['event1']=($row['salary']/$totaleventDays)*$row["event1"];
$allocationeventwise[$row["empid"]]['event2']=($row['salary']/$totaleventDays)*$row["event2"];
$allocationeventwise[$row["empid"]]['event3']=($row['salary']/$totaleventDays)*$row["event3"];
$allocationeventwise[$row["empid"]]['event4']=($row['salary']/$totaleventDays)*$row["event4"];
$allocationeventwise[$row["empid"]]['event5']=($row['salary']/$totaleventDays)*$row["event5"];
$allocationeventwise[$row["empid"]]['event6']=($row['salary']/$totaleventDays)*$row["event6"];
$allocationeventwise[$row["empid"]]['event7']=($row['salary']/$totaleventDays)*$row["event7"];
$sql .='("'.$row["empid"].'",
'.$allocationeventwise[$row["empid"]]["event1"].',
'.$allocationeventwise[$row["empid"]]["event2"].',
'.$allocationeventwise[$row["empid"]]["event3"].',
'.$allocationeventwise[$row["empid"]]["event4"].',
'.$allocationeventwise[$row["empid"]]["event5"].',
'.$allocationeventwise[$row["empid"]]["event6"].',
'.$allocationeventwise[$row["empid"]]["event7"].',)';
if($i<mysqli_num_rows($result))
$sql .=",";
else
$sql .=";";
}
echo $sql;
if (mysqli_query($this->conn, $sql)) {
echo "New record created successfully<br/>";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($this->conn);
}
} else {
echo "0 results";
}
}
}
When I use it like this
include('saveexceltodb.php');
$obj = new saveexceltodb(0);
$obj->updateIntermidiate();
I get following error .
Warning: mysqli_query(): Couldn't fetch mysqli in C:\xampp\htdocs\import-excel\saveexceltodb.php
You should follow below steps
Check database connection
Check query syntax
You have to pass connection object in mysqli_query function in you case it is ' $this->conn '
Hope, It may help you.

PHP variable scope issue with mysqli

I am still learning PHP and I'm trying to get around this error I'm getting.
As per this link my code is correct, but this is my code and this is the error i'm receiving:
$con = mysqli_connect("IP","username","passowrd","dbname");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function get_demos(){
$result = mysqli_query($con,"SELECT * FROM demos");
if(!$result)
{
die("Invalid query ".mysqli_error($con));
}
return $result;
}
get_demos();
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/content/83/11483383/html/php/db.php on line 10
Warning: mysqli_error() expects parameter 1 to be mysqli, null given
in /home/content/83/11483383/html/php/db.php on line 13 Invalid query
What am I doing wrong?
Thanks.
You should try like,
$con = mysqli_connect("IP","username","passowrd","dbname");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function get_demos($con){
$result = mysqli_query($con,"SELECT * FROM demos");
if(!$result)
{
die("Invalid query ".mysqli_error($con));
}
return $result;
}
get_demos($con);
You are not declaring that a variable $con is already set.
Try this one
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, 'databse_name_here') or die ('Failed to connect to MySQL: ' . mysqli_connect_error());
function get_demos($con){
$result = mysqli_query($con,"SELECT * FROM users");
if(!$result)
{
die("Invalid query ".mysqli_error($con));
}
return $result;
}
get_demos($con);
You have to pass your connection to your function. if you don't want to do it every time you can use singleton pattern to always have it in scope.
class DBCon {
private static $_instance = null;
private function __construct() {
$_instance = mysqli_connect("IP","username","passowrd","dbname");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
public static function get() {
if(is_null(self::$_instance)) {
self::$_instance = new DBCon();
}
return self::$_instance;
}
}
and use it in your code :
function get_demos(){
$result = mysqli_query(DBCon::get(),"SELECT * FROM demos");
if(!$result)
{
die("Invalid query ".mysqli_error(DBCon::get()));
}
return $result;
}
I figured out the solution after putting the question:
$con = mysqli_connect("IP","username","passowrd","dbname");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function get_demos(){
global $con;
$result = mysqli_query($con,"SELECT * FROM demos");
if(!$result)
{
die("Invalid query ".mysqli_error($con));
}
return $result;
}
get_demos();
By adding global $con.

PHP while loop never exits

I have a while loop inside a foreach loop. The while loop never exits and crashes the server, I can't figure out why. Here's a condensed version of the code.
foreach( $final_plates as $key => $value) {
$Plate_No = ($value['plate_no']);
$sql = "SELECT J.PLATE_NO FROM PLATE_LOGS J WHERE (J.PLATE_NO = " . $Plate_No . ")";
$db->query($sql);
while ($row = oci_fetch_assoc($db2->result)) {
echo $row['PLATE_NO'] . "</br>";
}
}
If I use the following statement instead of the while loop, the first record will be found without any problem
$row = oci_fetch_assoc($db->result);
I am using a class to connect to the database that I didn't write. I'm also new to programming. Here's some code from the class.
function connect(){
$this->connection = oci_connect($this->user, $this->password, $this->db) or die("Connection Failed: " . oci_error());
if(!$this->connection)
{
return false;
}
}
function query($sql){
// Query SQL
$this->result = oci_parse($this->connection, $sql) or die ("SQL ERROR" . oci_error($this->connection));
oci_execute($this->result) or die ("SQL ERROR" . oci_error($this->result));
}

Categories