This question already has answers here:
SELECT COUNT(*) AS count - How to use this count
(5 answers)
Closed 2 years ago.
I am sorry if this is a noob question, but I've been searching all over the internet for an answer and could find nothing that could solve my issue. Anyways, I've taken a look at the php documentation on mysqli_num_rows() (which is https://www.php.net/manual/en/mysqli-result.num-rows.php) since I am trying to find the amount of rows in a column. My table looks like this:
id | follower | followee
1 Xp10d3 IiBlurBeriI
2 IiBlurBeriI Xp10d3
In id number 1, the table shows that IiBlurBeriI has a follower of Xp10d3, and in id number 2 the table shows that Xp10d3 has a follower of IiBlurBeriI. I am trying to get all the subscribers where the username is equal to the profile that is being viewed. Anyways, I used the mysqli_num_rows() method to try and execute this but obviously it doesn't work. I don't get any MySQL errors whatsoever, but when viewing the amount of followers it is blank like this:
Username
followers.
following.
But I want it to look like this:
Username
5 followers.
2 following.
The rest of the MySQL that I used to view the profile worked fine; it was just the follower/following system that I had an issue with. My code is below:
<?php
session_start();
$servername = "localhost"; // Host name
$user = "xxxx"; // Mysql username
$pass = "xxxx"; // Mysql password
$dbname = "xxxx"; // Database name
$tbl_name = "forum_question"; // Table name
// Connect to server and select databse.
$conn = new mysqli($servername, $user, $pass, $dbname);
$userGet = $_GET['username'];
$userGetSQL = "SELECT USERNAME FROM data WHERE USERNAME='".$userGet."'";
$result = $conn->query($userGetSQL);
$userRow = $result->fetch_assoc();
$pfp = "SELECT PFP FROM data WHERE USERNAME = '".$_GET['username']."'";
$pfpresult = $conn->query($pfp);
$pfprow = $pfpresult->fetch_assoc();
$rank = "SELECT LEVEL FROM data WHERE USERNAME = '".$_GET['username']."'";
$rresult = $conn->query($rank);
$followers = "SELECT * FROM subscribers WHERE follower = '".$_GET['username']."'";
$fresult = $conn->query($followers);
$fcnt = $fresult->num_rows;
//echo "FOR TESTING PURPOSES! Followers query: " . $followers . ". Result: " . $fresult . ". num_rows: " . $fcnt . ".";
$following = "SELECT * FROM subscribers WHERE followee = '".$_GET['username']."'";
$ffresult = $conn->query($following);
$ffcnt = $ffresult->num_rows;
//echo "FOR TESTING PURPOSES! Following query: " . $following . ". Result: " . $ffresult . ". num_rows: " . $ffcnt. ".";
$desc = "SELECT DESCRIPTON FROM data WHERE USERNAME = '".$_GET['username']."'";
$descresult = $conn->query($desc);
$descRow = $descresult->fetch_assoc();
if (!isset($_SESSION['username']) && empty($_SESSION['username'])) {
echo 'You are not logged in! Go home to login!';
} else {
?>
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
body {
text-align: center;
font-family: sans-serif;
}
.card {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
max-width: 300px;
margin: auto;
text-align: center;
}
.title {
color: grey;
font-size: 18px;
}
.msg{
border: none;
outline: 0;
display: inline-block;
padding: 8px;
color: white;
background-color: #000;
text-align: center;
cursor: pointer;
width: 100%;
font-size: 18px;
}
a {
text-decoration: none;
font-size: 22px;
color: black;
}
.msg:hover, a:hover {
opacity: 0.7;
}
</style>
</head>
<body>
<button type="button" style="cursor:pointer">
Home
</button>
<br />
<?php
$check = mysqli_query($conn, "SELECT * FROM subscribers WHERE follower = '".$_SESSION['username']."' AND followee = '".$_GET['username']."'");
if (mysqli_num_rows($check) > 0) {
?>
<button type="button" style="cursor:pointer">
<a href='unfollow.php?username=<?php echo $userGet ?>'>Unfollow</a>
</button>
<?php
} else {
?>
<button type="button" style="cursor:pointer">
<a href='follow.php?username=<?php echo $userGet ?>'>Follow</a>
</button>
<?php
}
?>
<div class="card">
<?php
if ($pfprow['PFP'] == none.png) {
?>
<img src="<?php echo $pfprow['PFP'] ?>" id="pfp" style="width:100%" />
<?php
} else {
?>
<img src="pfp/<?php echo $pfprow['PFP'] ?>" id="pfp" style="width:100%" />
<?php
}
?>
<h1 id="username"><?php echo $_GET['username'] ?></h2>
<p id="title"><?php echo $rrow['LEVEL'] ?></p>
<p><strong><?php echo $fcount ?></strong> followers.</p>
<p><strong><?php echo $ffcount ?></strong> following.</p>
<div class="desc">
<?php
echo $descRow['DESCRIPTON'];
?>
</div>
<p><button class="msg"><i class="fa fa-envelope-o" aria-hidden="true"></i> Send Message</button></p>
</div>
</body>
</html>
<?php
}
exit();
?>
On a side note, yes I know my code is vulnerable to SQL injection. I am trying to learn how to use prepared statements (I am a new to PHP but have used HTML+CSS for a couple of years) so that I can change my code later on. I don't believe I have any INSERT statements so this should be fine.
Setting aside the SQL injection vulnerabilities that you already mentioned, if you want to know how many rows have, for example, follower = 'some_follower', do a COUNT instead:
SELECT COUNT(1) FROM subscribers WHERE follower = 'some_follower'
Because if you do a SELECT * FROM subscribers WHERE follower = 'some_follower' you are asking the DB to return all the results, while you just want to know the COUNT.
Example in PHP:
$result = $conn->query("SELECT COUNT(1) FROM subscribers WHERE follower = 'some_follower'");
$row = $result->fetch_row();
echo '#: ', $row[0];
Related
I am writing a chat on php, when I try to log in, user_id is recorded in the session, after a successful attempt, a chat page appears where all the messages are written but the problem is that all the messages were written by me, but it is not true. There are some messages which has been written by other users. So, how can I solve this problem by using JOIN? Can you give me some adive or improve my code?
This is code for log in:
<?php
session_start();
include 'db.php';
if (isset($_POST['email-e']) && isset($_POST['password-pass'])) {
$email_e = mysqli_real_escape_string($mysqli,$_POST['email-e']);
$password_pass = crypt($_POST['password-pass']);
$query = "SELECT id, email, password FROM users_data WHERE email = '$email_e' AND password = '$password_pass'";
$sql = mysqli_query($mysqli,$query) or die(mysqli_error());
if (mysqli_num_rows($sql) == 1) {
$row = mysqli_fetch_assoc($sql);
$_SESSION['user_id'] = $row['id'];
$_SESSION['email-e'] = $row['email'];
setcookie("CookieMy", $row['email'], time()+60*60*24*10);
}
else {
echo 'User not found!';
header("Location: login.html");
}
}
if (isset($_SESSION['email-e'])){
header("Location: chat.php");
} else {
$email_e = '';
if (isset($_COOKIE['CookieMy'])){
$email_e = htmlspecialchars($_COOKIE['CookieMy']);
}
}
?>
This is chat.php code:
<?php
session_start();
include 'db_chat.php';
// header('Content-Type: text/html; charset=utf-8');
//echo trim($_SESSION['email-e'])." <br />"."You are authorized <br />";
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Chat</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<title>Chat</title>
<style>
form,p,span{margin:0;padding:0}
input{font:12px arial}
a{color:#00f;text-decoration:none}
a:hover{text-decoration:underline}
#wrapper,
#loginform{margin:0 auto;padding-bottom:25px;background:#ebf4fb;width:504px;border:1px solid #acd8f0}#loginform{padding-top:18px}#loginform p{margin:5px}
#chatbox{text-align:left;margin:0 auto;margin-bottom:25px;padding:10px;background:#fff;height:270px;width:430px;border:1px solid #acd8f0;overflow:auto}
#usermsg{
width:380px;
height: 50px;
border:1px solid #acd8f0;
border-radius: 3px 3px 3px 3px;
}
#submitmsg{width:70px; height: 53px; border-radius: 5px 5px 5px 5px; cursor: pointer;}
.error{color:#f00}
#menu{padding:12.5px 25px 12.5px 25px}
.welcome{float:left}
.logout{float:right}
.msgln{margin:0 0 2px 0}
</style>
</head>
<body>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <?php echo trim($_SESSION['email-e'])?><b></b></p>
<p class="logout" name="logout">
<a name="logout" id="exit" href="#">Exit Chat</a>
</p>
<div style="clear:both"></div>
</div>
<div id="chatbox">
<?php
if(isset($_POST['submitmsg'])) {
if(!empty($_POST['usermsg']) && is_string($_POST['usermsg'])) {
$time = date("Y-m-d H:i:s");
$usermsg = trim($_POST['usermsg']);
$sql_chat ="INSERT INTO `users_chat` (usermsg,time)
VALUES('{$usermsg}','{$time}')";
$res = mysqli_query($mysqli_chat,$sql_chat);
}
}
$query_chat = "SELECT * FROM `users_chat`";
$res = mysqli_query($mysqli_chat,$query_chat);
while($row_chat = mysqli_fetch_array($res)):?>
<?php $_SESSION['user_id'] = $row_chat['id'];?>
Email: <?=$row_chat['email-e']?> <br>
Message: <?=$row_chat['usermsg']?> <br>
Time: <?=$row_chat['time']?> <br>
<?php endwhile;?>
</div>
<form name="message" action="" method="post">
<input name="usermsg" type="text" id="usermsg" style="margin-left:25px;">
<input name="submitmsg" type="submit" id="submitmsg" value="Send"/><br>
</form>
</div>
</body>
</html>
This is structure of my users_chat table:
CREATE TABLE `users_chat` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`usermsg` varchar(255) NOT NULL,
`user_id` int(11) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
What is the structure of your users_chat table. I don't see you assign poster id to each message when insert to the database. You must have a field in your users_chat like poster_id which is the foreign key to the users_data table's id and run this sql in the handle POST request INSERT INTO users_chat (poster_id, usermsg, time) VALUES('{$_SESSION["user_id"]}', '{$usermsg}','{$time}')
while($row_chat = mysqli_fetch_array($res)):?>
<?php $_SESSION['user_id'] = $row_chat['id'];?>
this will modify the user_id in the session to the id of the chat message, I don't think this is what you want.
Here's what I'm basically trying to do:
Retrieve the values of a column
Store those values into an array in PHP
Echo each value with a line break in between each value
Here's my attempted code:
<?php
$connection = mysqli_connect("localhost", "root", "bruhfrogzombie098", "growtapi_social");
if (!$connection) {
die("Failed to connect to MYSQL: " . mysqli_connect_errno());
};
$members = mysqli_query($connection, "SELECT Username FROM s_users");
$members_status = mysqli_query($connection, "SELECT Status_Content FROM s_users");
$members_array = array();
while ($member = mysqli_fetch_assoc($members)) {
$members_array[] = $member;
};
$members_status_array = array();
while ($status = mysqli_fetch_assoc($members_status)) {
$members_status_array[] = $status;
};
?>
And this is where I want to echo out the values:
<center>
<h1>Members Directory</h1>
<div style="width: 20%; height; 75%; border: 3px solid black; margin: auto; overflow: hidden; overflow-y: scroll;">
<?php echo $members_array['$member'];
echo "<br />";
?>
</div>
</center>
I don't receive any errors, but the problem is that nothing shows up in the div, meaning that I either didn't retrieve the data properly or didn't use it right.
Note: I've finally moved on to writing up-to-date code, so I hope no one here comments that somewhere in this code I have outdated code ( ͡° ͜ʖ ͡°)
$members_array = array();
while ($member = mysqli_fetch_assoc($members)) {
$members_array[] = $member;
//$members_array is array and $member is array so $members_array like $members_array[][];
};
<center>
<h1>Members Directory</h1>
<div style="width: 20%; height; 75%; border: 3px solid black; margin: auto; overflow: hidden; overflow-y: scroll;">
<?
$member_count = count($members_array);
for( $i = 0 ; $i < $member_count ; $i++ ){
echo $member_array[$i]['Username'];
echo "<br />";
}
?>
</div>
</center>
I am not great with php/sql - still learning.
I am trying to get it so 5 url's (there are over 20 to chose from) are randomly selected from the user database and displayed on a page. In the event that the user has not filled out all 20+ url's in the members area of our site, I want it to skip the ones they have not filled out.
The problem is it is selecting and displaying 5 whether they are NULL or not and stopping after 5. Its not only counting the ones that are not null.
What do I need to fix, how would I go about this? I pasted the entire code from the page in question - hope its not to much to understand what I need.... like I say I am not that good at this stuff.
<?php
include "config.php";
if ($_GET['r']) {
if($_COOKIE['referid']!=$_GET['r']) mysql_query("UPDATE members SET hits_unique=hits_unique+1,hits_visitor=hits_visitor+1 WHERE userid='".$_GET['r']."'");
else mysql_query("UPDATE members SET hits_visitor=hits_visitor+1 WHERE userid='".$_GET['r']."'");
setcookie('referid', $_GET['r'], time()+365*24*60*60);
setcookie('referrer', $_SERVER['HTTP_REFERER'], time()+365*24*60*60);
}
include 'headsplash.php';
echo '<body style="font-family: "Lato", sans-serif; background-color: black; color: white; height:100%; overflow:hidden;">';
echo '<script src="modernizr-0.9.min.js"></script>';
echo '<canvas id="theapt" style="width:100%; height:100%; position:fixed; top:0;left:0; background-color:black; z-index:-1;"></canvas>';
echo '<center><h1 id="congrats" style="font-size:55px; margin: 0 6px 20px;">'.$_GET['r'].' Recommends</h1></center>';
echo '<div style="margin-bottom:5px; font-size:17px; text-align:center;">';
echo '\'s Downline Builder</h2>';
echo '<div class="wall_back shadow" style="opacity: .9; width:478px; margin: 15px auto 0; border: 1px solid white; border-radius:10px; padding:20px; background-color: #161616;">';
//Get the user links
$ub = array();
$sql = mysql_query("SELECT * FROM builder WHERE userid = '".$_GET['r']."'");
if(#mysql_num_rows($sql)) $ub = mysql_fetch_array($sql);
$lastcat = "";
//Get the links for each site
$slist = mysql_query("SELECT s.*,c.name as catname FROM builder_sites s JOIN builder_cat c ON s.category=c.id ORDER BY RAND() LIMIT 5");
while($each = mysql_fetch_array($slist)) {
$user = $_GET['r'];
$found = 0;
while($found == 0) {
//Referrer exists?
$sql = mysql_query("SELECT m.referid FROM members m JOIN members r ON m.referid = r.userid WHERE m.userid = '".$_GET['user']."'");
if(#mysql_num_rows($sql)) {
$referrer = mysql_result($sql, 0);
$sql = mysql_query("SELECT site".$each['id']." FROM builder WHERE userid = '".$_GET['r']."'");
if(#mysql_num_rows($sql)) {
// Found a row, check if it's empty
$value = mysql_result($sql, 0);
if($value) {
//found a link, end the loop
$links = $value;
$found = 1;
} else {
//No link, next.
$user = $referrer;
}
} else {
//No row, next.
$user = $referrer;
}
} else {
//No more referrers, use default values
$links = $each['url'];
$found = 1;
}
}
if($lastcat != $each['category']) ;
$lastcat = $each['category'];
?>
<table width="50%" cellspacing="5" cellpadding="5">
<tr>
<form method="post"><? echo $each['desc']; ?><input type="hidden" name="sid" value="<? echo $each['id']; ?>">
<br><b><? echo $each['explain']; ?></b>
</form>
</tr>
</table>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-41048281-1', 'thedownliner.com');
ga('send', 'pageview');
</script>
<? }
echo '<center><h3><br>Get your FREE downline builder here</button></h3></center>';
echo '</div>';
echo '</div>';
mysql_close($dblink);
?>
<?php
session_start();
$con=mysqli_connect("localhost","xxx","xxxxxx","xxx");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$eadd = $_POST['eadd'];
$pass = $_POST['pass'];
$eadd = htmlspecialchars(stripslashes(strip_tags($eadd)));
$pass = htmlspecialchars(stripslashes(strip_tags($pass)));
if (filter_var($eadd, FILTER_VALIDATE_EMAIL)) {
$sql = mysql_query("SELECT * FROM accounts WHERE Emailadd = '$eadd' AND Password = '$pass'");
if(!$sql){
die('There was an error in query '. mysql_error());
}
$count = mysql_numrows($sql) or die(mysql_error());
if ($count<=0)
{
echo "
<html>
<style>
body{
background-color:#cccccc;
}
#error{
position:relative;
margin:auto;
top:20px;
width:320px;
height:55px;
background-color:#63a8d7;
border:1px solid #2a262a;
}
#errorC{
position:absolute;
top:20px;
left:20px;
font: 14px arial, tahoma;
}
</style>
<body>
<div id=error>
<div id=errorC>
Incorrect Email Address and Password! <a href=index.php>GO BACK</a>
</div>
</div>
</body>
</html>
";
}
else
{
//have them logged in
$_SESSION['account'] = $eadd;
header('location:home.php');
}
mysqli_close($con);
} else {
echo "
<html>
<style>
body{
background-color:#cccccc;
}
#error{
position:relative;
margin:auto;
top:20px;
width:320px;
height:55px;
background-color:#63a8d7;
border:1px solid #2a262a;
}
#errorC{
position:absolute;
top:20px;
left:20px;
font: 14px arial, tahoma;
}
</style>
<body>
<div id=error>
<div id=errorC>
Invalid Email Address! <a href=index.php>GO BACK</a>
</div>
</div>
</body>
</html>
";
}
?>
Why there is an error "No database selected"? My mysqli_connect is correct. I have another register php code, using which I can register some email address using that connection.But here in login php code, I can't login with the user email address.
From the above code its look like you are using mysqli_connect for database connection and mysql_query for query execution. Use mysqli_query instead of mysql_query . Like this
mysqli_query("SELECT * FROM accounts WHERE Emailadd = '$eadd' AND Password = '$pass'");
Actually, you need to select a database after authentication.
We need to follow these steps while making a database connection.
Create a connection
Select the database
Fire the query
Use query result
Close the connection
Sample Code is here
Firstly, You need to add this line in your code after login
$db_select = mysql_select_db("myDatabase", $con);
Secondly, you need to pass $con as second parameter after selecting your database So your query statement becomes like this
$sql = mysql_query("SELECT * FROM accounts WHERE Emailadd = '$eadd' AND Password = '$pass'", $con);
I do not even know how to google this one...imagine it is something stupid...but any help would be great...
passing a variable when submitting a form...when echo the $_POST it is good...but when i put it into a php variable it is duplicated
<?
//list transactions by month
if ($_POST['m']=="yes"){
$table = $_POST['month'];
$_SESSION['table']=$_POST['month'];
$conn = mysql_connect("localhost", "mss_records", "3205") or die(mysql_error());
mysql_select_db('store_records', $conn) or die(mysql_error());
$result = mysql_query("SELECT * FROM $table");
while($row = mysql_fetch_array($result))
{
$id=$row['transaction'];
$date=$row['date'];
$time=$row['time'];
$paid=$row['payment'];
$total=$row['total'];
echo '<style type="text/css">
<!--
.list {
font-family: Georgia, "Times New Roman", Times, serif;
font-size: 12px;
color: #000;
padding: 2px;
border: 2px solid #009;
}
.view {
width: 100px;
}
-->
</style>
<div class="list">
<p><span style="color: #900">Transaction #</span>'.$id.'
<span style="color: #900">Date:</span>'.$date.'
<span style="color: #900">Time:</span>'.$time.'<span style="color: #900">
Paid By:</span>'.$paid.' <span style="color: #900">Total:</span>'
.number_format($total, 2).'
<form name="form1" method="post" action="find.php">
<label>
<input type="submit" name="view" id="view" value="'.$id.'">
</label>
</form>
</p>
</div>
<p></p>';
}
}
//view transaction after viewing by month
if (isset($_POST['view'])){
$conn = mysql_connect("localhost", "mss_records", "3205") or die(mysql_error());
mysql_select_db('store_records', $conn) or die(mysql_error());
$table = $_SESSION['table'];
echo "this is the number ".$_POST['view'];
$post=$_POST['view'];
echo "this is the post ".$post;
$result = mysql_query("SELECT * FROM $table WHERE transaction = '$post'")
or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$items=$row['transaction'];
}
echo $items;
}
?>
after the user goes through the first selection and on the second window the output is...
this is the number 46this is the $post 4646
Your query is mysql_query("SELECT * FROM $table WHERE transaction = '$post'"). Therefore the value of $items=$row['transaction']; is also going to be 46. When you echo out everything without line breaks, it smashes everything together.
POST is not duplicating anything, you are just echoing $items directly after it.
Try this:
$table = $_SESSION['table'];
echo "this is the number ".$_POST['view']."<br /> \n";
$post=$_POST['view'];
echo "this is the post ".$post."<br /> \n";
$result = mysql_query("SELECT * FROM $table WHERE transaction = '$post'")
or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$items=$row['transaction'];
}
echo $items;
}