How to make like and unlike - mysql

I have tried to make like and like system using ajax and mysql.
Click like, like is added and Click again, like min 1.
I want, when I click unlike, it will back to like.
But this, unlike until minus..
This is my mysql
<?php
include 'connect.php';
session_start();
$ip=$_SESSION['id'];
if ($_POST['id'])
{
$id=$_POST['id'];
$ip_sql=mysql_query("select id_user from social where track_id='$id' and id_user='$ip'");
$count=mysql_num_rows($ip_sql);
if ($count==0)
{
$sql = "update track set jumlah_like=jumlah_like+1 where track_id='$id'";
mysql_query($sql);
$sql_in = "insert into social (id_user,track_id) values ('$ip','$id')";
mysql_query($sql_in);
$result=mysql_query("select jumlah_like from track where track_id='$id'");
$row=mysql_fetch_array($result);
$love=$row['jumlah_like'];
?>
<span class="broke_love" align="left"><?php echo $love; ?></span>
<?php
}
else
{
$sql = "update track set jumlah_like=jumlah_like-1 where track_id='$id'";
mysql_query($sql);
//$sql_in = "insert into social (id_user,track_id) values ('$ip','$id')";
//mysql_query($sql_in);
$result=mysql_query("select jumlah_like from track where track_id='$id'");
$row=mysql_fetch_array($result);
$love=$row['jumlah_like'];
echo "<span class=on_img align=left>$love</span>";
}
}
?>

The problem is algorithmic that is causing your button to be stuck on 'unlike'.
Your basic condition is: if ($count==0) which always returns greater than 0 after the statement $sql_in = "insert into social (id_user,track_id) values ('$ip','$id')"; is run.
Therefore, your code gets stuck in always executing the else, and continously diminishing the likes.
You need to change your logic to be more:
Check if likes exist and add for specific user.
If like already exists, remove like record.

I think you are missing something from your script as you do not appear to remove a record from the table social.
However most of your selects and updates can be done with a single piece of SQL. Something
like:-
UPDATE track a
LEFT OUTER JOIN social b ON a.track_id = b.track_id AND id_user='$ip'
SET a.jumlah_like = a.jumlah_like + IF(b.track_id IS NULL, 1, -1)
It would probably be better to have a votes table rather than adding and deleting records on the social table. One row per vote.

Related

How to get random row from MYSQL and how to write it in active records?

This is my query
"SELECT * FROM package_info ORDER BY RAND() LIMIT 0,3;"
I try to write it in active records like this.
$this->db->select('*');
$this->db->from('package_info');
$this->db->order_by("id", "random");
$this->db->limit(0, 3);
$result = $this->db->get();
But it is not work. How to write this in active record?
Use Below code it will work fine -
$this->db->select('*');
$this->db->from('package_info');
$this->db->order_by("id", "random");
$this->db->limit(3, 0);
$result = $this->db->get()->result();
// shows last executed query
echo $this->db->last_query();
// shows data fetched
echo "<pre>";
print_r( $result );
echo "</pre>";
You can visit on this link to view how queries are used in Codeigniter.
https://www.codeigniter.com/userguide2/database/active_record.html
CodeIgniter does not mandate that you provide 2 arguments for most Query Builder statements, you can do a whole WHERE by doing ->where('1=1') and its perfectly fine.
I'm surprised how many people don't understand method chaining, but I'll show it in my example it is just nicer...
$result = $this->db->select('*')
->from('package_info')
->order_by('rand()')
->limit(0, 3)
>get();
As per above, if you don't have 2 parameters in your original query, dont feel compelled to add two.
Another thing you can do with basic queries like these, is omit the from('package_info') entirely and stick the table name in the ->get('package_info')
If you cant be bothered with query builder you don't need to use it either. I don't for some things (you cannot use UNION with them for one). In this case just use
$result = $this->db->query("SELECT * FROM package_info ORDER BY RAND() LIMIT 0,3;");

Display selected amount of records from database

I need a page that displays records from a database, sorted by their jobs. So the database holds different kind of persons with different jobs. For example, on the page "teacher" I just want to display all the teachers, not the other persons. I want to have 3 persons on a page and a button "previous" and "next" beneath it. If an user clicks the next-button I want the next 3 records to be shown. When the user reaches the last records, I need the next-button to disappear. Same goes for "previous".
What I have so far:
This piece of code creates a value named startrow.
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//give the value of the starting row 0 because nothing was found in URL
$startrow = 0;
//otherwise take the value from the URL
} else {
$startrow = (int)$_GET['startrow'];
}
The query I have:
$sql = mysql_query("SELECT * FROM $tbl_name WHERE jobs='teacher' LIMIT $startrow, 3")or
die(mysql_error());
$sql2 = "SELECT COUNT(*) AS TotalJobs FROM $tbl_name WHERE jobs='teacher'";
$result_count = mysql_query($sql2);
$count = mysql_fetch_array($result_count);
I created the $count for the if / else function in the next part (the part that doesn't seem to work the way I want it to):
if ($startrow < $count )
echo 'Next';
$prev = $startrow - 3;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo 'Previous';
So the previous-button seems to work the way it should. The next doesn't. I've created the
if ($startrow < $count)
so basicly, if the value of startrow is smaller than the total number of records, it puts a next-button. But if I test this, it displays the next-button anyhow, no matter the value of startrow.
What am I missing here?
mysql_fetch_array returns an array containing the count, not the value itself. Use $count['TotalJobs'] instead.
Also, you shouldn't use the mysql extension anymore, instead use PDO or MySQLi.
Edit
You can change:
$count = mysql_fetch_array($result_count);
to
$countArr = mysql_fetch_array($result_count);
$count = $countArr['TotalJobs'];

$SQL UPDATE doesn't work when added WHERE CLAUSE

I know I am simply missing the simplest thing here but cant seem to figure it out.
so this works with this code but changes all rows of the database as opposed to just the one with the page id...
<? $pageid= $_GET["id"];
$sql = "SELECT id, first_name, last_name, email, bio, job, job2, job3 FROM `".weapons."` WHERE id = $pageid";
if(isset($_POST['Update']))
{
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$job = $_POST['job'];
$job2 = $_POST['job2'];
$job3 = $_POST['job3'];
$bio = $_POST['bio'];
$email = $_POST['email'];
$sql = "UPDATE weapons SET first_name='$first_name', email='$email' , job='$job', job2='$job2', job3='$job3', bio='$bio', last_name='$last_name'";
if (#mysql_query($sql)) {
echo('<p>Update Complete</p>');
} else {
echo('<p>Error updating: ' . mysql_error() . '</p>');
}
}else{ ...
however when adding the WHERE clause, like as follows
$sql = "UPDATE weapons SET first_name='$first_name', email='$email' , job='$job', job2='$job2', job3='$job3', bio='$bio', last_name='$last_name' WHERE id = $pageid";
I get an error
Error updating: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
Any help would be great, thanks
EDIT
I actually missed a super easy thing, which is what I initially assumed, I had at first in my form had <form method='post' enctype='multipart/form-data' action='submit.php'> however that obviously messed up the get id because there isnt an idea, so even if that page was submit.php?id=4 when you hit submit it wouldnt run because the id would be gone.
Switching the code to <form method='post' enctype='multipart/form-data' action='#'> did just the trick.
Thanks for the help guys and I am looking into the sql injection now and working on how to better secure my site.
Please escape your strings before you create your SQL statement. Various characters in your input values will both break your query and open a HUGE security hole. That may very well be your problem. Look at this post for more info How can I prevent SQL injection in PHP?
In short, you assignments would look like this:
$first_name = mysql_real_escape_string($_POST['first_name']);
echo $sql; before you run it and post what that outputs.

MySql: Best way to run high number of search queries on a table

I have two tables, one is static database that i need to search in, the other is dynamic that i will be using to search the first database. Right now i have two separate queries. First on page load, values from second table are passed to first one as search term, and i am "capturing" the search result using cURL. This is very inefficient and probably really wrong way to do it, so i need help in fixing this issue. Currently page (html, front-end) takes 40 seconds to load.
Possible solutions: Turn it into function, but still makes so many calls out. Load table into memory and then run queries and unload cache once done. Use regexp to help speed up query? Possible join? But i am a noob so i can only imagine...
Search script:
require 'mysqlconnect.php';
$id = NULL;
if(isset($_GET['n'])) { $id = mysql_real_escape_string($_GET['n']); }
if(isset($_POST['n'])) { $id = mysql_real_escape_string($_POST['n']); }
if(!empty($id)){
$getdata = "SELECT id, first_name, last_name, published_name,
department, telephone FROM $table WHERE id = '$id' LIMIT 1";
$result = mysql_query($getdata) or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo <<<PRINTALL
{$row[id]}~~::~~{$row[first_name]}~~::~~{$row[last_name]}~~::~~{$row[p_name]}~~::~~{$row[dept]}~~::~~{$row[ph]}
PRINTALL;
}
}
HTML Page Script:
require 'mysqlconnect.php';
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$getdata = "SELECT * FROM $table WHERE $table.mid != '1'ORDER BY $table.$sortbyme $o LIMIT $offset, $rowsPerPage";
$result = mysql_query($getdata) or die(mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$idurl = 'http://mydomain.com/dir/file.php?n='.$row['id'].'';
$p_arr = explode('~~::~~',get_data($idurl));
$p_str = implode(' ',$p_arr);
//Use p_srt and p_arr if exists, otherwise just output rest of the
//html code with second table values
}
As you can see, second table may or may not have valid id, hence no results but second table is quiet large, and all in all, i am reading and outputting 15k+ table cells. And as you can probably see from the code, i have tried paging but that solution doesn't fit my needs. I have to have all of the data on client side in single html page. So please advice.
Thanks!
EDIT
First table:
id_row id first_name last_name dept telephone
1 aaa12345 joe smith ANS 800 555 5555
2 bbb67890 sarah brown ITL 800 848 8848
Second_table:
id_row type model har status id date
1 ATX Hybrion 88-85-5d-id-ss y aaa12345 2011/08/12
2 BTX Savin none n aaa12345 2010/04/05
3 Full Hp 44-55-sd-qw-54 y ashley a 2011/07/25
4 ATX Delin none _ smith bon 2011/04/05
So the second table is the one that gets read and displayed, first is read and info displayed if ID is positive match. ID is only unique in the first one, second one has multi format input so it could or could not be ID as well as could be duplicate ID. Hope this gives better understanding of what i need. Thanks again!
A few things:
Curl is completely unnecessary here.
Order by will slow down your queries considerably.
I'd throw in an if is_numeric check on the ID.
Why are you using while and mysql_num_rows when you're limiting to 1 in the query?
Where are $table and these other things being set?
There is code missing.
If you give us the data structure for the two tables in question we can help you with the queries, but the way you have this set up now, I'm surprised its even working at all.
What you're doing is, for each row in $table where mid!=1 you're executing a curl call to a 2nd page which takes the ID and queries again. This is really really bad, and much more convoluted than it needs to be. Lets see your table structures.
Basically you can do:
select first_name, last_name, published_name, department, telephone FROM $table1, $table2 WHERE $table1.id = $table2.id and $table2.mid != 1;
Get rid of the curl, get rid of the exploding/imploding.

PHP Array Duplicates

my first post here and hoping someone can help. I am querying a table in a mySQL DB, and obviously getting the results. However, the table is used to store multiple entry by one user for the purpose of user contacts.
What I would like to do is display each user individually, and count the number of contacts each user has. I had a look at the post "How to detect duplicate posts in PHP array, which helped a bit, but I am still stuck.
Please see my code for the query below, I have left out the array duplicate part as it is a pretty mess at the moment.
<?php
$result = mysql_query("SELECT * FROM vines");
while($row = mysql_fetch_array($result)) {
$results=$row['vinename'];
echo $results;
echo "<br />";
}
?>
This result returns the below, obviously these are records from the vinename coloumn.
Marks Vine<br />
Marks Vine<br />
Marks Vine<br />
Tasch Vine<br />
Tasch Vine<br />
Regards
Mark Loxton
Hi there, my first post here and hoping someone can help. I am querying a table in a mySQL DB, and obviously getting the results. However, the table is used to store multiple entry by one user for the purpose of user contacts.
You can do this in the query itself a lot more easily than in the PHP code afterwards.
SELECT name, COUNT(id) AS count FROM vines GROUP BY name
Just change the SQL Query to
SELECT vinename, COUNT(vinename) as counter FROM vines GROUP BY vinename
and then do
echo $row['vinename']." #".$row['counter']."<br />";
I would run two types queries...
1) Select each UNIQUE user from vines.
2) For each user in that set, run a second COUNT query against that user's id in the table "vines".
I hope that helps.
You can create a separate array to store records you've already output there.
<?php
$result = mysql_query("SELECT * FROM vines");
$duplicates = array(); ## store duplcated names here
while($row = mysql_fetch_array($result)) {
$results = $row['vinename'];
if (!array_key_exists($results, $duplicates)) {
echo $results;
echo "<br />";
$duplicates[$results] = 1; ## mark that we've already output this records
}
}
?>
You can try, change your query to use count and group of SQL.
Somoe thing like
$result = mysql_query("SELECT count(*) as total,name FROM vines GROUP by name");
firstly thank you everyone for such awesome input. I seriously did not expect such a quick response. I am seriously grateful.
I used the recommendation from Jitter. I have pretty much been going through so many variations of the above code today, but just needed that missing piece.
Thanks, everyone. Below is what the final code looks like for anyone else who has the same problem in the future.
<?php
$result = mysql_query("SELECT vinename, COUNT(vinename) as counter FROM vines GROUP BY vinename ORDER BY counter DESC LIMIT 0, 3");
while($vinerow = mysql_fetch_array($result))
echo $vinerow['vinename']." has ".$vinerow['counter']." tomatos."."<br />";
?>
change your query to:
SELECT distinct * FROM vines