I've already checked here on stackoverflow and searched on google, but couldn't find my answer. I've created a rating system Thumbs up and down, only members could vote on a article. When a member votes, sql is updating the row voteup/votedown. Now I've made a new table called vote I've got there 5 columns id, user, uID, ctitle, cID
So If a member who is logged in as for ex: Admin and he thumbs up the article for ex: I like coding SQL INSERT INTO the table which is called vote Admin to user the title into ctitle but at the same time he needs to update the table called post the row vote_up or vote_down
I'm only receiving the error: Failed to vote,
<?php
include 'config.php';
require_once 'core/init.php';
$user = new User();
$username = $user->data()->username;
function getAllVotes(mysqli $db, $id)
{
$votes = array();
if($q_13 = "SELECT * FROM post WHERE id = $id");
if($r_26 = $db->query($q_13));
if($r_26->num_rows==1)
{
$stem = $r_26->fetch_object();
$votes[0] = $stem->votes_up;
$votes[1] = $stem->votes_down;
}
return $votes;
}
function getEffectiveVotes(mysqli $db, $id)
{
$votes = getAllVotes($db, $id);
$effectiveVote = $votes[0] - $votes[1];
return $effectiveVote;
}
$id = $_POST['id'];
$action = $_POST['action'];
//current votes
$cur_votes = getAllVotes($db, $id);
//update votes
if($action=='vote_up')
{
$votes_up = $cur_votes[0]+1;
$q_13 = "UPDATE post SET votes_up = $votes_up WHERE id = $id";
$q_13 = "INSERT INTO vote WHERE user = '$username', cID = '$id'";
}
elseif($action=='vote_down')
{
$votes_down = $cur_votes[1]+1;
$q_13 = "UPDATE post SET votes_down = $votes_down WHERE id = $id";
$q_13 = "INSERT INTO vote WHERE user = '$username', cID = '$id'";
}
$r_26 = $db->query($q_13);
if($r_26)
{
$effectiveVote = getEffectiveVotes($db, $id);
echo $effectiveVote." Archers";
}
elseif(!$r_26)
{
echo "Failed to vote!";
}
?>
Related
I am using the code below to duplicate a event record in my database, problem is I am trying to also duplicate any child records (i.e. event services). I need it to copy all "event services" from the eventservices table as well as update the eventid during copy to the newly copied id record. Any help would be appreciated. Thanks.
Note: The eventservices table has a eventid field which matches the id of the event.
$table = 'events';
$id_field = 'id';
$id = $_GET['eventid'];
DuplicateMySQLRecord($table, $id_field, $id);
function DuplicateMySQLRecord($table, $id_field, $id) {
include_once 'db_connect.php';
// load the original record into an array
$result = mysql_query("SELECT * FROM {$table} WHERE {$id_field}={$id}");
$original_record = mysql_fetch_assoc($result);
// insert the new record and get the new auto_increment id
mysql_query("INSERT INTO {$table} (`{$id_field}`) VALUES (NULL)");
$newid = mysql_insert_id();
// generate the query to update the new record with the previous values
$query = "UPDATE {$table} SET ";
foreach ($original_record as $key => $value) {
if ($key != $id_field) {
$query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'", ';
}
}
$query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma
$query .= " WHERE {$id_field}={$newid}";
mysql_query($query);
// return the new id
return $newid;
}
Please use below code.I have not compile this code so test before use.
<?php
include_once 'db_connect.php';
$table = 'events';
$id_field = 'id';
$id = $_GET['eventid'];
DuplicateMySQLRecord($table, $id_field, $id);
function DuplicateMySQLRecord($table, $id_field, $id) {
// load the original record into an array
$result = mysql_query("SELECT * FROM {$table} WHERE {$id_field}={$id}");
$original_record = mysql_fetch_assoc($result);
// insert the new record and get the new auto_increment id
mysql_query("INSERT INTO {$table} (`{$id_field}`) VALUES (NULL)");
$newid = mysql_insert_id();
// generate the query to update the new record with the previous values
$query = "UPDATE {$table} SET ";
foreach ($original_record as $key => $value) {
if ($key != $id_field) {
$query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'", ';
}
}
$query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma
$query .= " WHERE {$id_field}={$newid}";
mysql_query($query);
if($newid) {
$oldid = $id;
copychilds($table, 'eventid', $oldid,$newid);
}
// return the new id
return $newid;
}
function copychilds($table, $id_field, $oldid,$newcopiedid) {
$result = mysql_query("SELECT * FROM {$table} WHERE id={$oldid}");
while($original_child_record = mysql_fetch_assoc($result){
// insert the new record and get the new auto_increment id
mysql_query("INSERT INTO {$table} (`id`) VALUES (NULL)");
$newid = mysql_insert_id();
// generate the query to update the new record with the previous values
$query = "UPDATE {$table} SET ";
foreach ($original_record as $key => $value) {
if ($key != 'id') {
$query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'", ';
}
}
$query .= '`'.$id_field.'` = "'.str_replace('"','\"',$newcopiedid).'", ';
$query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma
$query .= " WHERE id={$newid}";
mysql_query($query);
}
}
?>
Ok, I have all of this working with a few tweaks.
Below is my function, everything is working great, however, it only gets the first record and there may be multiple children. Any help appreciated.
function copychilds1($table, $id_field, $oldid,$newcopiedid, $updatedid) {
include_once '../inc/db_connect.php';
// load the original record into an array
$result = mysql_query("SELECT * FROM {$table} WHERE {$id_field}={$oldid}");
$original_record = mysql_fetch_assoc($result);
// insert the new record and get the new auto_increment id
mysql_query("INSERT INTO {$table} (`{$id_field}`) VALUES (NULL)");
$newid = mysql_insert_id();
// generate the query to update the new record with the previous values
$query = "UPDATE {$table} SET ";
foreach ($original_record as $key => $value) {
if ($key != 'id') {
$query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'", ';
}
}
$query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma
$query .= " WHERE id={$newid}";
mysql_query($query);
$finalquery = "UPDATE eventservices SET eventid = {$updatedid} WHERE id = {$newid}";
mysql_query($finalquery);
// return the new id
return $newid;
}
I'm working on a school project where I need to allow users to vote on pictures. Users can a picture up or down. It's the idea that they can change their vote anytime, but they can't undo their vote, so once they voted it's either up or down.
I've been trying some things but I can't seem to get it to work. It works when an user pressed an upvote for the first time, then the user is able to change his vote to a downvote. But when he tries to upvote again, nothing is happening this has been bugging me for a while now, I would appreciated any help.
Here is my code so far:
if (isset($_SESSION['loggedin'])) {
$result = mysql_query("SELECT * FROM user2pics WHERE picid = $id AND userid = $user");
if (mysql_num_rows($result) == 0) {
$votes_up = $cur_votes[0] + 1;
$resultaat = mysql_query("UPDATE pics SET likes = $votes_up WHERE picid = $id");
if ($resultaat) {
$query = mysql_query("INSERT INTO user2pics (picid, userid, vote) VALUES ($id, $user, 1)");
if ($query) {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
} elseif (!$query) {
echo "Failed!";
}
} elseif (!$resultaat) {
echo "Failed insert in pics!";
}
} else {
$row = mysql_fetch_array($result);
if ($row['vote'] == 0) {
$votes_down = $cur_votes[0] + 1;
$result = mysql_query("UPDATE pics SET likes = $votes_up WHERE picid = $id");
if ($result) {
$resultaat = $mysqli -> prepare("UPDATE user2pics SET vote = 1 WHERE picid = $id AND userid = $user");
$resultaat -> execute();
$effectiveVote = getEffectiveVotes($id);
if ($resultaat -> affected_rows == 1) {
echo $effectiveVote . " votes";
}
}
} else {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
}
}
} else {
echo "Please login first!";
}
} elseif ($action == 'vote_down'){
if (isset($_SESSION['loggedin'])) {
$result = mysql_query("SELECT * FROM user2pics WHERE picid = $id AND userid = $user");
if (mysql_num_rows($result) == 0) {
$votes_down = $cur_votes[1] + 1;
$resultaat = mysql_query("UPDATE pics SET dislikes = $votes_down WHERE picid = $id");
if ($resultaat) {
$query = mysql_query("INSERT INTO user2pics (picid, userid, vote) VALUES ($id, $user, 0)");
if ($query) {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
} elseif (!$query) {
echo "Failed to dislike!";
}
} elseif (!$resultaat) {
echo "Failed insert in pics!";
}
} else {
$row = mysql_fetch_array($result);
if ($row['vote'] == 1) {
$votes_down = $cur_votes[1] + 1;
$result = mysql_query("UPDATE pics SET dislikes = $votes_down WHERE picid = $id");
if ($result) {
$resultaat = $mysqli -> prepare("UPDATE user2pics SET vote = 0 WHERE picid = $id AND userid = $user");
$resultaat -> execute();
$effectiveVote = getEffectiveVotes($id);
if ($resultaat -> affected_rows == 1) {
echo $effectiveVote . " votes";
}
}
} else {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
}
}
} else {
echo "Please login first!";
}
}
$cur_votes is defined as:
$cur_votes = getAllVotes($id);
function getAllVotes($id) {
$votes = array();
$q = "SELECT * FROM pics WHERE picid = $id";
$r = mysql_query($q);
if (mysql_num_rows($r) == 1)//id found in the table
{
$row = mysql_fetch_assoc($r);
$votes[0] = $row['likes'];
$votes[1] = $row['dislikes'];
}
return $votes;
}
function getEffectiveVotes($id) {
/**
Returns an integer
**/
$votes = getAllVotes($id);
$effectiveVote = $votes[0] - $votes[1];
return $effectiveVote;
}
You're duplicating functionality by storing 'likes' in two places.
I didn't look at your weak entity (table for users and votes) so let's assume it will have three fields: user_id, item_id and vote TINYINT. Primary key on user_id and item_id so the same user can only have one vote per item.
Set vote to 1 or -1 depending on up or down, instead of storing likes in the item table, calculate total vote for an item dynamically like this:
SELECT SUM(vote) FROM user_votes WHERE item_id = ?;
If you only want positive votes, do this:
SELECT SUM(vote) FROM user_votes WHERE item_id = ? AND vote = 1;
When the user wants to record or change his vote, you can use REPLACE INTO syntax (thanks to Anigel for the suggestion -- I totally missed it) in order to store the user's new vote:
REPLACE INTO user_votes (user_id, item_id, vote) VALUES (?, ?, ?);
I have a form and when submitted, data will be inserted into three tables (user, journey, user_journey tables). Before the data is inserted, I want to check if that user already exists in the user table. If not, then there is no problem, the user will be inserted into the user table, however, if the user already exists in the user table, I don't want to add the user again. I want to get the user's user_id and insert into the third table (user_journey).
At the moment, when I submit the form, the user is inserted into the user table even if they exist in the table already.
I'm not sure about the way I went about checking if the user exists is correct and the way I'm fetching the user_id. Any advice would be appreciated
$query = $db->query("SELECT COUNT(*) FROM user WHERE facebook_id = '.$hdnFacebookId.'");
//$query->execute();
//$countRows = $query->rowCount();//return number of rows
//check to see if user is already in the database
if ($query->fetchColumn() > 0)
{
if ($oneWay)
{
$query_journey = $db->prepare("INSERT INTO journey
(from_destination,to_destination,journey_type,depart_date,depart_time,seats_available,journey_message,user_type)
VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime','$seatcounter','$textareanotes','$radUserType')");
}
else
{
$query_journey = $db->prepare("INSERT INTO journey
(from_destination,to_destination,journey_type,depart_date,depart_time,return_date,return_time,seats_available,journey_message,user_type)
VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime',STR_TO_DATE('$returnDate','%d/%m/%Y'),'$newRetTime ','$seatcounter','$textareanotes','$radUserType')");
}
$user_query = $db->prepare("SELECT user_id FROM user WHERE facebook_id = '$hdnFacebookId'");
$result = $user_query->execute();
$user_query_result = $user_query->fetch(PDO::FETCH_ASSOC);
$query_journey->execute();//EXECUTE QUERY
$lastJourneyID = $db->lastInsertId();
$queryUserJourney = $db->prepare("INSERT INTO user_journey
(journey_id,user_id)
VALUES('$lastJourneyID','$user_query_result')");
$queryUserJourney->execute();//EXECUTE QUERY
//include('index.php');
}
else //insert user
{
//if $oneWay true, then omit $returnDate and $returnTime
if ($oneWay)
{
$query = $db->prepare("INSERT INTO journey
(from_destination,to_destination,journey_type,depart_date,depart_time,seats_available,journey_message,user_type)
VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime','$seatcounter','$textareanotes','$radUserType')");
}
else
{
$query = $db->prepare("INSERT INTO journey
(from_destination,to_destination,journey_type,depart_date,depart_time,return_date,return_time,seats_available,journey_message,user_type)
VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime',STR_TO_DATE('$returnDate','%d/%m/%Y'),'$newRetTime ','$seatcounter','$textareanotes','$radUserType')");
}
$queryfb = $db->prepare("INSERT INTO user
(facebook_id,facebook_username,facebook_first_name,facebook_last_name,facebook_image,facebook_link)
VALUES('$hdnFacebookId','$hdnUsername','$hdnFirstName','$hdnLastName','$hdnFacebookImg','$hdnFacebookUrl')");
$query->execute();
$lastUserID = $db->lastInsertId();
$queryfb->execute();
$lastJourneyID = $db->lastInsertId();
$queryUserJourney = $db->prepare("INSERT INTO user_journey
(user_id,journey_id)
VALUES('$lastJourneyID','$lastUserID')");
$queryUserJourney->execute();
}
UPDATED
function userExists($db, $hdnFacebookId)
{
$userQuery = "SELECT * FROM user WHERE facebook_id = :user;";
$stmt = $db->prepare($userQuery);
$stmt->execute(array(':user'=>$hdnFacebookId));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
return true;
}
return false;
}
$userExists = userExists($db,$hdnFacebookId);
if($userExists)
{
//don't insert user
//get user's id from database
$user_query = $db->prepare("SELECT * FROM user WHERE facebook_id = '$hdnFacebookId'");
$result = $user_query->execute();
$user_query_result = $user_query->fetch(PDO::FETCH_ASSOC);
$userID = $user_query_result['user_id'];
$query_journey->execute();//EXECUTE QUERY
$lastJourneyID = $db->lastInsertId();
$queryUserJourney = $db->prepare("INSERT INTO user_journey
(journey_id,user_id)
VALUES('$lastJourneyID','$userID')");
$queryUserJourney->execute();//EXECUTE QUERY
}
else
{
//insert user
}
A typical "Check if user exists":
function userExists($db, $user)
{
$userQuery = "SELECT * FROM users u WHERE u.user=:user;";
$stmt = $db->prepare($userQuery);
$stmt->execute(array(':user' => $user));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
return true;
}
return false;
}
So you can do something like
$user = isset($_POST['user']) ? $_POST['user'] : "Unknown";
$userExists = userExists($db, $user);
if($userExists)
{
// Don't insert
]
else
{
// Insert the user.
}
I've got a table in the database called "favorites" with 3 columns (user_id, bookmarked_song_id, bookmark_tag) and I want to get all the Bookmarked_song_id for the current user.
$username = $this->session->userdata('username');
$uidq = mysql_query('SELECT user_id FROM users WHERE username="' . $username . '"');
$rq = mysql_fetch_assoc($uidq);
$user_id = $rq['user_id'];
$getfavq = mysql_query("SELECT * FROM favorites WHERE user_id=$user_id");
$favsr = mysql_fetch_array($getfavq); //contains all the information from the favorites database where user_id is the user_of the currently logged-in user
And I don't know what to use next... I want to have something like:
foreach($favsr['bookmarked_song_id'] as $song_id) {
$getsongq = mysql_query("SELECT * FROM songs WHERE song_id=$song_id");
$getsongr = mysql_fetch_assoc($getsongq);
$singer = $getsongr['singer'];
$song_name = $getsongr['song_name'];}
Obviously the method is wrong because I get: "Invalid argument supplied for foreach()". Can anyone help me with getting the songs? Thanks in advance.
It should be this:
$favsr = mysql_fetch_array($getfavq, MYSQL_ASSOC);
foreach($favsr as $row) {
$songid = $row['bookmarked_song_id'];
...
}
mysql_fetch_array only loads one row,
it should be like that
$getfavq = mysql_query("SELECT * FROM favorites WHERE user_id=$user_id");
while $favsr = mysql_fetch_array($getfavq);
{$songid=$favsr['bookmarked_song_id'];
$getsongq = mysql_query("SELECT * FROM songs WHERE song_id=$song_id");
$getsongr = mysql_fetch_array($getsongq);
$singer = $getsongr['singer'];
$song_name = $getsongr['song_name'];}
You have this tagged with codeigniter. If you've building a CodeIgniter application, you should probably use CI's database library:
$username = $this->session->userdata('username');
//Select your user
$this->db->select('user_id');
$this->db->where('username', $username);
$this->db->limit(1);
$user_query = $this->db->get('users');
if($user_query->num_rows() > 0)
{
// We found a user
$user = $user_query->row(); // select a single row
// Grab this user's favorites
$this->db->where('user_id', $user->id);
$favorites_query = $this->db->get('favorites');
$songs = $favorites_query->result();
if($songs)
{
foreach($songs as $song)
{
$song_id = $song->bookmarked_song_id;
$tag = $song->bookmark_tag;
// Do stuff with data.
}
}
else
{
// No songs/favorites found, catch error
}
}
else
{
// No such user found, catch error
}
Of course, the best practice is to have your user data and your favorites data in separate models, but this should work for now.
I am trying to write to my database if a variable is equal to 0. The problem is that it still writes to the database even when the variables equals 1. What is wrong??
echo $new_user;
if ($new_user == 0) {
//SENT NEW USER WELCOME MESSAGE
$adminid = '9';
$welcomemessagetitle = 'Welcome to The site';
$welcomemessagecontent = 'Hello and welcome';
$addmessages = "INSERT into `user_messages`(`to_user`,`from_user`,`title`,`content`)
VALUES ('$userid','$adminid','$welcomemessagetitle','$welcomemessagecontent');";
$query = mysql_query($addmessages) or die(mysql_error());
//SET USER AS NOT NEW USER
$newuservalue = '1';
$notnewuser = "UPDATE users SET new_user = $newuservalue WHERE id = $userid" ;
$query2 = mysql_query($notnewuser) or die(mysql_error());
} elseif ($new_user == 1) {};
UPDATE FULL CODE::
<?php
session_start();
include "../includes/db_connect.php";
///profile/index.php
if($_SESSION['id'])
{
$username = $_SESSION['username'];
$userid = $_SESSION['id'];
//WRITE FIRST TIME LOGIN INFORMATION TO DATABASE
$sql="SELECT new_user from `users` WHERE `id`= $userid ";
$res=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_assoc($res)) $new_user = $row['new_user'] ;
echo $new_user;
if ($new_user == 0) {
//SENT NEW USER WELCOME MESSAGE
$adminid = '9';
$welcomemessagetitle = 'Welcome to Escorvee';
$welcomemessagecontent = 'Hello and welcome';
$addmessages = "INSERT into `user_messages`(`to_user`,`from_user`,`title`,`content`)
VALUES ('$userid','$adminid','$welcomemessagetitle','$welcomemessagecontent');";
$query = mysql_query($addmessages) or die(mysql_error());
//SET USER AS NOT NEW USER
$newuservalue = '1';
$notnewuser = "UPDATE users SET new_user = $newuservalue WHERE id = $userid" ;
$query2 = mysql_query($notnewuser) or die(mysql_error());
} elseif ($new_user == 1) {};
}
?>
It the variable $new_user is the value 1 then your code won't be executed so I would guess one of the following applies:
$new_user isn't 1.
The database is being modified from another location.
Your script is being called twice.
To work out which you will have to provide more information in your question.