The script will not save the data to mysql - php

I am pulling my hair out about this script below. No mater what I do it will not save the data sent to it. I have set the script of many different ways and also tested it like I show below.
I have set the part that sends it to the script like this $pid = 6 $emailmsg = 1 etc.... and it worked. This is what is not making any sense to me. I have used this same script but with different var at least a dozen times in this program with no problem.
This is what the data looks like that I am sending to the script
print_r($_POST);
[emailmsg] => 1 [emailrt] => 2 [pid] => 6 [$emrtid] => 48 [$emmsid] => 46
This is one of the script that will not send the data to the database
$stmt = $db->prepare("UPDATE options SET pid = ?,emailmsg = ? WHERE id = ?");
echo $stmt->execute(array($_POST['pid'],$_POST['emailmsg'],$_POST['emmsid']));
$stmt = $db->prepare("UPDATE options SET pid = ?, emailrt = ? WHERE id = ?");
$stmt->execute(array($_POST['pid'],$_POST['emailrt'],$_POST['emrtid']));
I also tried it like this
$sql = "UPDATE options SET
pid = ?,
emailmsg = ?
WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->bindValue('1', $_POST['pid'], PDO::PARAM_INT);
$stmt->bindValue('2', $_POST['emailmsg'], PDO::PARAM_STR);
$stmt->bindValue('3', $_POST['emmsid'], PDO::PARAM_INT);
$stmt->execute();
$sql = "UPDATE options SET
pid = ?,
emailrt = ?
WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->bindValue('1', $_POST['pid'], PDO::PARAM_INT);
$stmt->bindValue('2', $_POST['emailrt'], PDO::PARAM_STR);
$stmt->bindValue('3', $_POST['emrtid'], PDO::PARAM_INT);
$stmt->execute();

If you literally copied your print_r output to your question, the problem is that your WHERE condition is never met so no row is ever updated.
This:
echo $stmt->execute(array($_POST['pid'],$_POST['emailmsg'],$_POST['emmsid']));
should be:
echo $stmt->execute(array($_POST['pid'],$_POST['emailmsg'],$_POST['$emmsid']));
// ^ that's what it looks like in your print_r
The same applies to $_POST['emrtid'] in your second query: $_POST['$emrtid'].

Try like using named parameter:
$stmt = $db->prepare("UPDATE options SET pid = :pid, emailrt = :emailrt WHERE id = :emrtid");
$stmt->execute(array('pid'=>$_POST['pid'],
'emailrt'=>$_POST['emailrt'],
'emrtid'=>$_POST['emrtid']
));

Related

Stop User From Liking Post Multiple Times

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

PDO PHP bindParam() repeated use of same parameters

Yesterday i decided to learn PDO and rewrite our server php to PDO.
The thing that jumped to my mind while rewriting the code is the need of repeated use of bindParam for the same parameters i already used.
Here is an example:
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->beginTransaction();
$stmt = $dbh->prepare("INSERT INTO Products(productID,numOfLikes) VALUES (:productID,0) ON DUPLICATE KEY UPDATE productID = productID;");
$stmt->bindParam(":productID",$productID);
$stmt->execute();
if($customerID !== 0){
//*****Check, if customerID is in the Database, else add the customerID to the Database.
$stmt = $dbh->prepare("INSERT INTO Customers(customerID) VALUES (:customerID) ON DUPLICATE KEY UPDATE customerID = customerID;");
$stmt->bindParam(":customerID",$customerID);
$stmt->execute();
//*****if customerID and productID are NOT registered together ,then register and add +1 to productID numOfLikes
$stmt = $dbh->prepare("SELECT customerID, productID FROM CustomerProducts WHERE productID = :productID AND customerID = :customerID");
$stmt->bindParam(":productID",$productID);
$stmt->bindParam(":customerID",$customerID);
$stmt->execute();
if ($stmt->rowCount() == 0) {
//echo "added";
$stmt = $dbh->prepare("INSERT INTO CustomerProducts(customerID, productID) Values (:customerID,:productID)");
$stmt->bindParam(":customerID",$customerID);
$stmt->bindParam(":productID",$productID);
$stmt->execute();
$stmt = $dbh->prepare("UPDATE Products SET numOfLikes = numOfLikes + 1 WHERE productID = :productID");
$stmt->bindParam(":productID",$productID);
$stmt->execute();
}else {
//echo "removed";
$stmt = $dbh->prepare("DELETE FROM CustomerProducts WHERE productID = ".$productID." AND customerID = ".$customerID);
$stmt->bindParam(":customerID",$customerID);
$stmt->bindParam(":productID",$productID);
$stmt->execute();
$stmt = $dbh->prepare("UPDATE Products SET numOfLikes = numOfLikes - 1 WHERE productID = ".$productID);
$stmt->bindParam(":productID",$productID);
$stmt->execute();
}
}
$dbh->commit();
Is there a way to write it in "prettier way"?
Can you see any flows in that could. I would appreciate every help.
Note: this code will be for production use in the near future.
Yes there is...
You can supply bindParam as an array to the execute function...
Something like this:
$statement->execute([
':username'=> $username,
':password'=> $password
]);
It's using bindParam and execute in just one statement, and it looks cleaner in my opinion.
Yes, you can get around the repeated variables by defining mySql user variables like this:
$psVars = $dbh->prepare("SET #pid = :productID;");
$psVars->bindParam(':productID', $productID);
$psVars->execute();
Then, in subsequent statements, just use #pid instead of a bound parameter

limit entry to db while added new records

ok i have this recent visits table and the following code i use to enter records into the table user wise
if($user->is_logged_in() ){
$postid = $row['postid'];
$uid = $_SESSION['memberid'];
$stmt = "SELECT * FROM recent WHERE postid = :postid AND memberid = :memberid";
$stmt = $db->prepare($stmt);
$stmt->bindParam(':postid', $postid, PDO::PARAM_STR);
$stmt->bindParam(':memberid', $uid, PDO::PARAM_STR);
$stmt->execute();
$recentCount = $stmt->rowCount();
if(!$recentCount)){
$stmt = $db->prepare('INSERT INTO recent (postid,memberid) VALUES ( :postid,:memberid)');
$stmt->execute(array(
':postid' => $postid,
':memberid' => $uid
));
}
}
but the thing is i wish to limit records, as in per user only 50 records should be in db. supposing user visits a new topic then if there already 50 records in recent table for the user then the number 50 gets deleted and 49 record becomes 50. i hope you get my point?
its just that records per user should not exceed above 50 is what i mean.
Based on the question and comments, I think you can do it like this (you didn't mention the name of your date field but for this example I'll assume it's called createddate):
if($user->is_logged_in() ){
$postid = $row['postid'];
$uid = $_SESSION['memberid'];
$stmt = "SELECT COUNT(*) FROM recent WHERE postid = :postid AND memberid = :memberid"; //let mysql count the rows
$stmt = $db->prepare($stmt);
$stmt->bindParam(':postid', $postid, PDO::PARAM_STR);
$stmt->bindParam(':memberid', $uid, PDO::PARAM_STR);
$stmt->execute();
$recentCount = $stmt->fetchColumn(); //fetch first column in first row, this will be the count result
if($recentCount >= 50)
{
$stmt2 = $db->prepare('DELETE FROM recent WHERE createddate = (select min(createddate) where memberid = :memberid)');
$stmt2->bindParam(':memberid', $uid, PDO::PARAM_STR);
$stmt2->execute();
}
$stmt = $db->prepare('INSERT INTO recent (postid,memberid) VALUES ( :postid,:memberid)');
$stmt->execute(array(
':postid' => $postid,
':memberid' => $uid
));
Apologies if the PDO syntax is wrong, I haven't used it in a while. I'm sure you can make that right yourself. But the important thing is the structure of the PHP "if" statement and the "delete" SQL.

PHP PDO search for a value in two or more columns using one string

When I want to find a value from a row using PDO I use the following method:
//Search whether user exists
$sqlQueryEmailLogin = $dbh->prepare("SELECT vendor_id, first_name, last_name, email_login, user_password, passport_id, login_attempts, login_last_attempt FROM $tableVendorDetails WHERE email_login = ?");
$sqlQueryEmailLogin->bindValue(1, $emailLogin);
$sqlQueryEmailLogin->execute();
and the following PHP code for the search field
$emailLogin = 'xyz#abc.com'
Now I'd like to search two columns or more and use the following code
$sql = "SELECT * FROM articles WHERE id = ? AND status = ?";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, $id);
$stmt->bindValue(2, $status);
$stmt->execute();
I'd like to search the two columns from a string. How should I go about it, please?
The string value i go is from a html form with one input box
I'd like a string that is capable of searching two values from a MySQL table e.g.
$search = $id; and
$seach = $status;
in this case both cancel each other
You could simplify it by using the method described by #gbestard. But you should also do this:
$search = 'asdf'; // fill this with your form input
$sql = "SELECT * FROM articles WHERE id = :id OR status = :status";
$stmt = $conn->prepare($sql);
$stmt->execute(array(
':id' => $search,
':status' => $search,
));
Notice the change to OR in the query, and supplying the $search multiple times...
That's what I'm using
$sql = "SELECT * FROM articles WHERE id = :id AND status = :status";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':id' => $id , ':status' => $status));
Try the following
$sql = "SELECT * FROM articles WHERE id = :id AND status = :status";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':id', $id);
$stmt->bindValue(':status', $status);
$stmt->execute();
See docs http://php.net/manual/en/pdostatement.bindvalue.php
You should use OR instead of AND. That way, you will get all rows that match either by id or by status.
SELECT * FROM articles WHERE id = ? OR status = ?

How can I properly use a PDO object for a parameterized SELECT query

I've tried following the PHP.net instructions for doing SELECT queries but I am not sure the best way to go about doing this.
I would like to use a parameterized SELECT query, if possible, to return the ID in a table where the name field matches the parameter. This should return one ID because it will be unique.
I would then like to use that ID for an INSERT into another table, so I will need to determine if it was successful or not.
I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.
$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();
You can use the bindParam or bindValue methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
A litle bit complete answer is here with all ready for use:
$sql = "SELECT `username` FROM `users` WHERE `id` = :id";
$q = $dbh->prepare($sql);
$q->execute(array(':id' => "4"));
$done= $q->fetch();
echo $done[0];
Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();
I hope this help someone, Enjoy!
Method 1:USE PDO query method
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Getting Row Count
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Method 2: Statements With Parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Method 3:Bind parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Want to know more look at this link
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}

Categories