This question already has answers here:
mysqli::query(): Couldn't fetch mysqli
(4 answers)
Closed 1 year ago.
I was told to stop using MySQL and now learning MySQLi. However I ran into a problem using fetch array and don't know what I did wrong.
//Connect to db
include "mysqli_connect.php";
// Construct our join query
$sql = "SELECT userID, username, lastlogin FROM users";
//Crate results
$result = mysqli_query($link, $sql);
// Print out the contents of each row into a table
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
// Free result set
mysqli_free_result($result);
// Close connection
mysqli_close($link);
Messages I see:
[Connection Successful] Host info: db413417616.db.1and1.com via
TCP/IP
Warning: mysqli_query() [function.mysqli-query]: Couldn't fetch
mysqli in /homepages/9/d413002686/htdocs/maintenance/testsession.php
on line 9
Warning: mysqli_fetch_array() expects parameter 1 to be
mysqli_result, null given in
/homepages/9/d413002686/htdocs/maintenance/testsession.php on line 12
Warning: mysqli_free_result() expects parameter 1 to be
mysqli_result, null given in
/homepages/9/d413002686/htdocs/maintenance/testsession.php on line 15
Warning: mysqli_close() [function.mysqli-close]: Couldn't fetch
mysqli in /homepages/9/d413002686/htdocs/maintenance/testsession.php
on line 18 ()
I used this to for mysqli_connect.php: http://www.php.net/manual/en/mysqli.construct.php
<?php
// $link (host, username, password, database)
$link = mysqli_connect('host', 'username', 'password', 'database');
//If connection is successful, otherwise show error message.
if (!$link) {
die('[Connect Fail] Error: (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
// Echo success message
echo '[Connection Successful] Host info: ' . mysqli_get_host_info($link) . "\n";
// Close the link
mysqli_close($link);
?>
This line in your include file should be removed:
// Close the link
mysqli_close($link);
You're closing $link, a.k.a. your connection to the database, and then trying to use it in your query. You only want to close it when you're all done with it.
Related
This question already has answers here:
mysqli_query() expects parameter 1 to be mysqli, object given
(3 answers)
Closed 2 years ago.
I am trying to find a sum of a column in mysql table but I get an error as below.
<?php require_once("../../../../512/1.001/data/class.php");
$sql=mysqli_query($db,"select SUM(tbl_ccp_loans.payableamount) AS total"); $row = mysqli_fetch_assoc($sql);
$sum = $row['total'];
$sum;?>
I expect the Total sum is 'Number' but the output is
Warning: mysqli_query() expects parameter 1 to be mysqli, object given in /home/testing/public_html/orrf/bej/ccp-main2/_dashboard/data.php on line 223
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in /home/testing/public_html/orrf/bej/ccp-main2/modules/_dashboard/data.php on line 224
Function mysqli_query() expects as first parameter object of mysqli class (returned by mysqli_connect()), but based on code in your comments, your $db variable is an object of different class. If this is a custom class, try to use appropriate methods from this class to execute a query and retrieve results.
Next is a basic example using mysqli_connect().
<?php
require_once("../../../../512/1.001/data/class.php");
$db = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$db) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$sql = mysqli_query($db, "select SUM(tbl_ccp_loans.payableamount) AS total");
if ($sql === false) {
echo 'Error. ' . mysqli_connect_errno() . PHP_EOL;
exit;
}
$row = mysqli_fetch_assoc($sql);
$sum = $row['total'];
echo $sum;
?>
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 4 years ago.
I've spent the past 2 hours trying to solve this one error. I am a complete rookie so I dont know what's going on. Here's the code, please help:
<?php
header('Access-Control-Allow-Origin: *');
$host="localhost"; // Host name
$username="id11111_ab"; // Mysql username
$password="*****"; // Mysql password
$db_name="id11111_cd"; // Database name
$tbl_name="ef"; // Table name
// Connect to server and select database.
$link = mysqli_connect($host, $username, $password, $db_name);
// Retrieve data from database
$sql = "SELECT * FROM scores ORDER BY score DESC LIMIT 10";
$result = mysqli_query($link,$sql);
// Start looping rows in mysql database.
while($rows=mysqli_fetch_array($result)){
echo $rows['name'] . "|" . $rows['score'] . "|";
// close while loop
}
?>
mysqli_query() returns false if it fails. Subsequently, the mysqli_fetch_array() function is being passed this false boolean value, on which it can't operate. You'd be wise to check the value that mysqli_query() returns isn't false prior to attempting to retrieve the resource. E.g.:
$result = mysqli_query($link,$sql);
if (!$result) {
die('Query failed');
}
It seems like the mysql connection is not established properly.
Check for errors using this:
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
I'm new to MySql so forgive me for any stupid errors but Basically i'm making a blog and i have a table which has 4 columns: post_id, post_text, post_user and post_date. I am unable to get my code to insert data into MySql, I'd be greatfull if you could have a look and let me know where I'm going wrong:
<?php
$host = "localhost";
$user="user";
$password="*********";
$db="myData";
$user_id = $_SESSION['user_id'];
ini_set('display_errors', 1); error_reporting(-1);
//can't find the user_id
$con=mysql_connect($host,$user,$password,"myData","posts");
if( $con === FALSE ) {
die('mysql connection error: '.mysql_error());
}
$post_text = mysqli_real_escape_string($con,$_POST["blog_entrance"]);
$post_date = mysqli_real_escape_string($con,date("y.m.d"));
$query = "INSERT INTO posts (post_text, post_user) VALUES ('$post_text','$user_id','$post_date')";
mysql_query($query,$con) or die('Can\'t post data atm: ' . mysql_error());
mysql_close($host,$user,$password,"myData","posts");
header('Location: ../index.php');
?>
the error message is this
"Warning: mysql_connect() expects parameter 5 to be long, string given in /media/sdc1/Documents/Coding/Blog/www/core/submit.php on line 15 Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /media/sdc1/Documents/Coding/Blog/www/core/submit.php on line 21 Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /media/sdc1/Documents/Coding/Blog/www/core/submit.php on line 22 Notice: Undefined variable: user_id in /media/sdc1/Documents/Coding/Blog/www/core/submit.php on line 25 Warning: mysql_query() expects parameter 2 to be resource, null given in /media/sdc1/Documents/Coding/Blog/www/core/submit.php on line 26 Can't post data atm:"
I can see that all these errors seem to stem from the mysql_connect function, please could you tell me the error of my ways?
Also i'm unsure as to whether to use mysql or mysqli????
Read about mysql_connect() function: here
You must use:
$con = mysql_connect($host,$user,$password);
Anyway, mysql_* functions is old, monstrous and deprecated. Use PDO or mysqli
I thought i'd post my final code so future users can have a look at it:
$con= new mysqli($host,$user,$password,$db);
if ($con->connect_errno) {
die("Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error);
}
$post_text = mysqli_real_escape_string($con,$_POST["blog_entrance"]);
$post_date = mysqli_real_escape_string($con,date("y.m.d"));
if (!$con->query("INSERT INTO posts(post_text, post_user, post_date) VALUES ('$post_text',$user_id','$post_date')")) {
die("Multi-INSERT failed: (" . $con->errno . ") " . $con->error);
}
This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 8 years ago.
I looked at the other answers to problems similar to mine but cant seem to solve this.
Here is the code.
$connection = mysql_connect("localhost","root","starwars");
$conn = mysql_select_db("project", $connection);
// This code assumes $itemID is set to that of
// the item that was just rated.
// Get all of the user's rating pairs
$sql = "SELECT DISTINCT r.itemID, r2.ratingValue - r.ratingValue
as rating_difference
FROM rating r, rating r2
WHERE r.userID=$userID AND
r2.itemID=$itemID AND
r2.userID=$userID;";
$db_result = mysql_query($sql, $conn);
echo "The result is {$db_result}";
$num_rows = mysql_num_rows($db_result)or die('Cannot Execute:'. mysql_error());
The error being displayed is:
Warning: mysql_query() expects parameter 2 to be resource, boolean
given in C:\xampp\htdocs\recomender\ratingfiles\class.rating.php on
line 177
Line 177 is
$db_result = mysql_query($sql, $conn);
And if I echo $conn it gives the value of "1" which I thought was equal to true, thus boolean, any ideas?
Pass $connection as the second parameter, not $conn.
You assign the result of mysql_select_db to $conn, and mysql_select_db returns true or false, not a connection resource.
This probably means $conn is false, meaning it didnt get setup correctly. You may want to check how you have set that up and ensure the database connection details are correct and the server this is running on can access the database server.
Take a look at the return values on this page:
http://php.net/manual/en/function.mysql-connect.php
change first 2 lines to
$conn = mysql_connect("localhost","root","starwars");
mysql_select_db("project", $conn);
or, better, just refrain from using connection variable at all
mysql_connect("localhost","root","starwars");
mysql_select_db("project");
...
$db_result = mysql_query($sql);
$db_result = mysql_query($sql, $connection);
Second argument to mysql_connect must have
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
http://php.net/manual/en/function.mysql-query.php
This question already has answers here:
Warning: mysqli_error() expects exactly 1 parameter, 0 given error
(4 answers)
Closed 2 years ago.
I am trying to get my head around mysql. Can someone tell my why this mysql query is not working? I am getting the following error:
Warning: mysqli_error() expects
exactly 1 parameter, 0 given in
/home/freebet2/public_html/test.php on
line 11
test.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/db.php');
$conn = db_connect();
$result = $conn->query("ALTER TABLE users ADD COLUMN refer_old INT(10) AFTER refer_id");
if(!$result){
echo "Error with MySQL Query: ".mysqli_error();
}
?>
db.php
<?php
function db_connect() {
$result = new mysqli('localhost', 'user', 'password', 'db');
if (!$result) {
throw new Exception('Could not connect to database server');
} else {
return $result;
}
}
?>
If I change the alter string to something like : $result = $conn->query("SELECT * FROM users refer_id"); I get no error for some reason.
You are mixing the object-oriented and the procedural styles of the mysqli API :
You are using object-oriented :
$result = new mysqli('localhost', 'user', 'password', 'db');
And, then, procedural :
echo "Error with MySQL Query: ".mysqli_error();
You should use either OO, or procedural -- but not both ; and if you choose procedural, the functions expect the link identifier passed as a parameter.
For instance, mysqli_error should be called either using the object-oriented API :
$link = new mysqli(...);
echo $link->error;
Or the procedural API :
$link = mysqli_connect(...);
echo mysqli_error($link);
(Of course, it will not change the fact that you are having an error in your SQL query, but it'll allow you to get the error message, which should help finding the cause of that error)
As far as the sql error is concerned, does 'user' have permissions to alter the table?
Use mysqli_error($result) as mysqli_error expects the connection to be passed as a parameter.