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()
Related
I have a code that have an access to my database's "comments" table. I did a connection variable and created all the stuff in order to get table. But I when save and refresh the page, it is showing this error below. What's the problem?
<?php
// connection
$connection = mysqli_connect(
$config['db']['server'],
$config['db']['username'],
$config['db']['password'],
$config['db']['name']
);
if ($connection == false)
{
echo 'Error!<br>';
echo mysqli_connect_error();
exit();
}
// comments
$сomments = mysqli_query($connection, "SELECT * FROM `comments` ORDER BY `articles_id` DESC LIMIT 5");
while ($com = mysqli_fetch_assoc($comments))
{
?>
<article class="article">
<div class="article__image" style="background-image: url(https://www.gravatar.com/avatar/<?php echo md5($com['email']); ?>?s=125);"></div>
<div class="article__info">
<?php echo $com['author']; ?>
<div class="article__info__preview"><?php echo mb_substr(strip_tags($com['text']), 0, 100, 'utf-8') . ' ...'; ?></div>
</div>
</article>
<?php
}
?>
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in W:\domains\itblog.kg\includes\sidebar.php on line 56 . What is the problem?
The problem is that the query ($comments = mysqli_query(...) is returning a null value. This means that there has been some problem with the query.
Try changing the code like this:
$сomments = mysqli_query($connection, "SELECT * FROM `comments` ORDER BY `articles_id` DESC LIMIT 5");
// start new
if (!$comments) {
echo "Error - " . mysqli_error($connection);
} else
// end new
while ($com = mysqli_fetch_assoc($comments))
{
?>
<article class="article">
...
(Note that you should also surround the whole while loop with braces {}, as it is the else clause, to avoid future errors. But it should work like that.)
The script should report the error it is seeing and it should allow you to fix the query.
Edit - I'd bet that the comments table does not have an articles_id column - probably it should be article_id.
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.
I am trying to make this program where I can delete a thread if I am logged in. Now I already have the button linked and everything, I have it doing multiple tasks when pressed, but it seems to not run the SQL query I want it to. Now I have a variable called $forumid which is set in the URL and retrieved using $_GET['forumid'];
I know this is setting properly, because I have done echo $forumid; and its been correct. But there is one line of code that doesn't run for some reason, and that is:
$db->query("DELETE FROM threads WHERE id='$forumid'");
Now when I remove the WHERE clause, it works, but it wipes out the entire table. So I now know that the problem is the WHERE clause, I just can't find out why it is the issue. I am fairly new to PHP so please forgive my ignorance. But if anyone is able to see the issue, please tell me. Thank you.
[EDIT: COMPLETE CODE]
<?php
require 'connect.php';
session_start();
$forumid = $_GET['forumid'];
$title;
$body;
$by;
$loggedAsAuthor;
?>
<html>
<head>
<title>Legend Factions - View Forum</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="header">
Home
Forum
Vote
Donate
Members
</div>
<div id="content">
<div id="divider">
<?php
if ($result = $db->query("SELECT * FROM threads")) {
while ($row = $result->fetch_assoc()) {
if ($row['id'] == $forumid) {
$title = $row['title'];
$body = $row['words'];
$by = $row['by'];
if ($_SESSION['sess_username'] == $by || $_SESSION['sess_username'] == "admin") {
$loggedAsAuthor = true;
}
}
}
}
echo '<h2>', $title, '</h2><br/><label>By: ', $by;
if (isset($loggedAsAuthor)) {
echo '<form action="viewForum.php" method="post">
<br/><input type="submit" name="delete" value="Delete Thread"/>
</form>';
}
$delete = $_POST['delete'];
if (isset($delete)) {
$db->query("DELETE FROM threads WHERE id=$forumid ");
//header("Location: forum.php");
}
?>
<hr/>
<?php
echo $body;
?>
</div>
</div>
</body>
</html>`
You need to modify your sql query as like :
$db->query("DELETE FROM threads WHERE id= $forumid "); // removed single quotes
Hope it works for you now.
You can try this way, Hope it will help
$qry = "DELETE FROM threads WHERE id= $forumid ";
$db->query($qry);
Your query seems to be correct.
If $_GET['forumid'] is a string, do :
$db->query("DELETE FROM threads WHERE id=".$db->quote($_GET['forumid']));
If $_GET['forumid'] is numeric, do :
$db->query("DELETE FROM threads WHERE id=".(int)$_GET['forumid']);
In any case, string syntax should work, because string will be cast to integer by mysql.
To debug, do :
echo "DELETE FROM threads WHERE id=".$db->quote($_GET['forumid']) ;
And give us the result, or directly paste it into phpMyAdmin to see the error.
You should also add this line at the top of your script to see all errors :
error_reporting(E_ALL) ;
ini_set('display_errors', true) ;
if(isset($_GET['forumid']) && !empty($_GET['forumid'])){
$qry = "DELETE FROM threads WHERE id= '" . mysql_real_escape_string ($_GET['forumid']) . "'";
}
or use active record
$this->db->where('id', $forumid );
$this->db->delete('threads ');
Either integer or string syntax in MySQL should work if the threads id is an integer. What I see that could be happening is:
1) $forumid does not have the value you think it has?
To check it, var_dump the variable right before the delete query:
var_dump($forumid); die;
2) The table id column is not named "id"?
Check the database schema, to check if the column has the name you think it should have. In mysql CLI:
desc threads;
I am beginner to PHP and mySQL. I am creating a navigation trough my database. I have two tables set up one is the main nav items and one is the sub nav items. They are connected by the subject_id. I am using a loop to display them. The first table displays and the second table leaves space for where the information should be but it does not show up. I think it must be something in the SQL settings but I have no idea. Here is my code(i know the database is connected):
<?php require_once("includes/connection.php") ?>
<?php require_once("includes/functions.php") ?>
<?php include("includes/headder.php") ?>
<table id="structure">
<tr>
<td id="navigation">
<ul class="subjects">
<?php
$subject_set = mysql_query("SELECT * FROM subjects", $connection);
if(!$subject_set){
die("database query failed: " . mysql_error());
}
while ($subject = mysql_fetch_array($subject_set)) {
echo "<li>" . $subject["menu_name"] . "</li>";
$page_set = mysql_query("SELECT * FROM pages WHERE subject_id = {$subject["id"]}", $connection);
if(!$page_set){
die("database query failed: " . mysql_error());
}
echo "<ul class=\"pages\">";
while ($page = mysql_fetch_array($page_set)) {
echo "<li>" . $page["menu_name"] . "</li>";
}
echo "</ul>";
}
?>
</ul>
</td>
<td id="page">
<h2>Content Area</h2>
</td>
</tr>
</table>
<?php include("includes/footer.php") ?>
Since you mentioned that white space is showing where the data should be, it appears that rows are indeed found. Consequently, your select statement should be ok. This most likely means that the index "menu_name" can't be found on the $page record.
Check to make sure that "menu_name" is indeed a column of the pages table.
To test what valid columns the $page record has you can use the following inside the while $page loop:
var_dump($page);
If the subject id is an integer you do not need single quotes in the where clause. However, if the subject_id contains any non-integer characters, your select statement would need to be:
$page_set = mysql_query("SELECT * FROM pages WHERE subject_id = '{$subject["id"]}'", $connection);
I need to add Data to the Data that is already in the table.What i need to know is how to Add but i dont want to get the Data,manipulate it(Add) and then update.
Like Data= Data+NewData
With UPDATE, use the CONCAT MySQL function described here.
Example:
UPDATE table SET row = concat(row,'data to add') WHERE …
You don't need to get the data in the row before updating, just update the column that you need to.
http://www.w3schools.com/php/php_mysql_update.asp
If I understand correctly you need a way to execute an sql statement that UPDATE or INSERT data in one statement.
You could use REPLACE INTO or ON DUPLICATE KEY in your statement:
REPLACE INTO FOO(ID,BAR) VALUES('1','BAR')
OR
INSERT INTO FOO (ID, BAR) VALUES(1,'BAR1'),(3,'BAR2') ON DUPLICATE KEY UPDATE BAR=VALUES(BAR)
Well, first you have to connect. Youre question is not clear so, here
'$'
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
and if you mean the content you want is already on that page, you can do this
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
<?
$sql="select * FROM `clients` where id = '".$id."' ORDER BY `id` DESC LIMIT 50;";
$row=mysql_query($sql) or die(mysql_error());
?>
<?php
while ($row = mysql_fetch_assoc($row)) {
?>
<h3> ID:</h3> <? echo $row["id"]; ?>
<hr>
<hr>
<h3> Date and time: </h3> <? echo $row["dt"]; ?>
<hr>
<h3> Name: </h3> <? echo $row["name"]; ?>
<hr>
<h3> Contact: </h3> <? echo $row["contact"]; ?>
<hr>
<h3> Notes: </h3> <? echo $row["note"]; ?>
<hr>
<h3> Our Comment: </h3> <? echo $row["comment"]; ?>
<hr>
<h3>Contacted:</h3>
<?
$boolval = $row["called"];
if ($boolval == 1)
{echo "Customer has been called";}
else
{echo "Customer has not been called";}
?>
<?php
};
?>
Hoe this helps
It sounds like what you want is a database model to do something like this:
$Model = db_table::fetch_by_id($id);
$Model->Name = 'new name';
$Model->update();
I've used custom database models to do this before, but I don't know of anything native to PHP that supports that.
Under the hood it's essentially doing this:
SELECT * FROM Google.Users WHERE id = '23';
//Your php business logic here\\
UPDATE Google.Users SET name='new name' WHERE id='23';
Okay, so if you want to append something this is how you do it.
For Strings ie text;
<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
?>
For numbers, say you have 2 as current value, and 4 is the new value
<?php
$current=2;
$new=4;
$current += $new; // now current is 6 as we added the 4 to it.
?>
To add it to your Data base, you simply insert it
INSERT INTO TABLE (ID) VALUES($current);
//OR if you're form posts and/or gets to your php page.
$sql="INSERT INTO Tabel (new number, current number)
VALUES
('$_POST[numbernew]','$_POST[numberold]')";