You and X others like this - php

I am putting a system together and I would like to get the amount of rows of users that doesn't include the session['id'] user so I can show the link a bit like facebooks.
Example: You and x.. others likes this
Obviously just using the standard num rows grabs all the records from the database but I'd like to exclude the session.
$likes = mysqli_query($mysqli, "
SELECT feedback_streamid,feedback_userid,feedback_rating FROM streamdata_feedback
WHERE feedback_streamid=".$streamitem_data['streamitem_id']."
AND feedback_rating=1 ORDER BY feedback_id LIMIT 10")
or die("SELECT Error: ".mysqli_error($mysqli));
$numRowslikes = mysqli_num_rows($likes);
while ($row = mysqli_fetch_array($likes)) {
$likesmemberid = rawfeeds_user_core::getuser($row['feedback_userid']);
$user1_id = $_SESSION['id'];
$user2_id = $row['feedback_userid'];
if ($user2_id == $_SESSION['id']) {
echo '<div class="like_name"><b>You and '.$numRowslikes.' Others likes this </b> ';
} else {
echo '<a title="'.$likesmemberid['fullname'].' Likes This" href="profile.php?username='.$likesmemberid['username'].'"> <img border=\'0\' src=\'../userimages/ cropped'.$row['feedback_userid'].'.jpg\' onerror="this.src=\'userimages/no_profile_img.jpeg\'" width=\'20\' ></a> ';
}
}

It sounds like you could just change your query to exclude the current user's ID, then use num_rows() as normal.
WHERE feedback_userid NOT IN ('whatever_id_here')

Related

How to search for multiple words in database

I cant seem to work out how to search (and display) multiple words that are in my database. This is an image of the database column
There all separate locations: Africa | Wales, UK | Stockholm, Sweden and I want to search for locations that are the same and display them, the following code works if there is one word in the column but not if there are multiple.
<?php
$sessionid = $_SESSION['id'];
$sql = "SELECT * FROM users WHERE id = '$sessionid';";
$rsults = mysqli_query($conn, $sql);
$resultsCheck = mysqli_num_rows($rsults);
if ($resultsCheck > 0) {
while ($row = mysqli_fetch_assoc($rsults)){
$follow = $row['follow'];
$loc = $row['places'];
}
}
$sql = "SELECT * FROM posts WHERE ext LIKE '$loc' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
$rsults = mysqli_query($conn, $sql);
$resultsCheck = mysqli_num_rows($rsults);
if ($resultsCheck > 0) {
while ($row = mysqli_fetch_assoc($rsults)){
echo '<div class="posts">';
echo '<img class="img"src='.$row['img'].' width="1500px">';
echo '</div>';
echo '<div class="contain">';
echo '<div class="over">';
echo '<div class="username2">';
echo '<img src="focus.png" width="25px" height="25px" style="padding-right: 10px;">'.''.$row['username'].''.'<img src="loc.png" width="25px" height="25px" style="padding-right: 5px; padding-left: 10px;">'.''.$row['ext'].'';
echo '</div>';
echo '<div class="content">';
echo $row['content'];
echo '</div>';
echo '</div>';
}
}
?>
Also I know this is open to sql injection, it's just a proof of concept. Thanks for the help!!
like operator in mysql comes with wild card e.g. '%', '_' etc.
you can use mysql query like this
$sql = "SELECT * FROM posts WHERE ext LIKE '%$loc%' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
for example if $loc = 'canada', it will return all the rows which have 'canada' in thier column whether the column contains 'canada, abc' or 'abc, canada'
When using LIKE you should add '%' sign at start and/or at end of LIKE parameter so it won't search for identical term but one starting or ending with the string you provided. Something like:
$sql = "SELECT * FROM posts WHERE ext LIKE '%$loc%' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
So it will find location that contains your search criteria and not just those identical to it. '%' is replacing any number of characters here.
This goes if you have one search term and you have multiple terms in database column. But if you have multiple search terms you will have to generate your query dynamically, adding one "OR ext LIKE '%$loc%'" for every term.
Use an "%" sign when using the LIKE functionality.
$sql = "SELECT * FROM posts WHERE ext LIKE '%$loc%' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
This would allow you to search through the content of a field.

How do I display a logged in user's images from the database?

Say if a user uploaded multiple images to their profile page, how would I display that specific user's images? I tried I did something like this:
$db = mysqli_connect("localhost", "root", "", "testdb");
$sql = "SELECT * FROM users ORDER BY id DESC";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result)) {
echo "<a href='profiles/uploads/".$row['image']."> ";
echo "<img id='img_div' title='".$row['image']."' alt='".$row['image']."' src='profiles/uploads/".$row['image']."'/>";
//echo "<p id='img_div'>".$row['desc']."</p>";
echo "</a>";
But I feel like this is terribly wrong because it is showing everyone's images and not the user's images. I tried looking up answers, but can't seem to find one.
You need a where clause. where id = 5, of course, replace the number with whatever user you are looking for.
Right now the query SELECT * FROM users ORDER BY id DESC is saying:
Select all columns from all users, ordering them by id.
Instead, you want something like:
SELECT * FROM users WHERE id = {user id} which states:
Select all columns from all users, where the id equals the user id.
As an aside, I'm not sure how you are setting up your database, but
if a user uploaded multiple images to their profile page, how would I display that specific user's images
makes me think that you should really be having separate tables, if you want to allow multiple pictures.
Try this:
You need to set user in sql query like id = 10.
And also missing ' last of this line: echo "<a href='profiles/uploads/".$row['image'].">";
<?php
$user_id = 10;
$db = mysqli_connect("localhost", "root", "", "testdb");
$sql = "SELECT * FROM users WHERE id = ". $user_id ." LIMIT 1";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result)) {
echo "<a href='profiles/uploads/". $row['image'] ."'>";
echo "<img id='img_div' title='".$row['image']."' alt='".$row['image']."' src='profiles/uploads/".$row['quotes']."'/>";
//echo "<p id='img_div'>".$row['desc']."</p>";
echo "</a>";
}
?>

Implementing facebook-style "unlike" function

I've recently implemented a custom liking and disliking feature for my comics site. I'd like to give users the ability to "Take back" their selection by "unclicking" the like or dislike button.
My function works by:
1) Passing button value (id = 'like' or id = 'dislike') via Jquery to
php script
2) script will first check if an ip exists in the database against
that given comic id... if not it will insert user's IP and current
comic ID... if it does, it originally said "you've already voted"... but now to implement "unliking", I will just have it run a delete query
3) then it will get total current likes for that comic id and
increment.
The way I think it can be done is if the user presses the button again, I basically run the opposite query... delete that user's vote from the table given that comic id... then decrement total likes for that image in the comics table.
So my questions are,
1) Is doing an insert query if they press a button once, then a delete
query if they "deselect" that same choice the best way to implement
this? Couldn't a user spam and overload the database by continuously
pressing the like button, thereby constantly liking and unliking?
Should I just implement some sort of $_SESSION['count'] for that ID?
2) If I'm storing a certain IP... what happens if several uniques
users happen to use the same computer at... let's say a netcafe... it
will always store that user's IP. Is storing against the IP the best
way to go?
Code if you need a reference:
<?php
include 'dbconnect.php';
$site = $_GET['_site'];
$imgid = intval($_GET['_id']);
$input = $_GET['_choice'];
if ($site == "artwork") {
$table = "artwork";
}
else {
$table = "comics";
}
$check = "SELECT ip, tablename, imgid FROM votes WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND tablename = '$table' AND imgid = $imgid";
$result = $mysqli->query($check);
if ($result->num_rows == 0) {
//Insert voter's information into votes table
$sql = "INSERT INTO
votes (ip, tablename, imgid)
VALUES
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)
ON DUPLICATE KEY UPDATE
imgid = VALUES(imgid)";
if (!$mysqli->query($sql)) printf("Error: %s\n", $mysqli->error);
/*while ($row = $result->fetch_assoc()) {
echo "you've inserted: " . $row['ip'] . ", " . $row['tablename'] . ", " . $row['imgid'] . ".";
}*/
$result = $mysqli->query("SELECT like_count, dislike_count FROM $table WHERE id = $imgid");
//put the counts into a list
list($likes, $dislikes) = $result->fetch_array(MYSQLI_NUM);
if ($input == "like") {
$sql = "UPDATE $table SET like_count = like_count + 1 WHERE id = $imgid";
$mysqli->query($sql);
$likes++;
}
else if ($input == "dislike") {
$sql = "UPDATE $table SET dislike_count = dislike_count + 1 WHERE id = $imgid";
$mysqli->query($sql);
$dislikes++;
}
}
else { //"unlike" their previous like for that given image id
$sql = "DELETE FROM
votes
WHERE (ip, tablename, imgid) =
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)";
if (!$mysqli->query($sql)) printf("Error: %s\n", $mysqli->error);
$result = $mysqli->query("SELECT like_count, dislike_count FROM $table WHERE id = $imgid");
//put the counts into a list
list($likes, $dislikes) = $result->fetch_array(MYSQLI_NUM);
if ($input == "like") { //remove like
$sql = "UPDATE $table SET like_count = like_count - 1 WHERE id = $imgid";
$mysqli->query($sql);
$likes--;
}
else if ($input == "dislike") {
$sql = "UPDATE $table SET dislike_count = dislike_count - 1 WHERE id = $imgid";
$mysqli->query($sql);
$dislikes--;
}
}
echo "Likes: " . $likes . ", Dislikes: " . $dislikes;
mysqli_close($mysqli);
?>
1) I would say yes, use a count feature to limit the number of attempts they can hit the button in succession. Probably wouldn't have much trouble unless they hit really high numbers, I believe a simple loop would do fine.
2) I would not store just the IP. I would try and use something more than just the IP as an Identifier, like the IP and the session cookie - that way it's unique. However on the look back to the server you would have to parse the entry from the db. Or perhaps the mac address. I'm not sure if you have access to that or not. How can I get the MAC and the IP address of a connected client in PHP?
I'm sure there's another way but conceptually that's how I see it working.

Make the PHP MySql Search Engine and Pagination work

I don't know how to make the search through another table. how should i do that?
the table name is comments and i want to search for all the post stored in the column name kom
Another thing is that i cant get the pagination start working...
I started the pagination within an else statment because i only need it when i get more than 1 result.
I can get the page links showing and limit the search posting showing but when i click on one off the links i cant get to the next page
Heres the code
<?php
$search = $_POST["search"];
$field = $_POST["field"];
if($_POST["submit"] && $search)
{
echo "<div id='result'>";
echo "<h2>Resultat</h2>";
$search = strtoupper($search);
$search = strip_tags($search);
$search = trim($search);
$query = "SELECT * FROM blogTable WHERE title LIKE '%$search%'
UNION
SELECT * FROM blogTable WHERE post LIKE '%$search%'";
$result = mysql_query($query, $conn) or die(mysql_error());
$matches = mysql_num_rows($result);
if($matches == 0)
//code if serch didnt result any results
else if($matches == 1)
//code if the matches only 1
else
{
$per_page = 4;
$pages = ceil($matches / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page']: 1;
$start = ($page - 1) * $per_page;
$query2 = "SELECT * FROM blogTable WHERE title LIKE '%$search%'
UNION
SELECT * FROM blogTable WHERE post LIKE '%$search%' LIMIT $start, $per_page";
$result2 = mysql_query($query2, $conn) or die(mysql_error());
echo "<font size='-1'>Sökningen $search gav $matches resultat</font><br/>";
while ($r2 = mysql_fetch_array($result2))
{
$id = $r["id"];
$title = $r["title"];
$post = $r["post"];
$time = $r["time"];
echo "<br/><strong><a href='comment.php?id=$id'>$title</a></strong><br/>";
echo "<font size='-1'>".substr($post, 0, 60)."</font><br/>";
echo "<font size='-1'>".substr($post, 60, 70)."</font><br/>";
echo "<font size='-3'>$time</font><br/>";
}
//theese are showin but cannot click of any of them
if($pages >= 1 && $page <= $pages)
{
for($nr = 1; $nr <= $pages; $nr++)
{
if($nr == $page)
echo "<a href='?page=".$nr."' style='font-size:20px;'>$nr</a>";
else
echo "<a href='?page=".$nr."' style='font-size:15px;'>$nr</a> ";
}
}
}
}
?>
Is there a specific reason you are using a UNION?
If not, you can change:
$query = "SELECT * FROM blogTable WHERE title LIKE '%$search%'
UNION
SELECT * FROM blogTable WHERE post LIKE '%$search%'";
to:
$query = "SELECT * FROM blogTable WHERE (title LIKE '%$search%') OR (post LIKE '%$search%')";
Anyway, I would never execute the same query twice, just get the first x results if no start parameter was given (for example a page number in the query string) and calculate the start point when a start parameter was given.
And if you want the total, use a COUNT(*) query or change your query:
$query = "SELECT SQL_CALC_FOUND_ROWS * FROM blogTable WHERE (title LIKE '%$search%') OR (post LIKE '%$search%')";
One thing that catches the eye is that the code you show is vulnerable to SQL injection.
Get rid of the strip_tags() (if it's for security, in which case it's useless) and do a mysql_real_escape_string() on every value you use in the search queries, or check whether the value is actually a number when using int columns.
Another thing is that the <font> tag is outmoded. The cool CSS way of styling text is having an external CSS stylesheet, and defining in it something like
span.small { font-size: 12px; color: green }
and then using it in the HTML like so:
<span class="small">Text goes here</span>
that said, this probably belongs on CodeReview.SE....
First, I always recommend to use GET method and not POST method for searches and filters, next, maybe this pagination php class can help you.

Print multiple columns individually

Using the following query:
SELECT title, nid, created FROM node WHERE uid = $account->uid ORDER BY changed DESC
How do I go about printing the title, nid, created separately (in PHP)?
Thanks! (I'm sure this is VERY simple, I'm just not used to PHP yet)
This is a very basic question, try google for tutorials. Here's a c/p from the very first google result about PHP and mysql which shows the technique you're after.
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM example")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry
echo "Name: ".$row['name'];
echo " Age: ".$row['age'];
http://www.tizag.com/mysqlTutorial/mysqlquery.php
If you expect only one result:
$query = "SELECT title, nid, created FROM node WHERE uid = '".$account->uid."' ORDER BY changed DESC";
$resource = mysql_query($query) or die (mysql_error());
if(mysql_num_rows($resource)>0)
{
$row = mysql_fetch_array($resource);
echo 'Title: '.$row['title'].'<br />';
echo 'ID: '.$row['nid'].'<br />';
}
else
{
echo 'no record found';
}
Otherwise (i reread the title of the question now, sorry)
while ($row = mysql_fetch_array($resource))
{
echo 'Title: '.$row['title'].'<br />';
echo 'ID: '.$row['nid'].'<br />';
}

Categories