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']."'";
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);
}
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 . "';";
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.
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);
}
}