I have a problem with accessing "comments" table in databases with PHP - php

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.

Related

WHERE clause effecting SQL query

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;

Query failing to get MySQL data, not mysql_error() displaying

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()

Multiple rows from db

I'm trying to echo out multiple rows from a sql database, but I get the error Warning. Illegal string offset 'Date' In....
$channel_check = mysql_query("SELECT content, Date FROM wgo WHERE Posted_By='$user' ORDER by `id` DESC;");
$numrows_cc = mysql_num_rows($channel_check);
if ($numrows_cc == 0) {
echo '';
// They don't have any channels so they need to create one?><h4> &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspYou haven't posted anything yet. You can post what's going on in your life, how you're feeling, or anything else that matters to you.</h4>
<?php
}
else
{
?>
<div id="recentc">
</div>
<?php
echo"<h2 id='lp'> Latest Posts</h2>";
while($row = mysql_fetch_array($channel_check)) {
$channel_name = $row['content']['Date'];
?>
<div style="margin-top:60px;">
<hr style="margin-right:340px;width:600px; opacity:0;">
<?php echo "<div id='rpc'><h6> $channel_name</h6></div>";?>
</div>
<?php
}
}
?>
DATE is a datatype in SQL, you need to escape it with back ticks
SELECT content, `Date` FROM wgo WHERE Posted_By='$user' ORDER by `id` DESC
Also, you're accessing your row incorrectly. Rows are typically represented by a uni-dimensional array, so $row['content'] and $row['Date']
$row is 1-dimensional array with 2 fields: content and Date.
Try,
while ($row = mysql_fetch_array($channel_check)) {
print_r($row);
//$channel_name = $row['content']['Date'];

Searching in table to find if IP address exists for a set_id

I have reached a stumbling block in my project and need some guidance. I need to implement a model query that returns a mysql_num_rows - I think. What i am trying to do is on my page I have a rating widget that records the IP address of the person voting. I do not want the person to vote more than once. When i do a return mysql_num_rows, i get an error saying
Warning: mysql_num_rows() expects exactly 1 parameter, 0 given
Here is my model
public function getRatingByIp($ipAddress)
{
$sql = sprintf ("SELECT ip_address FROM " . $this->_prefix . "media_set_rating
WHERE set_id = set_id");
mysql_query($sql);
return mysql_num_rows();
}
Here is what I have for the controller:
$setId = $this->_request->getParam('set_id');
$ipAddress = $this->_request->getClientIp();
$ipAddress = $setDao->getRatingByIp($setId);
$this->_view->assign('ip_address', $ipAddress);
$this->_view->assign('set_id', $setId);
Then in the view I want to do an if else statement to show or hide the rating form.
I have this right now:
<?php if ($this->ipAddress > 0) : ?>
"message"
<?php else: ?>
"rating form"
<?php endif; ?>
Maybe there is something I am missing in the code or maybe there is an easier way?
thanks for the help.
Revised 12:28 EST may 28th
Revised code for if Else is as follows
<?php if ($this->ip_address > 0) : ?>
"message"
<?php else: ?>
"rating form"
<?php endif; ?>
Code for query is exactly like what was posted by Eduardo!
thanks again!
You should use the resource in your query:
public function getRatingByIp($ipAddress)
{
$sql = "SELECT ip_address FROM " . $this->_prefix . " media_set_rating WHERE set_id = " . $ipAddress);
$result = mysql_query($sql);
return mysql_num_rows($result);
}
You should not use mysql_num_rows because it's deprecated.
Reference: http://php.net/manual/en/function.mysql-num-rows.php

How to check if my foreach loop has a bug?

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].

Categories