my WHERE do so my page dont work and i dont know how i do so then a user create a comment then a number in my thread will grow +1.
i wanna do this because then i user create a new comment the users who follow that thread can see "oh there is a new comment to the topic o follow"
here is my code
if(isset($_POST['opret_kommentar']))
{
$nyt_svar = 0;
$mysql2 = connect();
$stmt2 = $mysql2->prepare("INSERT INTO forum_traad (nyt_svar) VALUES (?) WHERE id = '$traadID'") or die($mysql->error);
$stmt2->bind_param('i', $nyt_svar) or die($mysql->error);
$stmt2->execute();
$indhold = htmlspecialchars($_POST['indhold']);
$godkendt = "ja";
$mysql = connect();
$stmt = $mysql->prepare("INSERT INTO forum_kommentare (fk_forum_traad, brugernavn, indhold, godkendt) VALUES (?,?,?,?)") or die($mysql->error);
$stmt->bind_param('isss', $traadID, $_SESSION['username'], $indhold, $godkendt) or die($mysql->error);
$stmt->execute();
$stmt->close();
$svar = mysqli_insert_id($mysql);
header("location: forum.traad.php?traadID=$traadID&kategoriID=$kategoriID&#$svar");
}
If you have an existing thread record which you want to increment, you will want to use an UPDATE statement rather than INSERT.
For example:
UPDATE forum_traad SET nyt_svar = (nyt_svar + 1) WHERE id = '$traadID';
So you mean, where ~ VALUES (VAR+1) ?
Related
I have a like button, which allows users to like posts on my site. If the user likes a post they have not liked before it will +1, if they press the same like button again it will -1. This is working on my virtual server on my laptop. However, the same code is not working on my live site. On my live site the user is able to like the same post multiple times, which is not what I want. I'm using a JQuery Ajax call to a PHP file that fires a some MySQL code.
Can anyone see anything obviously wrong with the PHP below?
include ("../con/config.php");
$postid = $_POST['postid'];
$userid = $_POST['userid'];
$query = $con->prepare("SELECT COUNT(*) AS CntPost FROM Likes WHERE UserID = ? AND PostID = ?");
$query->bind_param('ss',$userid,$postid);
$query->execute();
$result = $query->get_result();
$fetchdata = $result->fetch_assoc();
$count = $fetchdata['CntPost'];
if($count == 0){
$stmt = $con->prepare("INSERT INTO Likes(UserID,PostID) VALUES(?,?)");
$stmt->bind_param("ss", $userid, $postid);
$stmt->execute();
} else {
$stmt = $con->prepare("DELETE FROM Likes WHERE UserID = ? AND PostID = ?");
$stmt->bind_param("ss", $userid, $postid);
$stmt->execute();
}
// count numbers of likes in post
$query = $con->prepare("SELECT COUNT(*) AS CntLike FROM Likes WHERE PostID = ?");
$query->bind_param('s', $postid);
$query->execute();
$result = $query->get_result();
$fetchlikes = $result->fetch_assoc();
$totalLikes = $fetchlikes['CntLike'];
$return_arr = array("likes"=>$totalLikes,"type"=>$count);
echo json_encode($return_arr);
Managed to solve it. The issue was in the MySQL database column itself for the UserID. The number of chars for the column was not long enough and was truncating the UserID, which I populate using the sessionID. I amended this field in the database to allow for the length of a sessionID.
perhaps this statement
"SELECT COUNT(*) AS CntLike FROM Likes WHERE PostID = ?" need UserID in WHERE statement so you would know that specific UserID in that specific PostID
For some reason this php code on execution is returning NULL...cud any1 kindly help in correcting it?
public function like($pid)
{
$uid = escape($_SESSION['user']);
$sql = $this->_db->prepare("UPDATE postsinitial SET likes = likes+1 WHERE pid = :m;INSERT IGNORE INTO userlikedposts (ulp_userid,ulp_postid) VALUES (:k, :m)");
$sql->bindValue(':k', $uid);
$sql->bindValue(':m', $pid);
$sql->execute();
$query = $this->_db->prepare("SELECT likes FROM postsinitial WHERE pid = :n");
$query->bindParam(':n', $pid);
$query->execute();
while($rows = $query->fetch())
{
return $rows['likes'];
}
}
But when i run the two parts of the query separately, i.e., commenting out the $sql batch of code and running $query batch alone, it works and returns a value.. , it works fine..but not combined as stated..so how do i run it as is?
I've tried this model too for the select query bt still same result:
$query = $this->_db->prepare("SELECT likes FROM postsinitial WHERE pid = :n");
$query->bindParam(':n', $pid);
$query->execute();
while($rows = $query->fetch(PDO::FETCH_ASSOC))
{
return $rows[0]['likes'];
}
The answer is simple:
You should run your queries one by one instead of stuffing them all into a single call. Run your insert query separated rom update and you'll be fine.
public function like($pid)
{
$sql = "UPDATE postsinitial SET likes = likes+1 WHERE pid = ?";
$this->_db->prepare($sql)->execute($_SESSION['user']);
$sql = "INSERT IGNORE INTO userlikedposts (ulp_userid,ulp_postid) VALUES (?, ?)";
$this->_db->prepare($sql)->execute([$_SESSION['user'], $pid]);
$stmt = $this->_db->prepare("SELECT likes FROM postsinitial WHERE pid = ?");
$stmt->execute([$pid]);
return $stmt->fetchColumn();
}
I have a select where I have 3 results:
$stmt = $handler->prepare("SELECT id,comments,likes,views FROM sites WHERE usr_id = '$usr_id'");
$stmt->execute();
After this select I have 3 results. Now I want in another table update or insert a new row for each result
This is my complete code
I don't have any update or new insert in table. Can anybody please help me?
$stmt = $handler->prepare("SELECT id,comments,likes,views FROM sites WHERE usr_id = '$usr_id'");
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$rows[]=$row;
foreach($rows as $row){
$site_id = $row[id];
$stmt = $handler->prepare("SELECT id FROM session WHERE site_id = '$site_id' AND usr_id = '$usr_id'");
$stmt->execute();
$no=$stmt->rowCount();
if ($no > 0)
{
$stmt = $handler->prepare("UPDATE session SET comments = '$comments' , likes = '$likes' , views = '$views' WHERE usr_id = $usr_id AND site_id = $site_id");
$stmt->execute();
}
else
{
$stmt = $handler->prepare("INSERT INTO session(user_id,site_id,comments,likes,views)VALUES('$user_id','$site_id','$comments','$likes','$views')");
$stmt->execute();
}
}
}
First issue, you weren't taking advantage of prepared statements at all. Use parameters (the ? in the query) and then fill them with values in the execute() call.
Also, prepare your query outside a loop, and execute it inside. This is one of the key advantages of preparing statements in advance, there is less overhead when they are only prepared once.
Finally, there's no need for checking the database before your query and then executing one of two queries. Just let MySQL check if the value exists already with INSERT...ON DUPLICATE KEY UPDATE syntax. This relies on the database being set up properly, so there should be a UNIQUE index on (session.usr_id, session.site_id).
This is untested, but should get you going:
$stmt1 = $handler->prepare("SELECT id,comments,likes,views FROM sites WHERE usr_id = ?");
$stmt2 = $handler->prepare("INSERT INTO session SET comments = ?, likes = ?, views = ?, usr_id = ?, site_id = ? ON DUPLICATE KEY UPDATE comments = VALUES(comments), likes = VALUES(likes), views = VALUES(views)");
$stmt1->execute(array($usr_id));
while($row = $stmt1->fetch(PDO::FETCH_ASSOC)) {
$site_id = $row["id"];
$stmt2->execute(array($comments, $likes, $views, $usr_id, $site_id));
}
#Miken32's answer would be the ideal way.
A direct fix to your code would be this way:
$stmt1 = $handler->prepare("SELECT id,comments,likes,views FROM sites WHERE usr_id = :usr_id");
$stmt1->bindValue(':usr_id', $usr_id);
$stmt1->execute();
while ($row = $stmt1->fetch(PDO::FETCH_ASSOC)) {
$stmt2 = $handler->prepare("SELECT id FROM session WHERE site_id = :site_id AND usr_id = :usr_id");
$stmt2->bindValue(':usr_id', $usr_id);
$stmt2->bindValue(':site_id', $row['id']);
$stmt2->execute();
if ($stmt2->rowCount() > 0) {
$stmt3 = $handler->prepare("UPDATE session SET comments = :comments , likes = :likes , views = :views WHERE usr_id = :usr_id AND site_id = :site_id");
} else {
$stmt3 = $handler->prepare("INSERT INTO session(user_id,site_id,comments,likes,views)VALUES(:usr_id,:site_id,:comments,:likes,:views)");
}
$stmt3->bindValue(':comments', $row['comments']);
$stmt3->bindValue(':likes', $row['likes']);
$stmt3->bindValue(':views', $row['views']);
$stmt3->bindValue(':usr_id', $usr_id);
$stmt3->bindValue(':site_id', $row['id']);
$stmt3->execute();
}
But this is not the best way to go about it. INSERT ...UPDATE ON DUPLICATE KEY would be better.
So i think i'm close to figuring this out but my query won't add the item from the "pending" table to the "items" table. can you guys help me out with this please. Also if i want it to delete after it gets added should i add the code below the INSERT INTO SELECT query? thanks
action.php:
$sql = "INSERT INTO items (photo,title,description, name) SELECT (photo,title,description, name) FROM pending";
$stmt = $conn->prepare($sql);
$stmt->execute();
Example for delete query after it takes the item from the "pending" into items:
$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT);
//try deleting record using the record ID we received from POST
$sql = "DELETE FROM pending WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $idToDelete, PDO::PARAM_INT);
$stmt->execute();
I think you are leaving yourself open to mistakes doing it this way.
Consider what would happen if a new row is added to the pending queue after you have issued the INSERT SELECT but before you have started your delete.
I think you need to do this in a more controlled way inside a single loop to make sure you are only deleting what you have copied from pending into items.
$sql = "SELECT photo,title,description, name FROM pending";
$select_pending = $conn->prepare($sql);
$select_pending->execute();
$sql = "INSERT INTO items (photo,title,description, name)
VALUES (:photo,:title,:description, :name)";
$insert_items = $conn->prepare($sql);
$sql = "DELETE FROM pending WHERE id = :id";
$delete_pending = $conn->prepare($sql);
// only if you are using INNODB databases.
//$conn->beginTransaction();
while( $row = $select_pending->fetch_object() ) {
$insert_items->bindParam(':photo', $row->photo, PDO::PARAM_STR);
$insert_items->bindParam(':title', $row->title, PDO::PARAM_STR);
$insert_items->bindParam(':description', $row->description, PDO::PARAM_STR);
$insert_items->bindParam(':name', $row->name, PDO::PARAM_STR);
$insert_items->execute();
$delete_pending->bind_param(':id', $row->id, PDO::PARAM_INT);
$delete_pending->execute();
}
// only if you are using INNODB databases.
//$conn->commit();
$sql = "INSERT INTO items (photo,title,description, name)
SELECT photo,title,description, name FROM pending";
remove the () in the SELECT statement.
How can I allow the user submitting a form, to update his entry on "re-submission"
for example
12345678910 (unique id) , submitted the form with selections,
12345678910 , re-submitted with new selections
what's the function responsible for "automatically" updating such kind of form entries.
I know that I can use a check if the entry exists, but how do I update it if it exists and insert it in a new row if it doesn't ...
function checkstudentid($studentid)
{
$con = connectvar();
mysql_select_db("database1", $con);
$result = mysql_query(
"SELECT * FROM table WHERE studentid='$studentid' LIMIT 1");
if(mysql_fetch_array($result) !== false)
....
// I want to add the entry here since it doesn't exist...with checkboxes
// else , I want to update if it already exists
}
Now I'm also not completely positive if the above code will work...but this is what I have for starters, if there is any other way or if the method I'm using is "wrong" , I would appreciate the heads up...or if what I'm trying to is even possible (the way I'm doing it)...
NOTES
I only have one php file which the form submits to.
I am not using a login/registration system
I do not want to display all the data in a table using HTML, just an
"automatic" update if the studentid already exists in the table
If I were using a deprecated method to interact with a database, I would probably just do this:
<?php
function checkstudentid($studentid) {
$con = connectvar();
mysql_select_db("database1", $con);
$result = mysql_query(
"SELECT * FROM table WHERE studentid='$studentid' LIMIT 1");
$query = '';
if (mysql_num_rows($result) > 0) {
$query = "UPDATE table SET column1='$value_one', column2='$value_two' WHERE studentid='$studentid'";
} else {
$query = "INSERT INTO table VALUES('$new_id', '$value_one', '$value_two')";
}
if (mysql_query($query)) {
return true;
} else {
return false;
}
}
?>
But then again, I would use PDO to interact with the DB.
Here is a simple PDO example (you just have to write the function to return the connection):
<?php
function checkstudentid($studentid) {
$update = false;
$dbh = formPDOConnection();
$query = "SELECT studentid FROM table WHERE studentid=:id";
$stmt = $dbh->prepare($query);
$stmt->bindValue(':id', $studentid, PDO::PARAM_STR);
if ($stmt->execute()) {
if ($stmt->rowCount()) {
$update = true;
}
} else {
return 'failure to execute query';
}
// if we just need to update
if ($update) {
$update = "UPDATE table SET value1=:v1,
value2=:v2 WHERE studentid=:id";
$stmt = $dbh->prepare($update);
$stmt->bindValue(':id', $studentid, PDO::PARAM_STR);
$stmt->bindValue(':v1', $value_one, PDO::PARAM_STR);
$stmt->bindValue(':v2', $value_two, PDO::PARAM_STR);
} else {
$insert = "INSERT INTO table VALUES(:id,:v1,v2)";
$stmt = $dbh->prepare($insert);
$stmt->bindValue(':id', $new_id, PDO::PARAM_STR);
$stmt->bindValue(':v1', $value_one, PDO::PARAM_STR);
$stmt->bindValue(':v2', $value_two, PDO::PARAM_STR);
}
return $stmt->execute();
}
?>
Save yourself a headache and stop using mysql_*
You can use INSERT... ON DUPLICATE KEY UPDATE... on your mysql code instead use the logic in your PHP.
Here's a sample:
INSERT INTO `category` (`id`, `name`) VALUES (12, 'color')
ON DUPLICATE KEY UPDATE `name` = 'color';
Reference: http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html