Warning: mysqli_query() expects parameter 1 to be mysqli, null given in - php

I am trying to build a simple custom CMS, but I'm getting an error:
Warning: mysqli_query() expects parameter 1 to be MySQLi, null given in
Why am I getting this error? All my code is already MySQLi and I am using two parameters, not one.
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");
//check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL:" . mysqli_connect_error();
}
function getPosts() {
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
{
echo "<div class=\"blogsnippet\">";
echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
echo "</div>";
}
}

As mentioned in comments, this is a scoping issue. Specifically, $con is not in scope within your getPosts function.
You should pass your connection object in as a dependency, eg
function getPosts(mysqli $con) {
// etc
I would also highly recommend halting execution if your connection fails or if errors occur. Something like this should suffice
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");
getPosts($con);

use global scope on your $con and put it inside your getPosts() function
like so.
function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
{
echo "<div class=\"blogsnippet\">";
echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
echo "</div>";
}
}

The getPosts() function seems to be expecting $con to be global, but you're not declaring it as such.
A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.

Related

Mysqli function causes database connection to fail [duplicate]

I am trying to build a simple custom CMS, but I'm getting an error:
Warning: mysqli_query() expects parameter 1 to be MySQLi, null given in
Why am I getting this error? All my code is already MySQLi and I am using two parameters, not one.
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");
//check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL:" . mysqli_connect_error();
}
function getPosts() {
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
{
echo "<div class=\"blogsnippet\">";
echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
echo "</div>";
}
}
As mentioned in comments, this is a scoping issue. Specifically, $con is not in scope within your getPosts function.
You should pass your connection object in as a dependency, eg
function getPosts(mysqli $con) {
// etc
I would also highly recommend halting execution if your connection fails or if errors occur. Something like this should suffice
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");
getPosts($con);
use global scope on your $con and put it inside your getPosts() function
like so.
function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
{
echo "<div class=\"blogsnippet\">";
echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
echo "</div>";
}
}
The getPosts() function seems to be expecting $con to be global, but you're not declaring it as such.
A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.

Mysqli, stuck between "or die" and "sqlierror"

I'm having a trouble around starting a session. Here's my php:
<?php
session_start();
$con=mysqli_connect('localhost','root','','pttkhdt');
if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
else {
$a = $_SESSION['a'];
$knad ='SELECT * FROM admintb WHERE adID=' .$a;
$naad = mysqli_query($con,$knad);
$arad = array();
while($rowad=mysqli_fetch_assoc($naad)) $arad[] = $rowad;
}
?>
If I input that, when I tried to test run my site, it will show:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in...
But if I fix the line
$naad=mysqli_query($con,$knad);
Into:
$naad=mysqli_query($con,$knad) or die;
the page will "die" out and blank.
From the looks of it you're loading your mysqli_fetch_assoc into an array, using a while loop. However, a mysqli_fetch_assoc() is already loading an array.
Why don't you try this:
<?php
session_start();
$con=mysqli_connect('localhost','root','','pttkhdt');
if ( mysqli_errno($con) ) {
//Exit stops the rest of the script
exit( "Failed to connect to MySQL: " . mysqli_error($con) );
} else {
$a = $_SESSION['a'];
$knad = "SELECT * FROM admintb WHERE adID='" . $a . "'";
$arad = mysqli_fetch_assoc( mysqli_query($con,$knad) );
if (!$arad) { exit( mysqli_error($con) ); }
}
?>
The reason behind your sql error may be the fact that your prior SQL $knad statements says for example, adID=justatestvalue, so your SQL is searching for the column justatestvalue. Make sure to enclose actual statements in quotes.
mysqli_query($con,"SELECT * FROM user WHERE userName='$user'");
Check your error with mysql_error() and update your error here;
$naad=mysqli_query($con,$knad) or die(mysql_error());
or try this code below
$link=mysql_connect($host,$user,$pwd);
$db = mysql_select_db($dbname,$link);
if(!$db) die (mysql_error());

Check for specific entry in database

I want to check whether a specific entry is present in my database or not. If present then condition,if not then condition. I tried this code but got errors
<?php
$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classname = mysqli_real_escape_string($con, $_POST['class']);
$result = mysql_query("SELECT * FROM subjectinfo WHERE class = '{$classname}'", $con);
if(mysql_num_rows($result) == 0)
{
echo "No Such Entry In Table. Please ADD it First.";
}
else
{
echo "Entry Available";
}
}
mysqli_close($con);
?>
Errors :
Warning: mysql_query() expects parameter 2 to be resource, object given in C:\xampp\htdocs\pages\test.php on line 11
Warning: mysql_num_rows() expects parameter 1 to be resource, null given in C:\xampp\htdocs\pages\test.php on line 13
No Such Entry In Table. Please ADD it First.
Like your comments. Make sure you don't mix up mysqli and mysql. mysql is deprecated so you're better off using mysqli.
$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classname = mysqli_real_escape_string($con, $_POST['class']);
$result = mysqli_query($con, "SELECT * FROM subjectinfo WHERE class = '{$classname}'");
if(mysqli_num_rows($result) == 0)
{
echo "No Such Entry In Table. Please ADD it First.";
}
else
{
echo "Entry Available";
}
}
mysqli_close($con);
?>
You are mixing MySQL APIs - mysql_ + mysqli_ they do not mix together. Plus, your DB connection's backwards in your query. The connection comes first.
Here:
<?php
$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classname = mysqli_real_escape_string($con, $_POST['class']);
$result = mysqli_query($con,"SELECT * FROM subjectinfo WHERE class = '{$classname}'");
if(mysqli_num_rows($result) == 0)
{
echo "No Such Entry In Table. Please ADD it First.";
}
else
{
echo "Entry Available";
}
}
mysqli_close($con);
?>
Also use or die(mysqli_error($con)) to mysqli_query()
Plus, add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
Look into using prepared statements, or PDO with prepared statements, they're safer.
An insight:
Make sure your form element is indeed named.
I.e.:
<input type="text" name="class">
otherwise, you will receive an Undefined index class... warning.

mysql_close() expects parameter 1 to be resource, null given

The line causing the error is this one...
mysql_close($con);
Here is the entirety of the code...
$con=mysqli_connect("localhost","root","pass","db_name");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM medicos");
while($row = mysqli_fetch_array($result)) {
echo '.....';
}
mysql_close($con);
The line mysql_close($con); must be changed to mysqli_close($con);
You cannot interchangeably use mysql and mysqli functions, for example:
mysqli_connect requires use of mysqli_close
- likewise -
mysql_connect requires use of mysql_close

Connect to wamp server

I keep getting an error message:
Fatal error: Call to a member function execute() on a non-object in C:\wamp\www\Website\index.php on line 46
Below is my code. What could be going wrong? I am just using the stock root account for now.
<?php
$dbserver="localhost";
$username="root";
$password="";
$connection=mysql_connect("$dbserver","$username","$password")or die("could not connect to the server");
//execute an SQL statement and return a recordset
$rs = $connection->execute("SELECT product_name FROM products");
$num_columns = $rs->Fields->Count();
echo "<table border='1'>";
echo "<tr><th>Name</th></tr>";
while (!$rs->EOF) //looping through the recordset (until End Of File)
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $rs->Fields($i)->value . "</td>";
}
echo "</tr>";
$rs->MoveNext();
}
echo "</table>";
//close the recordset and the database connection
$rs->close();
$rs = null;
$conn->close();
$conn = null;
?>
The function mysql_connect returns a resource. This means the variable $connection is not an object and so you cannot call the function execute on it. This explains the error message.
Most of the database-related function calls in the code (Fields, MoveNext, ...) seem to be ADOdb-related. These will not work on a resource (or rowset) created by the mysql_* functions.
See the documentation for ADOdb and the documentation for the mysql extension for PHP for more information.
Since the original mysql extension for PHP is deprecated and ADOdb is not updated very frequently, I would suggest using PDO for your database access.

Categories