Deleting and Adding items to database based on multiselect list - php

I am currently trying to make a multi select list where items can be added and removed based on two columns. The left column is the full list and the right column where all the selected items are displayed. On submit the right column adds all newly selected items into the USERVIDEOS database.
The issue however is removing items from the USERVIDEOS database if they are removed from the right column. When pressing submit the USERVIDEOS database should only have rows for items currently in the right column and remove those no longer in there.
Example image
I have several items however I am unable to solve the issue. I've tried the following code:
if($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['user-videos'])) {
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("DELETE FROM USERVIDEOS WHERE userID = :userID AND videoID NOT IN (:videos)");
$stmt->bindParam(':userID', $userID);
$stmt->bindValue(':videos', implode(",", $_POST['user-videos']));
$stmt->execute();
// Add the new Videos
$stmt = $conn->prepare("INSERT INTO USERVIDEOS (userID, videoID) VALUES (:userID, :videoID)");
$stmt->bindParam(':userID', $userID);
$selected = $_POST['user-videos'];
foreach ($selected as $videoID) {
$stmt->bindParam(':videoID', $videoID);
$stmt->execute();
}
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
however, this results in removing everything but the newly selected items. The goal is to only remove those that got removed from the right column and add those that got added to the right column.
HTML
<div class="form_container">
<form name="videos" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="lvids">
<label for="video-list">Database Videos:</label>
<select class="videolist" id="video-list" size="10" name="video-list[]" multiple>
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Retrieve all video IDs from the USERVIDEOS table
$stmt1 = $conn->prepare("SELECT videoID FROM USERVIDEOS WHERE userID = :userID");
$stmt1->bindParam(':userID', $userID);
$stmt1->execute();
$filterVideos = $stmt1->fetchAll(PDO::FETCH_COLUMN, 0);
if(sizeof($filterVideos) != 0) {
$stmt2 = $conn->prepare("SELECT ID, videotitle FROM VIDEOS WHERE ID NOT IN (".implode(',', $filterVideos).") ORDER BY categorie ASC");
$stmt2->execute();
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['ID'] . "'>" . $row['videotitle'] . "</option>";
}
} else {
$stmt = $conn->prepare("SELECT ID, videotitle FROM VIDEOS ORDER BY categorie ASC");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['ID'] . "'>" . $row['videotitle'] . "</option>";
}
}
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
$conn = null;
$stmt = null;
?>
</select>
</div>
<div class="button_container">
<input class="btn" type="button" value=">>" id="add-btn">
<input class="btn" type="button" value="<<" id="remove-btn">
</div>
<div class="uvids">
<label for="user-videos">Selected Videos:</label>
<select class="uservideos" id="user-videos" size="10" name="user-videos[]" multiple>
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT VIDEOS.ID, VIDEOS.videotitle FROM VIDEOS
JOIN USERVIDEOS ON USERVIDEOS.videoID = VIDEOS.ID
WHERE USERVIDEOS.userID = :userID");
$stmt->bindParam(':userID', $userID);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row) {
echo "<option value='" . $row['ID'] . "'>" . $row['videotitle'] . "</option>";
}
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
?>
</select>
</div>
<br><br>
<input type="submit" value="Upload Videos">
</form>
</div>
If more information is required, just ask.

I've found a solution (non ideal) to the problem.
I've utilized javascript to select all options within the right column on the button submit. After this PHP removed all entries within the database where userID = $userID and after this adds all selected options back in.
The problem has been solved with a workaround. However, ideally, the database should remove everything and add items back that were there before.
Javascript utilized to select all options within the select:
$('#submit-button').click(function(event) {
event.preventDefault(); // prevent the form from being submitted
$('#user-videos option').prop('selected', true);
$('#videos').submit();
});

Related

delete mysql row by retrieving id PHP foreach

I've created a foreach statement that echos out some stuff about all users registered, how do I make a button that deletes that user from the row? I've tried this:
$query = "
SELECT id
, name
, bname
, email
, address
, agent
, status
, notes
FROM prospects
";
try {
$stmt = $db->prepare($query);
$stmt ->execute();
}
catch(PDOException $ex) {
die("Failed to run query. Tell the website owner!");
}
$rows = $stmt->fetchAll();
foreach($rows as $row) {
echo "<tbody>
<th>".$row['name']."</th>";
echo "BLAH BLAH BLAH!";
echo "<form method='post'><th><button type='submit' name='delete' class='btn btn-white btn-round btn-just-icon'>
<i class='material-icons'>remove_circle_outline</i>
<div class='ripple-container'></div>
</button></th></tbody></form>";
} $id = $db->prepare("SELECT id FROM example");
$id->execute();
$result = $id->fetch(PDO::FETCH_ASSOC);
if(isset($_POST['delete'])) {
try {
$sql = "DELETE FROM example WHERE id='".$result."'";
$db->exec($sql);
}
catch(PDOException $e) {
echo $sql . "<br />". $e->getMessage();
}
}
It returns this error:
Notice: Array to string conversion....
I know this is because I've grabbed the id and there is an array of ids that I've grabbed from the database? So how do I do delete a specific row when i click on the button?
You have to specify which element in array holds the id value.
Try:
$sql = "DELETE FROM example WHERE id='".$result['id']."'";

How to create autocomplete with PHP PDO and MariaDB to return concatenate values

I have a problem , i want to create with autocomplete to get back suggested information e.g A11 - some text, but i get back only e.g A11. I think that definetly problem is passing values from query in array and how to pass and structure array to display wanted data with autocomplete.
HTML
<form action='' method='post'>
<p><label>MKB dijagnoze: </label><input type='text' name='sifra_mkb' value='' class='auto'></p>
</form>
PHP
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";port=3306;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT sifra_mkb,naziv_mkb FROM i_dijagnoze WHERE sifra_mkb LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['sifra_mkb'].' '.$row['naziv_mkb'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($return_arr);
}

PHP - Search Using Form and Return Back Records

I am working in PHP/HTML/SQLITE3. I have a database that consist of several tables, one of the tables is called Item, which contains an itemID, name of item, and so forth. So my search takes the user input of the itemID and what I am suppose to return back is everything associated with that itemID.
I have tested out my search and it does return back the itemID, however, I am having a bit of trouble figuring out how to return back everything related to the itemID. Down below are my search form and what I have for a seperate file which contains the query.
<form method="POST" action="action.php">
<input name="search" type="text" size="20" maxlength="10"/>
<input type="submit" value="Search"/>
</form>
-----
<?php
if (isset($_POST["search"])) {
$itemID = $_POST["search"];
try {
$db->beginTransaction();
$query = "SELECT * FROM Item WHERE itemID = '$itemID';";
$result = $db->query($query);
if (empty($_POST['search'])){
echo "<strong>You didn't fill in anything!</strong>";
}
else {
echo $itemID;
}
$db->commit();
}
$db = null;
?>
Edit Code (Addition of attempt at fetchall):
<?php
if (isset($_POST["search"])) {
$itemID = $_POST["search"];
try {
$db->beginTransaction();
$query = "SELECT * FROM Item WHERE itemID = '$itemID';";
#$result = $db->query($query);
$result = sqlite_fetch_all($query, SQLITE_ASSOC);
foreach($result as $entry) {
echo 'ItemID: ' . $entry['itemID'] . ' Item Name' . $entry['name'];
}
if (empty($_POST['search'])){
echo "<strong>Esteemed customer did not fill in a
itemID number, please search again. </strong>";
}
$db->commit();
}
2nd Attempt:
<?php
$dbname = "mydatabase.db";
try {
// Establish connection to "mydatabase.db"
$db = new PDO("sqlite:" . $dbname);
// Set error handling so that errors throw an exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Enable foreign key constraints on the database
$db->exec("PRAGMA foreign_keys = ON;");
} catch (PDOException $e) {
echo "SQLite connection failed: " . $e->getMessage();
exit();
}
if (isset($_POST["search"])) {
$itemID = $_POST["search"];
try {
$sth = $db->prepare("SELECT * FROM Item WHERE itemID = '$itemID'");
#$query = "SELECT * FROM Item WHERE itemID = '$itemID';";
#$result = $db->query($query);
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
#if (empty($_POST['search'])){
#echo "<strong>Esteemed customer did not fill in a
#itemID number, please search again. </strong>";
}
}
?>
Any input would be greatly appreciated.
You should concatenate the itemid to the query
$query = "SELECT * FROM Item WHERE itemID = '" . $itemID . "';";

How to fetch checkbox

This is my HTML code:
<input type='checkbox' name='cbox[]' value='Jaywalking'/>
Jaywalking<br/>
<input type='checkbox' name='cbox[]' value='Littering'/>
Littering<br/>
<input type='checkbox' name='cbox[]' value='Illegal Vendor'/>
Illegal Vendor
This is my posting code:
if(is_array($_POST['cbox']))
$violation_save=implode(',',$_POST['cbox']);
else
$violation_save=$_POST['cbox'];
mysql_query("UPDATE tblcitizen SET violation='$violation_save' WHERE id='$id'") or die mysql_error());
How can I fetch the selected values from the database?
First of all you should NOT use the mysql_* functions of php anymore. These functions are marked as deprecated and will be removed in the next major php release.
So if $_POST['cbox'] is an array, you must handle it as an array.
// how to save checked values
try {
$db = new PDO(...);
$stmt = $db->prepare("UPDATE yourTable SET myField = :myField WHERE id = :id");
$stmt->bindParam(':id' , $id, PDO::PARAM_INT);
foreach ($_POST['cbox'] as $myField) {
$stmt->bindParam(':myField', $myField);
$stmt->execute();
}
} catch (PDOException $e) {
// error handling
}
// how to fetch checked values
try {
$myValues = array();
$db = new PDO(...);
$stmt = $db->prepare("SELECT myField FROM myTable WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$myValues[] = $row['myField'];
}
} catch (PDOException $e) {
// error handling
}
// HTML Part
<input type="checkbox" name="cbox[]" value="bla"<?php if (in_array('bla', $myValues)) { ?> checked="checked"<?php } ?> />
Just have a look at the php manual for PDO or the MySQLi extension.

MySQL update, skip blank fields with PDO

I would like to update a MySQL row via the form below. The form works great as is but, if I leave a field blank, it changes the field in MySQL to blank as well. I would like to update the sql but skip over any fields that are blank.
I have read a few ways of doing this but they didn't seem logical. I.e. using if statements in the sql string itself. (Having MySQL do the work that should be done in PHP).
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
echo '<form method="post" action="">
ID: <input type="text" name="a" /><br>
Program: <input type="text" name="b" /><br>
Description: <textarea row="6" cols="50" name="c"></textarea><br>
Cost: <input type="text" name="d"><br>
<input type="submit" value="Add Link" />
</form>';
}
try {
$dbh = new PDO($dsn, $user, $pass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $dbh->prepare('UPDATE links SET Program = :program , Descr = :descr, Cost = :cost WHERE Id= :id');
$stmt->bindParam(":id", $_POST["a"]);
$stmt->bindParam(":program", $_POST["b"]);
$stmt->bindParam(":descr", $_POST["c"]);
$stmt->bindParam(":cost", $_POST["d"]);
$stmt->execute();
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());}
$dbh = null;
}
}catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Something like this should work
.
.
.
$q = array();
if(trim($_POST["b"]) !== ""){
$q[] = "Program = :program";
}
if(trim($_POST["c"]) !== ""){
$q[] = "Descr = :descr";
}
if(trim($_POST["d"]) !== ""){
$q[] = "Cost = :cost";
}
if(sizeof($q) > 0){//check if we have any updates otherwise don't execute
$query = "UPDATE links SET " . implode(", ", $q) . " WHERE Id= :id";
$stmt = $dbh->prepare($query);
$stmt->bindParam(":id", $_POST["a"]);
if(trim($_POST["b"]) !== ""){
$stmt->bindParam(":program", $_POST["b"]);
}
if(trim($_POST["c"]) !== ""){
$stmt->bindParam(":descr", $_POST["c"]);
}
if(trim($_POST["d"]) !== ""){
$stmt->bindParam(":cost", $_POST["d"]);
}
$stmt->execute();
}
.
.
.
Change the statement:
$stmt = $dbh->prepare('UPDATE links SET Program = :program , Descr = :descr, Cost = :cost WHERE Id= :id');
As follows:
$stmt = $dbh->prepare('UPDATE links SET Program = IF(trim(:program)="", Program, :program) , Descr = IF(trim(:descr)="", Descr, :descr), Cost = IF(trim(:cost)="", Cost, :cost) WHERE Id= :id');
Check post field for empty :
It will skip update query if any field data is empty.
If( $_POST["a"] && $_POST["b"] && $_POST["c"] && $_POST["d"]){
try {
$dbh = new PDO($dsn, $user, $pass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $dbh->prepare('UPDATE links SET Program = :program , Descr = :descr, Cost = :cost WHERE Id= :id');
$stmt->bindParam(":id", $_POST["a"]);
$stmt->bindParam(":program", $_POST["b"]);
$stmt->bindParam(":descr", $_POST["c"]);
$stmt->bindParam(":cost", $_POST["d"]);
$stmt->execute();
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());}
$dbh = null;
}
}catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
Option2 Update all fields except empty:
try {
$sql ="UPDATE links SET ";
if($_POST["a"])
$sql .=" Program = :program ,";
if($_POST["b"])
$sql .=" Descr = :descr ,";
if($_POST["c"])
$sql .=" Cost = :cost ,";
$sql = rtrim($sql,',');
$dbh = new PDO($dsn, $user, $pass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $dbh->prepare($sql);
if($_POST["a"])
$stmt->bindParam(":id", $_POST["a"]);
if($_POST["b"])
$stmt->bindParam(":program", $_POST["b"]);
if($_POST["c"])
$stmt->bindParam(":descr", $_POST["c"]);
$stmt->execute();
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());}
$dbh = null;
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
It is easier to use unnamed parameters for dynamic queries in PDO and passing them as an array in execute(). The statement will not be executed unless at least 1 parameter is passed along with the id. I have left in the echo of the derived statement and the dump of the array.
Example statement
UPDATE `links` SET `Program` = ? , `Cost` = ? WHERE `Id` = ?
Example array
Array ( [0] => 2 [1] => 3 [2] => 2 )
if(isset($_GET['a'])){
$id = $_GET['a'];
$program = isset($_GET['b']) ? $_GET['b'] : NULL;
$descr = isset($_GET['c']) ? $_GET['c'] : NULL;
$cost= isset($_GET['d']) ? $_GET['d'] : NULL;
$params =array();
$sql = "UPDATE `links` SET "; //SQL Stub
if (isset($program)) {
$sql .= " `Program` = ? ,";
array_push($params,$program);
}
if (isset($descr)) {
$sql .= " `Descr` = ? ,";
array_push($params,$descr);
}
if (isset($cost)) {
$sql .= " `Cost` = ? ,";
array_push($params,$cost);
}
$sql = substr($sql, 0, -1);//Remove trailing comma
if(count($params)> 0){//Only execute if 1 or more parameters passed.
$sql .= " WHERE `Id` = ? ";
array_push($params,$id);
echo $sql;//Test
print_r($params);//Test
$stmt = $dbh->prepare($sql);
$stmt->execute($params);
}
}

Categories