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.
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();
}
please help me out and sorry for my bad English,
I have fetch data , on basis of that data I want to update the rows,
Follows my code
I fetched data to connect API parameters
<?php
$stmt = $db->stmt_init();
/* publish store for icube*/
$stmt->prepare( "SELECT id,offer_id,name,net_provider,date,visible,apikey,networkid FROM " ."affilate_offer_findall_icube WHERE visible='1' ");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result( $id, $offer_id, $name, $net_provider, $date, $visible,$apikey,$networkid);
$sql = array();
if($rows>0)
{
while($info = $stmt->fetch() ) {
$jsondataicube = file_get_contents('filename/json?NetworkId='.$networkid.'&Target=Affiliate_Offer&Method=getThumbnail&api_key='.$apikey.'&ids%5B%5D='.$offer_id.'');
$dataicube = json_decode($jsondataicube, true);
foreach($dataicube['response']['data'][0]['Thumbnail'] as $key=>$val)
{
$offer_id = $dataicube['response']['data'][0]['Thumbnail']["$key"]['offer_id'];
$display = $dataicube['response']['data'][0]['Thumbnail']["$key"]['display'];
$filename = $dataicube['response']['data'][0]['Thumbnail']["$key"]['filename'];
$url = $dataicube['response']['data'][0]['Thumbnail']["$key"]['url'];
$thumbnail = $dataicube['response']['data'][0]['Thumbnail']["$key"]['thumbnail'];
$_filename = mysqli_real_escape_string($db,$filename);
$_url = mysqli_real_escape_string($db,$url);
$_thumbnail = mysqli_real_escape_string($db,$thumbnail);
$sql[] = '("'.$offer_id.'","icube","'.$_thumbnail.'","'.$_url.'")';
}
}
As I store values which have to be inserted in 'sql'
now
$stmt->prepare( "SELECT offer_id FROM " ."affilate_offer_getthumbnail_icube ORDER BY 'offer_id' ASC");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result($offer_id);
$sqlimplode = implode(',', $sql);
if($rows>0)
{
$query = "UPDATE affilate_offer_getthumbnail_icube WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}`
`
Insert query working well,but how can I update all the data like insert query ?
My Answer is refering to a "set and forget"-strategy. I dont want to look for an existing row first - probably using PHP. I just want to create the right SQL-Command and send it.
There are several ways to update data which already had been entered (or are missing). First you should alter your table to set a problem-specific UNIQUE-Key. This is setting up a little more intelligence for your table to check on already inserted data by its own. The following change would mean there can be no second row with the same value twice in this UNIQUE-set column.
If that would occur, you would get some error or special behaviour.
Instead of using PHPMyAdmin you can use this command to set a column unique:
ALTER TABLE `TestTable` ADD UNIQUE(`tablecolumn`);
After setting up your table with this additional intelligence, you alter your Insert-Command a little bit:
Instead of Insert you can drop and overwrite your Datarow with
REPLACE:
$query= "REPLACE INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100) VALUES (".$sqlimplode.")";
See: Replace Into Query Syntax
Secondly you can do this with the "On Duplicate Key"-Commando.
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
$query= "INSERT INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100)
VALUES (".$sqlimplode.")
ON DUPLICATE KEY UPDATE net_provider = ".$newnetprovider.",
logo2020 = ".$newlogo2020.",
logo100 = ".$newlogo100.";";
Note: I think you missed some ( and ) around your $sqlimplode. I always put them around your implode. Maybe you are missing ' ' around strings as well.
Syntax of UPDATE query is
UPDATE table SET field1 = value1, field2 = value2 ...
So, you cannot pass your imploded array $sql to UPDATE query. You have to generate another sql-string for UPDATE query.
This is clearly incorrect:
$query = "UPDATE affilate_offer_getthumbnail_icube
WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
If the intention is to INSERT offer_id='".$offer_id."' and then UPDATE ... SET offer_id = '".$sqlimplode."'";
You have to use two separate queries, one for INSERT and then another one for UPDATE
An Example:
$query = "INSERT INTO affilate_offer_getthumbnail_icube
(col_name) VALUES('".$col_Value."')";
//(execute it first);
$query2 = "UPDATE affilate_offer_getthumbnail_icube SET
col_name= '".$col_Value."'" WHERE if_any_col = 'if_any_Value';
//(execute this next);
Try this:
$sqlimplode = implode(',', $sql);
if($rows>0)
{
/*$fields_values = explode(',',trim(array_shift($sql), "()"));
$combined_arr = array_combine(['offer_id','net_provider','logo2020','logo100'],$fields_values);
$sqlimplode = implode(', ', array_map(function ($v, $k) { return $k . '=' . $v; }, $combined_arr, array_keys($combined_arr))); */
$query = "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode." ON duplicate key update net_provider = values(net_provider),logo2020 = values(logo2020),logo100 = values(logo100)";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$sqlimplode = implode(',', $sql);
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}
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) ?
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 />";
}