MySQLi Query error Couldn't fetch mysqli - php

I am getting the following error when I'm trying the code down below:
Error: Warning: mysqli::mysqli(): (HY000/2002): No such file or directory in /volume1/web/index.php on line 4 Warning: mysqli::query(): Couldn't fetch mysqli in /volume1/web/index.php on line 7 Warning: main(): Couldn't fetch mysqli in /volume1/web/index.php on line 23
The code that I am using..
<?php
// Connect to the DB
$mysqli = NEW MySQLi("localhost","root","","dbproject");
//Query the DB
$resultSet = $mysqli->query("SELECT * FROM clients");
// Count the returned rows
if($resultSet->num_rows != 0) {
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['id'];
$fname = $rows['firstname'];
$lname = $rows['lastname'];
$country = $rows['country'];
echo "<p>ID: " .$id. " <br /> Name: ".$fname." ".$lname. "<br /> Country: ".$country." </p>";
}
// Turn the results into an array
// Display the results
} else{
echo $mysqli->error;
}
?>
As the error reffers to line 4, 7 and 23
Line 4:
$mysqli = NEW MySQLi("localhost","root","","dbproject");
Line 7:
$resultSet = $mysqli->query("SELECT * FROM clients");
Line 23:
echo $mysqli->error;
Can someone please help me with this? Many thanks!

The solution:
I changed line 4 from:
$mysqli = NEW MySQLi("localhost","root","","dbproject");
to
$mysqli = NEW MySQLi("localhost:3307","root","","dbproject");
Adding the port somehow fixed it.

I just tried it on my server and I don't see anything wrong with it. Just make sure your login details are correct as wel as you database and table name.
This is the script I just tested on my server. I added a connection test and changed the database and table name:
<?php
// Connect to the DB
$mysqli = NEW MySQLi("localhost","root","","test");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
//Query the DB
$resultSet = $mysqli->query("SELECT * FROM testing");
// Count the returned rows
if($resultSet->num_rows != 0) {
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['ID'];
echo "<p>ID: " .$id. " </p>";
}
// Turn the results into an array
// Display the results
} else{
echo $mysqli->error;
}
?>

Related

trying to display records from database using php

this is my first question here so feedback on how to improve my questions would be appreciated.
I am trying to display records from a database using PHP.
Here is the code
<?php
$dbConn = new mysqli('localhost', 'twa037', 'twa037Dg', 'autoservice037');
if($dbConn->connect_error) {
die("failed to connect to the database: " . $dbConn->connect_error);
}
else
{
echo "success";
}
$sql = "select * from customer ";
if ($dbConn->query($sql) )
{
echo "query successful";
}
while($row = $sql->fetch_assoc()) {
echo $row['familyName'];
}
$dbconn->close();
?>
I am able to connect to the database and also the query appears to be working fine as it is displaying "success" and "query successfull".
However, I am getting this error
Fatal error: Uncaught Error: Call to a member function fetch_assoc()
on string
Before you guys suggest this could be a duplicate of another post, I have noticed that in the other posts they have used the same code as I have without an issue.
mysqli_query returns a result on that you can call fetch_assoc(). not on the querystring itself.
if ($result = $dbConn->query($sql) )
{
echo "query successful";
}
while($row = $result->fetch_assoc()) {
more informations you can find here
while($row = $sql->fetch_assoc()) <=> while($row = $dbConn->query($sql)->fetch_assoc())

Checking whether username exists in MySQLi Database and PHP

I have been working on a website which has a xampp server and a database called users with a table called AccountDetails. About a year ago I got it to work perfectly, but the server I was using then required MySQL not MySQLi. Now I have to use MySQLi and can't even get the simplest of sql's SELECT function to work, any ideas would be much appreciated.
<?php
$link = mysqli_connect("localhost:3306", "root","", "users");
if(mysqli_connect_errno($link)){
echo "MySql Error: " . mysqli_connect_error();
} else {
echo"Connection Successful <br></br>";
}
echo("Check if still working <br></br>");
// -----------------------------//
echo("Its running <br></br>");
$result = $link->query("SELECT ID, UserName FROM AccountDetails");
return $result->result();
var_dump($result);
mysqli_close($link);
?>
The Query itself works when I plug it into the phpmyadmin SQL section and it returns the values that I expect it too.
I've spent days looking online for different answers but none of them work, and the var_dump only gives me "bool(false)" which I don't think I should be getting.
You can try this code
<?php
$link = mysqli_connect("localhost:3306", "root","", "users");
if(mysqli_connect_errno($link)){
echo "MySql Error: " . mysqli_connect_error();
} else {
echo"Connection Successful <br></br>";
}
echo("Check if still working <br></br>");
// -----------------------------//
echo("Its running <br></br>");
$sql_select = "SELECT * FROM AccountDetails";
$result = $link->query($sql_select);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "UserName: " . $row['UserName']. "<br>";
}
} else {
echo "No Records";
}
$link->close();
?>

No results come up in my HTML page from PHP query

I'm trying to display data from my SQL database on a HTML page through a php query.
I've done a similar query before in the same way and that worked, however this php query doesn't display any results on my html page and I have no idea why.
<?php
$con=mysqli_connect("localhost","root","password","registration");
if (mysqli_connect_errno())
{
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$query = "SELECT * FROM goal WHERE id = $_SESSION[userid]";
$result = mysqli_query($con, $query);
if($result == false) {
die("Query failed: ".mysqli_error($con).PHP_EOL.$query);
}
while($row = mysqli_fetch_assoc($result))
{
echo "Weight Lost:"."<p>".$row['weightlost']."</p>\n";
echo "Weight Unit:"."<p>".$row['weightunit']."</p>\n";
echo "Date set for goal to be reached:"."<p>".$row['whenby']."</p>\n";
}
mysqli_close($con);
?>

Switched computers and get two new mysqli_fetch_row errors.

after I managed to connect my website form to my database, I decided to try to transfer over my files to my work computer.
Initially I only had one error: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given in...
However now I get an extra mysqli_fetch_row() error the same as above but the error is on a different line.
Additionally I also get the error: Undefined index: fill which I never got before. Are there any mistakes in my code? The form still works and can connect to my database.
<center><form action="fill.php" method="post">
Fill
<input type="text" id="fill"" name="fill">
<input type="submit" id ="submit" name="submit" value="Submit here!">
</form></center>
</div>
<?php
$val1 = $_POST['fill'];
$conn = mysqli_connect('localhost', 'root', '')or
die("Could not connect");
mysqli_select_db($conn, 'rfid');
$val2 = "SELECT * FROM card_refill WHERE refill = $val1";
$result1= $conn->query($val2);
$row = mysqli_fetch_row($result1);
$refill1 = $row[2];
$value = "SELECT *FROM card_credit ORDER BY id DESC LIMIT 1:";
$result = $conn->query($value);
$row = mysqli_fetch_row($result);
$refill = $row[2];
$money= $refill+$refill1;
echo $money;
$sql = "UPDATE card_credit SET value = '$money'";
if ($conn->query($sql) === TRUE) {
echo "Success";
}
else {
echo "Warning: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>
</body>
</html>
You're getting that error because you use $_POST['fill'] without checking whether it's set first. It will only be set when the form is submitted, not when the form is first displayed. You need to put all the code that processes the form input into:
if (isset($_POST['submit'])) {
...
}
BTW, you can do that entire update in a single query.
UPDATE card_credit AS cc
CROSS JOIN card_refill AS cr
CROSS JOIN (SELECT * FROM card_credit ORDER BY id DESC LIMIT 1) AS cc1
SET cc.value = cr.col2 + cc1.col2
WHERE cr.refill = '$val1'
Like GolezTrol said from his comment. You're mixing object and functional notation.
Although this might not work exactly how you need it to because I don't have all the information. I have written you something I think is close to what you're looking for.
<?php
// Define the below connections via $username = ""; EXTRA....
// This is best done in a separate file.
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$val1 = $_POST['fill'];
$result1 = $conn->query("SELECT * FROM card_refill WHERE refill = '$val1' ");
$result2 = $conn->query("SELECT * FROM card_credit ORDER BY id DESC LIMIT 1:");
$refill1 = array(); // Pass Results1 Into Array
while($row = $result1->fetch_assoc()) {
$refill1[] = $row[2];
}
$refill = array(); // Pass Results2 Into Array
while($row = $result2->fetch_assoc()) {
$refill[] = $row[2];
}
/* Without an example of what data you are getting from your tables you will have to figure out what data you want from the arrays.
$money= $refill+$refill1;
echo "DEBUG: $money";
*/
// This code will not be functional until your populate the $money value.
$sql = "UPDATE card_credit SET value = '$money' ";
if ($conn->query($sql) === TRUE) {
echo nl2br("Record updated successfully"); // DEBUG
print_r(array_values($refill1)); // DEBUG
print_r(array_values($refill)); // DEBUG
echo nl2br("\n"); // DEBUG
} else { // DEBUG
echo "Error updating record: " . $conn->error; // DEBUG
echo nl2br("\n"); // DEBUG
}
$conn->close();
?>

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.

Categories