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
Related
I'm trying to build a basic API with PHP and mysql and depending on the url path, different database tables are used and therefore the connection needs to be made. But I keep getting this error:
Fatal error: Call to a member function prepare() on a non-object
in....line 6
dashboard.class.php:
class dashboard {
public function getData($conn) {
// Get latest status
$stmt = $conn->prepare("SELECT status FROM status_archive ORDER BY datetime DESC LIMIT 1 ");
$stmt->execute(); //line 6
$stmt->bind_result($status);
$stmt->fetch();
($status == '1' ? $status = 'up' : $status = 'down');
$stmt->close();
return $status;
}
}
Function that creates the database connection:
function db_connection($type) {
$db = $type.'_db';
syslog(LOG_INFO, 'DB: '.$db);
// Check to see if a development or production server is being used
if (strpos(getenv('SERVER_SOFTWARE'), 'Development') === false) {
$conn = mysqli_connect(null,
getenv('PRODUCTION_DB_USERNAME'),
getenv('PRODUCTION_DB_PASSWORD'),
$db,
null,
getenv('PRODUCTION_CLOUD_SQL_INSTANCE'));
} else {
$conn = mysqli_connect(getenv('DEVELOPMENT_DB_HOST'),
getenv('DEVELOPMENT_DB_USERNAME'),
getenv('DEVELOPMENT_DB_PASSWORD'),
$db);
}
// Check if successful connection to database
if ($conn->connect_error) {
die("Could not connect to database: $conn->connect_error " .
"[$conn->connect_errno]");
}
return $conn;
}
This is the code at the end of the file that initiates everything:
$path_array = explode("/", parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));
$conn = db_connection($path_array[3]);
include 'classes/dashboard.class.php';
$dashboard = new dashboard;
$results = $dashboard->getData($conn);
echo json_encode($results, JSON_PRETTY_PRINT);
mysqli_connect can to return falsy value.
You should use OOP style (new mysqli) or check $conn:
$conn = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (!$conn) {
die('Connection error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
php.net - See "Procedural style" example.
It turned out it was due to variable scope.
I ended up using PHP $GLOBALS to get it to work.
I have this script that deletes a certain picture from the website. It's written with mysql functions so i wanted to update it to mysqli but doing so makes the script stop working. No die message from the script are shown no php errors and adding error_reporting(E_ALL); doesn't show any errors either.
Original script:
if(isset($_POST['F3Verwijderen']))
try
{
//delete the file
$sql = "SELECT PandFoto3 FROM tblpand WHERE `PK_Pand` = '".$pandid."'";
$con = mysql_connect('WEBSITE.mysql', 'WEBSITE', 'PASS');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("WEBSITE");
$result = mysql_query($sql, $con);
while ($row = mysql_fetch_array($result)) {
if(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3'])) {
unlink($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3']);
} else {
echo $row['PandFoto3'];
}
}
//delete the path url from the database field
mysql_query("UPDATE tblpand SET PandFoto3 = NULL WHERE `PK_Pand` = '".$pandid."'");
mysql_close($con);
header('Location: ../admin/pand-aanpassen.php?id='.$pandid);
}
Updated to mysqli:
try
{
//delete the file
$sql = "SELECT PandFoto3 FROM tblpand WHERE `PK_Pand` = '".$pandid."'";
$con = mysqli_connect('WEBSITE.mysql', 'WEBSITE', 'PASS');
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db("WEBSITE");
$result = mysqli_query($sql, $con);
while ($row = mysqli_fetch_array($result)) {
if(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3'])) {
unlink($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3']);
} else {
echo $row['PandFoto3'];
}
}
//delete the path url from the database field
mysqli_query("UPDATE tblpand SET PandFoto3 = NULL WHERE `PK_Pand` = '".$pandid."'");
mysqli_close($con);
header('Location: ../admin/pand-aanpassen.php?id='.$pandid);
}
Edit:
"no php errors and adding error_reporting(E_ALL); doesn't show any errors either."
That's because it isn't a PHP issue, it's a MySQL issue.
Those are two different animals altogether.
As I said in commments, you need to switch these variables ($sql, $con) around ($con, $sql).
Then this:
$con = mysqli_connect('WEBSITE.mysql', 'WEBSITE', 'PASS');
Just use the 4th parameter instead of mysqli_select_db("WEBSITE"); where you didn't pass the connection variable to.
$con = mysqli_connect('WEBSITE.mysql', 'WEBSITE', 'PASS', 'WEBSITE');
The syntax is:
host
username
password (if any)
database
You also could have done mysqli_select_db($con, "WEBSITE");
Sidenote: In mysql_ (see footnotes), the connection comes last, unlike in mysqli_ which comes first.
Do the same for your UPDATE and pass the connection parameter first.
mysqli_query($con, "UPDATE...
Sidenote: To verify that the update truly was successful, use affected_rows()
http://php.net/manual/en/mysqli.affected-rows.php.
Another thing, mysqli_error() requires a connection to it mysqli_error($con) and check for errors for your queries.
I.e.:
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
References:
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.select-db.php
Sidenote:
You're using try() but no catch(). Either remove it, or consult the manual:
http://php.net/manual/en/language.exceptions.php
Example #4 pulled from the manual:
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
try {
echo inverse(5) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "First finally.\n";
}
try {
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "Second finally.\n";
}
// Continue execution
echo "Hello World\n";
?>
Final notes:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Footnotes: (MySQL and MySQLi comparison)
In regards to mysql_query():
mixed mysql_query ( string $query [, resource $link_identifier = NULL ]
http://php.net/manual/en/function.mysql-query.php
For mysqli_query():
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
http://php.net/manual/en/mysqli.query.php
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.
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());
?>
i am using this tutorial and i dont know what is error is this
<?php
header('Content-type: application/json'); // this is the magic that sets responseJSON
// Connecting, selecting database
$link = mysql_connect($dbhost, $dbuser, $dbpass)
or die('Could not connect: ' . mysql_error());
mysql_select_db($dbname) or die('Could not select database');
switch($_POST['op']) {
case 'getAllRecords': {
$table = $_POST['table'];
$query = sprintf("SELECT * FROM %s", mysql_real_escape_string($table));
// Performing SQL query
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$all_recs = array();
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$all_recs[] = $line;
}
break;
}
}
echo json_encode($all_recs);
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
error is :- null
Warning: mysql_free_result(): supplied argument is not a valid MySQL result resource in /home/ajay/public_html/mapleleafrealities.com/test.php on line 26
This is Example
My Error
if you have any simple example of getting json from external db please give me link or code
The op POST parameter is not "getAllRecords", so you're trying to encode something that doesn't exist, and free a result that was never taken. Try putting them inside.