This question already has an answer here:
mysqli_query(): Couldn't fetch mysqli error [duplicate]
(1 answer)
Closed 2 years ago.
I am new to PHP and not familiar with many of its rules, so this could possibly be a stupid question.
I have a database with top level categories and subcategories combined into one table. I want to first print out all the top-level categories, and then printout the subcategories associated with that category.
Here is my code:
<?php
session_start();
include_once "/mysqli_connect.php";
$categories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'category'");
mysqli_close($conn);
?>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div id="wrap" class="animate">
<?php
while ($categories = mysqli_fetch_array($categories0, MYSQLI_ASSOC)) {
$catecory_name = $categories['category'];
echo '
<div class="content">
<div class="content_container no_padding">
<div class="content_container header">
<p>'.$categories['category'].'</p>
</div>
';
$subcategories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'subcategory'");
while ($subcategories = mysqli_fetch_array($subcategories0, MYSQLI_ASSOC)) {
echo $subcategories['category'];
//mysqli_free_result($subcategories0);
}
echo '
</div>
</div>
';
}
?>
</div>
</div>
</body>
</html>
Here is the connection script:
<?php
DEFINE ('DB_USER', '*');
DEFINE ('DB_PASSWD', '*');
DEFINE ('DB_HOST', '*');
DEFINE ('DB_NAME', '*');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWD, DB_NAME);
if(!$conn){
die('Database connection error');
}
echo '<!-- Connected to database -->'
?>
It returns the following error:
Warning: mysqli_query(): Couldn't fetch mysqli
When both queries are above the doctype everything is fine, but when the second query is below the doctype the error occurs.
The first query always runs without problems, it is the second one that returns the error.
I can't seem to figure out what is going on, if anyone can help me that would be appreciated.
You forget to close your while loop. check comment in line where you need to close it.
<?php
$categories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'category'");
?>
<!DOCTYPE html>
<?php
while ($categories = mysqli_fetch_array($categories0, MYSQLI_ASSOC)) {// need to close your loop
$catecory_name = $categories['category'];
echo '
<div class="content">
<div class="content_container header">
<p>'.$categories['category'].'</p>
</div>
';
}// close here
$subcategories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'subcategory'");
// The above line is where the error occurs
while ($subcategories = mysqli_fetch_array($subcategories0, MYSQLI_ASSOC)) {
echo $subcategories['category'];
}
?>
UPDATED
Remove close connection from top because after it your query will not execute. Your connection variable is vanished after your connection is closed.
<?php
session_start();
include_once "/mysqli_connect.php";
$categories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'category'");
?>
Today I have phased the same problem. But There is little mistake that you did in code.
You are trigger select statement this:
See. You are now closing the connection with mysqli_close($conn);
and then in while loop you are fetching data. If connection has been closed then how can php take data from mysql table?
Just remove mysqli_close($conn); statement and run.
In the last line you can put this code. After all the operation.
Related
I am apologizing ahead, this is my first question here and I am still a student.
No time to waste.
I am making a website where you are given drop down boxes to choose CPU, Motherboard, Memory and the rest of your computer parts and sent via email or printed out or generate a code unique to you and your build, so the build is stored in the code. That all comes later.
My problem is that the computer parts listed in tables in database wont load in the box (or dropdown box) as using PHP to generate it from the DB. I've already searched many questions and answers on Stackoverflow but to no avail and I want to kill myself (not really, I am not suicidal at all, it's a figure of speech)
Here is what I got. Then I will explain all the problems that have been popping up.
index.php
<?php
include_once 'func.inc.php';
connectDB();
testDB();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>PC Builder</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body background="background.jpg">
<header>
<h1>PC Builder</h1>
</header>
<section>
<table>
<tr>
<td class="titlecolomn">CPU</td>
<td><?php queryCPU(); ?></td>
</tr>
</table>
</section>
</body>
</html>
<?php closeDB(); ?>
func.inc.php
<?php
include_once 'db.inc.php';
function connectDB(){
$conn = new mysqli($servername, $username, $password, $dbname);
}
function testDB(){
if ($conn->connect_error) {
die("Debug: Connection Failed: " . $conn->connect_error);
}
echo "Debug: Connection Successful.";
}
function closeDB(){
mysqli_close();
}
function queryCPU(){
$queryCPU = "SELECT * FROM CPU";
$db = mysqli_query($db, $queryCPU);
echo '<select name="selectCPU">';
echo '<option value = "SelectCPU"> Select CPU </option>';
while ( $db=mysqli_fetch_assoc($db)) {
echo '<option value="{'.$db[ID].'}">'.$db[Name].'</option>';
}
echo '</select>';
}
db.inc.php
<?php
$servername = "localhost";
$username = "theUsername";
$password = "thePassword";
$dbname = "tableName";
?>
MySQL DB structure.
WebsiteName_PCBuilder
CPU (Table)
ID (Int, AUTO_INC)
Name (Varchar, 30)
ClockSpeed (Decimal 10,2)
Cores (Int)
Price (Decimal 10,2)
Here are the problems.
Whatever kind of password or username or database name or localhost name I put ConnectDB(); always returns
Debug: Connection Successful.
As such the <Select> </Select> is loaded with nothing in it but
'<option value = "SelectCPU"> Select CPU </option>'.
Also, if you know a better or alternative way of doing this, please do recommend it. I am quite flexible changing the entire thing if it it can work.
Here is the website. http://pcbuilder.tariqsendi.ml/
In above provided code, I snipped out the unimportant parts.
Ignore the Main Domain.
Thank you so much, in advance.
That's because you overwriting the same var.
Change
while ( $db=mysqli_fetch_assoc($db)) {
echo '<option value="{'.$db[ID].'}">'.$db[Name].'</option>';
}
With
while ($row = mysqli_fetch_assoc($db)) {
echo '<option value="{'.$row['ID'].'}">'.$row['Name'].'</option>';
}
while ( $row=mysqli_fetch_assoc($db)) {
echo '<option value="'.$row['ID'].'>'.$row['Name'].'</option>';
}
I've been working on a website of mine- it's a shop for different items (it's also my first website). I just got done with the HTML/CSS part of the website but I want to make it more dynamic and easier to edit without having to change multiple pages at once. One way I figured I could do this and also make it easier to implement a website search is by having the names and prices of the items in a database and having PHP code retrieve the name and price and insert it underneath the image of the item. Unfortunately, I have absolutely no idea how to go about this. I've tried looking for other people with similar questions but none of them seem to be specifically what I'm looking for. I'll put my PHP code below and then I'll put some html code that shows where I want to put the information.
<?php
$servername = "localhost";
$username = "root";
$password = "testpw";
$dbname = "testdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error) {
}
$sql = "SELECT id, name, price FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo " " .$row["id"]. " " .$row["name"]. " " .$row["price"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
So that's the PHP code that I use to get the information for each item. The problem though is that it gets the information for every item and displays it at once. I want the code to check for the ID of the item and then retrieve the stats about it and display them. This means if I want to rearrange items in the shop I only have to change the ID- which makes it much much easier for me to manipulate the shop and the items in it. Below is the HTML code for the items.
<div id="images">
<figure>
<img class="gunimage" id="(THIS IS THE ID USED TO GET THE INFO)" src="idk.png" width="225" height="190" alt="">
<figcaption><h3>Name: (INSERT NAME HERE USING PHP) </h3></figcaption>
<figcaption><h5>Price: (INSERT OTHER PRICE HERE)/month</h5></figcaption>
<figcaption><div id="tfbutton5"><form action="buy.html"><input type="submit" value="Rent" class="tfbutton5"></form></figcaption>
</div>
</figure>
</div>
I labeled where I want the info to go, and I want to have the ID thing so the PHP code knows what item it is. I know both codes work separately, as I've tested both of them many times. Sorry if my question is really long, I wanted to make it as specific as possible so it's clear what my problem is. Please excuse if my code requires a lot of changes to make applicable in the situation I'm describing, as I only could figure out how to make something that lists out the info for every item. Any help would be appreciated. Thank you.
If you wanted to do something more you could put in a file called
'connection.php' or something more descriptive
try {
$servername = 'localhost';
$username = 'root';
$password = 'testpw';
$dbname = 'testdb';
$db = new mysqli($servername, $username, $password, $dbname);
} catch(Exception $e) {
echo $e->error_list;
exit;
}
function execute_query($con, $query, $variables) {
$stmt = $con->prepare($query);
$stmt->execute($variables);
return $stmt;
}
you could split these the top part in a connection.php while the function in a function.php file if you have more than one function.
include ('connection.php');
$id_number = $_GET['id'];
# !! NOTICE if grabbing | my understanding another page |
// filter if grabbing from GLOBAL Variable $_GET
$id = filter_var($id_number, FILTER_SANITIZE_NUMBER_INT); //take out
if not grabbing from outside source.
$con = $db;
try {
$query = 'SELECT t.id as id , t.name as name, t.price as price
FROM items as t
WHERE t.id = :id';
$variables[':id'] = $id;
$items = execute_query($con, $query, $variables);
}catch(mysqli_error_list $e) {
echo $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="images"><!-- i am guessing you want it within this div-->
<?php if(isset($item)) { ?>
<?php foreach ( $items as $item) { ?>
<figure>
<img class="gunimage" id="<?php echo $item['id']; ?>"
src="idk.png" width="225" height="190" alt="<?php echo $item['name'];
?>">
<figcaption><h3>Name: <?php echo $item['name']; ?> </h3>
</figcaption>
<figcaption><h5>Price: <?php echo $item['price']; ?> </h5>
</figcaption>
<figcaption>
<!-- instead of a id tfbutton5 needs to be a class otherwise your
going to have an issue here when it loops, you will have an error-->
<div class="tfbutton5"><form action="buy.html"><input
type="submit" value="Rent" class="tfbutton5"></form>
<!--also, not sure why you have an Id and a class named exactly
identical but it is bad practice. sorry do not do it. -->
</figcaption>
</div>
</figure>
<?php } ?>
<?php } ?>
</div>
</body>
</html>
if you wanted an image source, you would need to enter that into a database and connect your Items table to an Image table with that table having say..rows id, image, and item-id. then use the item-id as a point between the item and the image
I am using phpmyadmin and had mySQL database working with my php until I started adding foreign key constraints. Then all of the sudden it stopped working. Now I'm backtracking to the very beginning when I ran my first query, but it still will not work (even though it used to). When I call for the mysql_error() nothing appears.
It seems so simple but I do not know what is going wrong. I even deleted out all of the tables from my database except the subjects table.
manage_content page (which should read my table):
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/db_connection.php");?>
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/functions.php");?>
<?php include($_SERVER['DOCUMENT_ROOT']."/includes/header-home.php");?>
<?php
// 2. Perform database query
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
confirm_query($result);
?>
<div id="main">
<div id="navigation">
<ul class="subjects">
<?php
// 3. Use returned data (if any)
while($subject = mysqli_fetch_assoc($result)) {
// output data from each row
?>
<li><?php echo $subject["first_name"] . " (" . $subject["id"] . ")"; ?></li>
<?php
}
?>
</ul>
</div>
<div id="page">
<h2>Manage Content</h2>
</div>
</div>
<?php
// 4. Release returned data
mysqli_free_result($result);
?>
<?php include($_SERVER['DOCUMENT_ROOT']."/includes/footer.php");?>
Functions page:
<?php
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed: " . mysql_error());
}
}
?>
Please help! I'm new and I know this is incredibly simple. I just don't know what I'm missing!
Because when you do query you call mysqlI_query() function, but when you wanna get error, you do it with mysql_query(), try to change that!!
mysqli_error()
I've been working with this one page forever using MAMP and I can't get the PHP to render. It must be something with getting the info from the table but I can't figure out what. I'm pretty sure I have everything lined up correctly.
For a while it was just sending me back jibberish and then nothing but eventually I got it render the HTML through localhost by switching the while loop to a do-while loop so that it would run through once. So the issue must be with the connection to MySQL I'm thinking, but I don't know what.
<?php
$product_id = $_GET['id'];
$link = mysqli_connect('localhost', 'root', 'root', 'legend');
$result = mysqli_query($link, "SELECT * FROM test WHERE id=" . $product_id . "'");
while($row = mysqli_fetch_array($result)) {
?>
<html>
<head>
</head>
<body>
<div>
<p>Name: <?php echo $row['unitOne']; ?></p>
<p>Box Quantity: <?php echo $row['unitTwo']; ?></p>
</div>
</body>
</html>
<?php
}
mysqli_close($link);
?>
Try to structure your code this way and please consider all the comments below your first post. I also recommend reading this article that will clarify what prepared statements and bound parameters are: http://www.w3schools.com/php/php_mysql_prepared_statements.asp
Remember to always construct your HTML markup correctly. There should never be more than one open and close tag for html, head and body. And if you do have more that can surely mess things up for you.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cart</title>
</head>
<body>
<?php
$query = "SELECT * FROM products WHERE product_id = ?"; //for security we will be using prepared statements
$stmt = $link -> mysqli -> prepare($query); //$link contains your database connection
$stmt -> bind_param('i', $id); //$id contains a product id the "i" will define it as an integer
$stmt -> execute();
$result = $stmt -> fetch_result();
while($row = $result -> fetch_assoc()){ //loop out the results
echo '<div>';
echo '<p>Name: '.$row['unitOne'].'</p>';
echo '<p>Box Quantity: '.$row['unitTwo'].'</p>';
echo '</div>';
}
?>
</body>
</html>
I was just quickly throwing together a script for an article website where I retrieve articles out of a database.
Here is my index.php script
<?php
// include header
require("include/header.php");
require("include/helperfunctions.inc.php");
?>
<!-- page content -->
<!-- left section -->
<section id="contentleft">
<?php require("include/functions.php");
displayArticles();
foreach ($articles as $article) : ;
?>
<h2>Recent Articles</h2>
<ul>
<li><?php echo htmlout($articles['id']) ; ?></li>
<li><?php echo htmlout($articles['title']) ; ?></li>
<li><?php echo htmlout($articles['summary']) ; ?></li>
</ul>
<?php endforeach; ?>
</section>
<!-- right content -->
<section id="contentright">
</section>
<?php
// include footer
require("include/footer.php");
?>
Here is the start of the function library
function displayArticles($order="publicationdate DESC"){
// connect to the database
include("include/db.inc.php");
$query = "SELECT id, title, summary FROM maths order by ". $order . " limit 10";
// query the database
$result = mysqli_query($link, $query);
// error checking
if(mysqli_connect_errno()){
// $error = "error fetching articles";
echo " could not connect: " . mysqli_connect_errno() . " ";
exit();
}
// loop through storing values into array
while($row = mysqli_fetch_array($result)){
$articles[] = array('id'=>$row['id'] , 'title'=>$row['title'],'summary'=>$row['summary']);
}
}
?>
I get this error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\Apache24\htdocs\include\functions.php on line 17 Recent Articles Notice: Undefined variable: articles in C:\Apache24\htdocs\home.php on line 14 Warning: Invalid argument supplied for foreach() in C:\Apache24\htdocs\home.php on line 14
It looks like a scope issue with the $articles object. You create $articles in the displayArticles() function.. but outside of the function, your other code does not know about it. Try returning $articles inside displayArticles(), and replace your displayArticles(); call at the top of the first page with:
$articles = displayArticles();
Also, as panique in the comments pointed out, you are referencing the wrong object inside your foreach block. Remove the 's' at the end of each $articles[blah], so that it reads $article[blah].