mysqli_num_rows generates unlimited amount of data - php

so, I'll try to explain it as good as I can with my knowledge in english.
I am trying to count data from my database, basically - how many fields I have with the same ID. here's image from database.
image from database
for example, in posts i have review system and it works, i have this PHP code to count how many same fields i have with review and id.
Here's the code:
<?php
$revposid = $res['content_id'];
$pos="SELECT review FROM comments WHERE review='positive' and postid=$revposid";
$neg="SELECT review FROM comments WHERE review='negative' and postid=$revposid";
$neu="SELECT review FROM comments WHERE review='neutral' and postid=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
if ($result=mysqli_query($_db,$neg)){$rowcountneg=mysqli_num_rows($result);}
if ($result=mysqli_query($_db,$neu)){$rowcountneu=mysqli_num_rows($result);}
?>
<div class="reviews" id="reviews">
<span class="good"><b class="fa fa-thumbs-up"></b><?php echo $rowcountpos ?></span>
<span class="neutral"><b class="icon-thumbs-up"></b><?php echo $rowcountneu ?></span>
<span class="bad"><b class="fa fa-thumbs-down"></b><?php echo $rowcountneg ?></span>
</div>
and when I try to use the same code
$revposid = $cont['content_id'];
$pos="SELECT content_id FROM user_content_like WHERE content_id=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
in my other script I have like system, it should show all my likes and under likes total likes of the post but when I use it it shows unlimited amount of data, i have no idea why. Here's the full code, I would appreciate some help or explanation.
<?php $ususername = $_GET['user_username'];$sql = "SELECT * FROM user_details WHERE user_username='$ususername'";$usresult = mysqli_query($_db,$sql);?>
<?php if( ! mysqli_num_rows($usresult) ) {
echo " Ooops? <br> <br>User <b>".$_GET["user_username"]."</b> doesn't exist.";
} else {
while($usrow = mysqli_fetch_array($usresult,MYSQLI_BOTH)) {?>
<?php
$current_user = $usrow['user_id'];
if ($_db->connect_error) {
die("Connection failed: " . $_db->connect_error);
}
$sql = "SELECT * FROM user_content_like WHERE user_id=$current_user ORDER BY date_added DESC;";
$result = $_db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$content_id = $row['content_id'];
$sql1 = "SELECT * FROM content WHERE content_id=$content_id";
$result1 = $_db->query($sql1);
if ($_SESSION['user_id'] == $usrow['user_id']) {$output = '
<button type="button" class="unlike_button" onclick="unlike(this);" name="like_button" data-content_id="'.$row["content_id"].'" ><i class="fa fa-minus"></i></button>
';} else {
$output = '';
}
while($cont = $result1->fetch_assoc()) {
$revposid = $cont['content_id'];
$pos="SELECT content_id FROM user_content_like WHERE content_id=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
echo '
<div class="community-feed-thread">
<div class="community-icon-thread"></div>
<div class="community-comments-thread">'.$output.'</div>
<a href="'.$cont["content_id"].'" class="community-title-thread"><h3>'.$cont["title"].'</h3>
<span class="likes-desc"> Total likes: '.$rowcountpos.'</span>
</a>
</div>
';
}
}}
else {
echo " hmmmmmmmmmmmm.<Br><br>". $usrow["user_username"]." doesn't like anything. ";
}
$_db->close();
?>
<?php }}?>
this is how i want it to look
This is how it looks

Your re-using the same variable for different result sets in the code...
$result = $_db->query($sql);
and
if ($result=mysqli_query($_db,$pos))
You will need to ensure you only use the variable name once or it may have side effects in other loops.

Related

How do I make an individual url for each ticket?

I am trying to make a forum-like website from scratch and this is the first big problem that I encountered so far, I am trying to make an individual link with ?info[id] for each ticket/topic but I simply can't, no matter what id I put in the url, I see all of them instead of the specific one, you have all the code in the video.
Video Link
My Details.php Code
<?php
require('Includes/Header.php');
$query = "SELECT * FROM forum";
$result = mysqli_query($conn ,$query);
?>
<?php while($row = mysqli_fetch_array($result)) {?>
<div class="FormAfter">
<label>ID</label><br><br>
<span><?php echo htmlspecialchars($row['id']); ?></span><br><br>
<label>Titlu</label><br><br>
<span name="Titlu"><?php echo htmlspecialchars($row['titlu']);?></span><br><br>
<label>Categorie</label><br><br>
<span><?php echo htmlspecialchars($row['categorie']); ?></span><br><br>
<label>Descriere</label><br><br>
<span name="Descriere" cols="30" rows="10" readonly><?php echo htmlspecialchars($row['descriere']);?></span>
</div>
<?php
}
mysqli_close($conn);
?>
This is my Topics.php code
<?php
require('Includes/Header.php');
$query = "SELECT * FROM forum";
$result = mysqli_query($conn ,$query);
?>
<div class="TopicListBig">
<span id="IdTitlu">ID <strong>|</strong> Titlu <strong>|</strong> Categorie</span> <br> <br> <br>
</div>
<?php
while($row = mysqli_fetch_array($result)){ ?>
<div class="RandomSpan">
<span class="TopicList"><?php echo htmlspecialchars($row['id']); ?></span>
<span class="TopicList"><?php echo htmlspecialchars($row['titlu']); ?></span>
<span class="TopicList"><?php echo htmlspecialchars($row['categorie']); ?></span>
<span class="TopicList">Info</span><br><br>
</div>
<?php
}
mysqli_close($conn);
?>
Your SQL query is explicitly fetching all records: "SELECT * FROM forum" It's the exact same query in Details as it is in Topics and nowhere in the code for Details do you make use of the id parameter in the URL's query string.
What you're looking for in that SQL query is the WHERE keyword. For example:
SELECT * FROM forum WHERE id=?
Within your WHERE clause you identify the specific filter to find the exact record(s) you want. Then you bind your value to that parameter before executing the query. While that link shows the (generally preferred) object-oriented style, you can also use the procedural style you currently use. For example:
$query = mysqli_prepare($conn, 'SELECT * FROM forum WHERE id=?');
mysqli_stmt_bind_param($query, 's', $_GET['id']);
mysqli_stmt_execute($query);
$result = mysqli_stmt_get_result($query);
while ($row = mysqli_fetch_array($result)) {
// your output
}

How do I incorporate $stmt into my search?

Right now I have everything set up correctly with my lines of code because my search bar works, however I am trying to add the first chunk of code to my second chunk of code to help prevent sql injection. This has racked my brain, and I feel as though I have hit a brick-wall. Any help would be appreciated.
I am not sure how to incorporate these lines of code...
$stmt = $mysqli->prepare('SELECT * FROM article WHERE art_country=? OR art_city=?');
$stmt->bind_param('s', $art_country, $art_city);
$stmt->execute();
Into this, and make it work...
$sql = "SELECT * FROM article WHERE art_country LIKE '%$search%' OR art_city LIKE '%$search%'";
if($result = $mysqli->query($sql)) {
if($result->num_rows > 0) {
while($row = $result->fetch_array()){
echo "
//populate to page code...
}
$result->free();
} else {
echo "No results, search again.";
}
} else {
echo "ERROR: Could not execute $sql. " .$mysqli->error;
}
Thank you
As of right now here is everything I have
<?php
if (isset($_POST['submit-search'])) {
$stmt = $mysqli->prepare('SELECT * FROM article WHERE art_country LIKE ? OR art_city LIKE ?');
$art_country = '%'.$art_country.'%';
$art_city = '%'.$art_city.'%';
$stmt->bind_param('ss', $art_country, $art_city);
if ($stmt->execute()) {
$result = $stmt->get_result();{
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<div class='article-box'>
<a class ='search-link' href='".$row['art_URL']."'>
<img class='search-image' src=".$row['art_imageURL'].">
</a>
<a class ='search-link' href='".$row['art_URL']."'>
<h4 class='search-title'>".$row['art_title']."</h4>
</a>
<a class ='search-link' href='".$row['art_URL']."'>
<p class='article-search'>".$row['art_description']."</p>
</a>
<div class='description-container'>
<span><h3 class='index-page'>".$row['art_city']." | ".$row['art_country']." | ".$row['art_date']."</h3></span>
</div>
<div class='divider'></div>
</div>";
}
$result->free();
} else {
echo "No results, search again.";
}
}
}
}
?>
Original and working before mysqli
if (isset($_POST['submit-search'])) {
//mysqli...... prevents people from editing the database
$search = mysqli_real_escape_string($conn, $_POST['search']);
//could just be title this seslects everything.
$sql = "SELECT * FROM article WHERE art_country LIKE '%$search%' OR art_city LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "
<div class='article-box'>
<a class ='search-link' href='".$row['art_URL']."'>
<img class='search-image' src=".$row['art_imageURL'].">
</a>
<a class ='search-link' href='".$row['art_URL']."'>
<h4 class='search-title'>".$row['art_title']."</h4>
</a>
<a class ='search-link' href='".$row['art_URL']."'>
<p class='article-search'>".$row['art_description']."</p>
</a>
<div class='description-container'>
<span><h3 class='index-page'>".$row['art_city']." | ".$row['art_country']." | ".$row['art_date']."</h3></span>
</div>
<div class='divider'></div>
</div>";
}
} else {
echo "No results. Search again.";
}
}
Based on the discussion in the comments, this should be the final version you need.
Summary of changes:
Re-instate the $search variable, which gets data from $_POST and then is passed as the parameter value for both parameters
re-instate the use of LIKE in your query, to make the query equivalent to the one in your old code
add an extra s in the first argument to bind_param, as you have 2 parameters rather than 1
Replace if($result = $mysqli->query($sql)) { with if ($stmt->execute()) { so it checks whether the query succeeds
Use get_result() to retrieve the result object from the executed statement.
After that, your code can proceed as it already did.
<?php
if (isset($_POST['submit-search'])) {
$search = $_POST["search"];
$stmt = $mysqli->prepare('SELECT * FROM article WHERE art_country LIKE ? OR art_city LIKE ?');
$search = '%'.$search.'%';
$stmt->bind_param('ss', $search, $search);
if ($stmt->execute()) {
$result = $stmt->get_result();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<div class='article-box'>
<a class ='search-link' href='".$row['art_URL']."'>
<img class='search-image' src=".$row['art_imageURL'].">
</a>
<a class ='search-link' href='".$row['art_URL']."'>
<h4 class='search-title'>".$row['art_title']."</h4>
</a>
<a class ='search-link' href='".$row['art_URL']."'>
<p class='article-search'>".$row['art_description']."</p>
</a>
<div class='description-container'>
<span><h3 class='index-page'>".$row['art_city']." | ".$row['art_country']." | ".$row['art_date']."</h3></span>
</div>
<div class='divider'></div>
</div>";
}
$result->free();
} else {
echo "No results, search again.";
}
}
}
?>

How insert a new line for each result of query select

I checked all the similar questions but I didn't find an answer.
I wanna insert a <br/> after each result of a query select but i can't do it, maybe because I use float property in CSS.
I'll explain my problem with code:
$sqlUser = "SELECT id,username FROM utenti where id IN (select idUtente from motopartecipanti where idItinerario = '".$idViaggio."') ORDER BY username";
$resultUser = $mysqli->query($sqlUser);
while($rowUser = $resultUser->fetch_assoc()) {
$username = $rowUser["username"];
$idUtente = $rowUser["id"];
echo '
<div style="float:left;">
<label>'.$username.'</label>
</div>
';
$sqlTipo = "SELECT tipo FROM moto where id IN (select idMoto from
motopartecipanti where idItinerario = '".$idViaggio."' AND idUtente =
'".$idUtente."') ";
$resultTipo = $mysqli->query($sqlTipo);
while($rowTipo = $resultTipo->fetch_assoc()) {
$tipo = $rowTipo["tipo"];
echo '
<div style="float:right;">
<label>'.$tipo.'</label>
</div>
';
}
}
The code works but the output is:
Username1Username2 Type1Type2
Instead it should be:
Username1 Type1
Username2 Type2
I used mysql tag too because maybe it can be a problem of query syntax
Add a '' tag at the end of $tipo 'div' tag
while($rowTipo = $resultTipo->fetch_assoc()) {
$tipo = $rowTipo["tipo"];
echo '
<div style="float:right;">
<label>'.$tipo.'</label>
</div><div style="clear:both">
';
}
You can echo <br/> tag or I think its better if you echo a row rather than `. However this depends on your requirement.
echo '
<div style="float:right;">
<label>'.$tipo.'</label> <br/>
</div>
';

Embedded html within while-loop to display result based on what data is returned

Hi Friends
The code I've presented displays data (moduleID & moduleName) associated with a log in user. Presently it shows specific html code associated with a moduleID that should be displayed on the screen when the user logs in. I want to implement a way to iterate through the values (Possibly if-else statement within loop) in order the specific html code i have presented to be shown when a user has one or many moduleID's attached to them.
Here is my homepageDemo.php
<?php
session_start();
//including the database connection file
include 'config.php';
$cuserID= $_SESSION['userID'];
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
$result = mysqli_query($mysqli, "SELECT m.moduleID, m.moduleName
FROM modules m
JOIN courses c ON m.courseID = c.courseID
JOIN usersDemo u ON c.courseID = u.courseID
WHERE userID = '$cuserID'"); // using mysqli_query instead
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
while($res = mysqli_fetch_array($result)) {
echo "
<div id='loader-wrapper'>
<div id='loader'><div id='loader1'>
</div>
</div>
<p><a onclick='IS4439Function()'>IS4437</a></p>
</div>
";
}
?>
Here is the html code attached to the moduleID of IS4437
<div id="loader-wrapper">
<div id="loader"><div id="loader1">
</div>
</div>
<p><a onclick="IS4439Function()">IS4437</a></p>
</div>
Here is the html code attached to the moduleID of IS4408
<div id="loader-wrapper1">
<div id="loader"><div id="loader1">
</div>
</div>
<p><a onclick="IS4408Function()">IS4408</a></p>
</div>
EDIT
So as I've mentioned the problem i'm currently having, these are the different methods I've already tried.
Originally before embedding the html into the while loop in the homepageDemo.PHP, I simply returned the moduleID & moduleName associated with logged in user as text
<?php
session_start();
//including the database connection file
include 'config.php';
$cuserID= $_SESSION['userID'];
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
$result = mysqli_query($mysqli, "SELECT m.moduleID, m.moduleName
FROM modules m
JOIN courses c ON m.courseID = c.courseID
JOIN usersDemo u ON c.courseID = u.courseID
WHERE userID = '$cuserID'"); // using mysqli_query instead
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>"."<a>".$res['moduleID']."</a>"."</td>";
echo "<td>"."<a>".$res['moduleName']."</a>"."</td>";
}
?>
Then I attempted to iterate through the values to return the html code associated with each individual moduleID
SWITCH STATEMENT ATTEMPT:
while($res = mysqli_fetch_array($result)) {
switch ($cuserID) {
case 1:
echo "
<div id='loader-wrapper'>
<div id='loader'><div id='loader1'>
</div>
</div>
<p><a onclick='IS4439Function()'>IS4437</a></p>
</div>
";
break;
case 2:
echo "
<div id='loader-wrapper'>
<div id='loader'><div id='loader1'>
</div>
</div>
<p><a onclick='IS4408Function()'>IS4408</a></p>
</div>
";
break;
case 7:
echo"
<div id='loader-wrapper'>
Functions called
function IS4439Function() {
{
window.location.href = "global.php";
}
}
function IS4408Function() {
{
window.location.href = "isStrategy.php";
}
}
function IS4449Function() {
{
window.location.href = "webApp.php";
}
}
Unfortunately neither were what I was trying to achieve. Any thoughts?
You're really close, and I'm not exactly sure where the disconnect is, but here you go. You need to replace the hardcoded moduleID value (IS4439) with the value that you've already pull from the db. Putting together what you already have, it really just comes down to concatenation.
while($res = mysqli_fetch_array($result)) {
echo "
<div id='loader-wrapper'>
<div id='loader'><div id='loader1'>
</div>
</div>
<p><a onclick='" . $res['moduleID'] . "Function()'>". $res['moduleID'] . "</a></p>
</div>
";
}
I would suggest though, that instead of calling different functions, you consider calling just one function, and passing in the moduleID as a parameter and then act accordingly within the function.
Based on your update, you would then have this...
while($res = mysqli_fetch_array($result)) {
?>
<div id='loader-wrapper'>
<div id='loader'><div id='loader1'>
</div>
</div>
<p><a onclick='redirectFunction("<?php echo $res['moduleID']; ?>");'><?php echo $res['moduleID']; ?></a></p>
</div>
<?php
}
?>
and your function would be...
function redirectFunction(moduleID)
{
var newLocation = "";
if(moduleID == "IS4439")
{
newLocation = "global.php";
}
else if(moduleID == "IS4408")
{
newLocation = "isStrategy.php";
}
else if(moduleID == "IS4449")
{
newLocation = "webApp.php";
}
window.location.href = newLocation;
}

How can I update with a form using MYSQLI

I'm lost on MySQLi. Manages a blog on standard mysql query, MySqli threw me. Followed a tutorial for inserting into a database. Notice the link for Edit. Not sure how to jump to a edit page to update. It this the wrong way of doing it? I think it's the echo that is the echo that is the issue?
<?php
$sql = "
SELECT snippets.Title, snippets.Link, snippets.Text, snippets.Created, camp_names.ribbon as Ribbon, camp_names.alt_text, camp_names.name as Campaign, camp_names.id
FROM snippets
LEFT JOIN camp_names ON snippets.Campaign = camp_names.id
ORDER BY camp_names.id ASC
";
$results = $db->query($sql);
if($results->num_rows) {
While($row = $results->fetch_object()) {
echo "
<div class='snippets'>
<div class='title'><h5><a href=''>{$row->Campaign}</a></h5><strong>{$row->Title}</strong> - Created:{$row->Created}</div>
<div class='ribbon_wrapper'>
<div class='ribbon'><img src='{$row->Ribbon}' alt='{$row->alt_text}' /></div>
<div class='ribbon_text'>{$row->Text}...<a href='{$row->Link}'> Read more</a></div>
<a href='#'>edit</a>
</div>
</div>
";
}
} else {
echo 'No Results';
}
?>

Categories