I need some help I am trying to create a PHP form using sqlite3 database. I am looking up values from from an existing sqlite3 database in the table2 where the column id = 340 and display those values as a dropdown selection. Then once the value is selected by the user then the form is submitted by the users which updates the new values to the table1 with the values from the php form. I get it to display the names in the dropdown but when I click on the update button to submit the data it updates what the value is in the array.
For example lets say I have 3 fruits in the table and I select pear it updates the table with a "1" instead of the word "pear"
apple
pear
peach
PHP entry page Code:
<html>
<head>
<title></title>
</head>
<div class = "controlbox">
<body style="font-size:12;font-family:verdana">
<form action="post.php" method="post">
<p>
<h1> </h1>
<br>
<br>
Slot1 : <select name="slot1">
<option>--Available Options--</option>
<?php
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
$stmt2 = $db->query ("SELECT * FROM table2 where ID = '340' ");
$rowarray = $stmt2->fetchall(PDO::FETCH_ASSOC);
$slot1 = 0;
foreach($rowarray as $row)
{
echo "<option value = $slot1 >$row[FirstName] $row[LastName]</option>";
$slot1++;
}
?>
</select><br>
<p>
<input type="submit" name="update" value="update">
</p>
</form>
</body>
</html>
PHP Code: Post.php
<?php
$slot1 = sqlite_escape_string($_POST['slot1']);
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
if (!empty($slot1)) {
try
{
$stmt = $db->prepare("UPDATE table1 SET Slot1place = :slot1 WHERE ID = '340'");
$stmt->bindParam(':slot1', $slot1,PDO::PARAM_STR);
$stmt->execute();
}
catch(Exception $e)
{
echo $e->getMessage();
}
echo "submitted successfully";
}
?>
You dont use sqlite_escape_string if youre using a prepared statement like that. The values are going to be quoted witn they are bound to the statement.
I think you should check your html syntax (Is it missing tags, and the ).
Check it out at: http://www.w3schools.com/html5/tag_option.asp
echo "<option name = $name >$row[FirstName] $row[LastName]</option>";
Everything else is the right syntax
Related
I have been able to display the data from my database on to my website and I'm trying to delete a single row.
Now the button works but it completely deletes everything as you may tell from the code.
I have no idea on how to assign the delete button to a specific row in my table, where it just deletes that data in that specific row.
On top of this I have one delete button that sits upon my table and have no clue on how to set separate delete buttons for each row given.
admin.php (Displaying my data)
<?php
echo "<table style='box'>";
echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>Role</th>
<th>Email</th><th>Username</th><th>Delete</th><th>Amend</th></tr>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='box'>" . parent::current(). "</td>";
}
function beginChildren(){
echo "<tr>";
}
function endChildren(){
echo "</tr>";
}
}
require 'connection.php';
try {
$stmt = $conn->prepare("SELECT id, FirstName, LastName, Role, Email, Username FROM users");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v){
echo $v;
}
}
catch (PDOException $e){
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
<form method="post" action="delete.php">
<input <input class="btn-default" type="submit" name="login" value="Delete">
</form>
<?php
echo "</table>";
?>
delete.php
<?php
$servername = 'localhost';
$username = 'root';
$pass = 'root';
$database = 'tutor_database';
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//sql to delete record.
$sql = "DELETE FROM users WHERE id = id";
$conn->exec($sql);
echo "Record deleted!";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
I would show an image but I don't have enough reputation points to display it.
The WHERE clause in your DELETE statement will always return to true. On every row, ID will always equal ID. Hence, everything is deleted. You need to pass a parameter to delete script to filter on the row you want deleted. You can do so by a hidden HTML input value using get="method" of <form>.
However, the key is how to obtain that id from webpage's select query. Additionally, you will want to put the input button at the end of each row to delete the corresponding row's id. For these two items, you might have to return to traditional loop onto web page instead of the RecursiveArrayIterator() because we need to add a non fetched object (form delete button) into table.
admin.php (notice form button as last table cell of each row)
...same code as above...
try {
$stmt = $conn->prepare("SELECT id, FirstName, LastName, Role, Email, Username FROM users");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $result->fetch()) {
?>
<tr>
<td style="box"> <?php echo $row['id']; ?></td>
<td style="box"> <?php echo $row['FirstName']; ?></td>
<td style="box"> <?php echo $row['LastName']; ?></td>
<td style="box"> <?php echo $row['Role']; ?></td>
<td style="box"> <?php echo $row['Email']; ?></td>
<td style="box"> <?php echo $row['Username']; ?></td>
<td>
<form method="get" action="delete.php">
<input type="hidden" name="rowid" value="<?php echo $row['id']; ?>">
<input class="btn-default" type="submit" name="login" value="Delete">
</form>
</td>
<tr>
<?php
}
}
catch (PDOException $e){
echo "Error: " . $e->getMessage();
}
$conn = null;
delete.php (notice $id generated from $GET() and used in delete query)
$servername = 'localhost';
$username = 'root';
$pass = 'root';
$database = 'tutor_database';
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// OBTAIN ROWID FROM $_GET
if(isset($_GET['rowid'])) {
$id = $_GET['rowid'];
}
// DELETE SPECIFIED ROW
$sql = "DELETE FROM users WHERE id = ".$id;
$conn->exec($sql);
echo "Record deleted!";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
Trying to follow what you have. Have you tried setting the id to a var before doing?
$sql = "DELETE FROM users WHERE id = id";
Example:
$sql = "DELETE FROM users WHERE id = '$id'";
One problem is that your DELETE statement does not include a variable.
//sql to delete record.
$sql = "DELETE FROM users WHERE id = id";
You need something more like:
//sql to delete record.
$sql = "DELETE FROM users WHERE id = " . $id;
where $id is defined with the ID of the selected row.
Let's address another "hidden" problem.
Now the button works but it completely deletes everything as you may tell from the code.
Given the fact that you said this deletes ALL the records, I would guess that the id of each of your rows is the string 'id' and not a unique integer value.
DELETE FROM {table} WHERE id = {number} does not delete ALL records. It only deletes records matching the condition. You should make sure that you are setting id's correctly when adding rows. The id column should have the following properties: INT UNSIGNED NOT NULL AUTO_INCREMENT.
I have this function on my php:
function getLastMatchs($nb) {
try
{
$db = new PDO(DBHOST, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
die('connexion failed: '.$e->getMessage());
}
$i=0;
$get5tmatchs = $db->query('SELECT wid, lid, date, cwid, clid FROM `match`');
while ($nb<$i)
{
$data5matchs = $get5tmatchs->fetch();
echo '<tr>
<td>'.$data5matchs['wid'].'</td>';
echo '<td>'.$data5matchs['lid'].'</td>';
echo '<td>'.$data5matchs['cwid'].'</td>';
echo '<td>'.$data5matchs['clid'].'</td>';
echo '<td>'.$data5matchs['date'].'</td>
<br>
</tr>';
$i++;
}
}
And my form is:
echo '<form action="index.php" method="post">
<h3>My question......</h3>
<p>
<input type="text" name="nbmatchs" />
<input type="submit" value="ok" />
</p>
</form>';
echo getLastMatchs('nbmatchs');
How can i do for show nbmatch time the guys want my table ?
When i do now, nothing happen.
Thanks for your help
PS: For exemple i tape 5, i can see 5 time the tabe i have put in my function.
What you indended to accomplish (as far I understood) to allow a visitor enter a numer and then submit it after what some "matches" data it shown. The number visitor entered acts as a limiter.
1. Where do you get your POST variables? You have placed a function below the form with an input value of string 'nbmatchs'. I guess you wanted to submit the form and get the 'nbmatches' value and then apply it to the SQL query for filtering. The way you have done it doesn't work. You have action attribute on your form element set to index.php. That's where we are going to submit the form data. So we need to have a way to get the submitted POST variables. We do it like this:
$nbmatchs = $_POST['nbmatchs'];
Never trust data client has given you. As we know that it must a number let's do a check on it:
$nbmatches = is_numeric(trim($_POST['nbmatchs'])) ? $_POST['nbmatchs'] : 1;
Above we checked if the data client has given really is a number. If it is we'll assign this nubmer to variable $nbmatches. If the data client has given is not a number (eg. some string) we assign number 1 to the variable. At this point we may end the script execution a let the visitor know he must enter a number but we just assign 1 to the variable if anything seems suspicious. After that we can submit this variable to the function getLastMatchs which takes the variable and assigns it to the SQL query as a results limiter. Assuming that all the code will be in one file 'index.php' you should have the following code:
<?php
function getLastMatchs($nbmatches) {
try{
$db = new PDO(DBHOST, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die('connexion failed: '.$e->getMessage());
}
try {
$select = $db->prepare('SELECT wid, lid, date, cwid, clid FROM `match` LIMIT '.$nbmatches.';');
$select->execute();
$results = $select->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $ex) {
echo "<span style='color:red'>".$ex->getMessage()."</span></p>";
}
echo '<table>';
foreach($results as $result){
$output = '<tr>';
$output .= '<td>'.$result['wid'].'</td>';
$output .= '<td>'.$result['lid'].'</td>';
$output .= '<td>'.$result['cwid'].'</td>';
$output .= '<td>'.$result['clid'].'</td>';
$output .= '<td>'.$result['date'].'</td>';
$output = '</tr>';
echo $output;
}
echo '</table>';
}
if(isset($_POST['nbmatchs'])){
$nbmatches = is_numeric(trim($_POST['nbmatchs'])) ? $_POST['nbmatchs'] : 1;
getLastMatchs($nbmatches);
}
?>
<form action="index.php" method="post">
<h3>My question......</h3>
<p>
<input type="text" name="nbmatchs" />
<input type="submit" value="ok" />
</p>
</form>
Let me know if this works the way you wanted.
I'm trying to delete an entry from my database using an HTML form. However, when it's submitted, the entry doesn't get deleted from the database and no error code is displayed to say why.
Could somebody possibly let me know if I'm missing something from my code, just in case I've over-looked something?
Thank you.
<form method="post" action="./removeBook.inc.php">
<select name="books">
<option>Please select the Book you wish to delete:</option>
<?php
try {
$dsn = "mysql:host=csdm-mysql;dbname=db1001550_book_management";
$username = "1001550";
$password = "1001550";
// try connecting to the database
$con = new PDO($dsn, $username, $password);
// turn on PDO exception handling
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
// enter catch block in event of error in preceding try block
echo "Connection failed: " . $e->getMessage();
}
try {
$sql=("SELECT * FROM books");
$results = $con->query($sql);
if ($results->rowcount() == 0) {
echo "<p>No books found. </p><br />";
} else {
foreach ($results as $row) {
$book_id=$row['book_id'];
echo "<option value=\"".$book_id."\">".$book_id."</option>";
}
}
} catch (PDOException $e) {
echo "Query failed: " . $e->getMessage();
}
mysql_close();
?>
</select>
<input type="submit" name="submit" value="Remove Book" style="width:auto;">
</form>
And here is the code within the form submitted page:
<?php
$host="csdm-mysql"; // Host name
$username="1001550"; // Mysql username
$password="1001550"; // Mysql password
$db_name="db1001550_book_management"; // Database name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("Cannot select DB");
if (isset($_POST['books'])) {
$books=$_POST['books'];
}
// Remove data from database
$result=mysql_query("DELETE FROM books WHERE book_id=$books");
// if successfully deleted from database, prompt will say book was deleted.
if ($result) {
print "<script type=\"text/javascript\">";
print "alert('Book has been deleted successfully!')";
print "</script>";
} else {
print "<script type=\"text/javascript\">";
print "alert('Book was not deleted')";
print "</script>";
}
// close connection
mysql_close();
?>
<form method="post" action="./removeBook.inc.php">
<select name="books">
<option>Please select the Book you wish to delete:</option>
<option value='B0001'>B0001</option><option value='B0002'>B0002</option><option value='B0003'>B0003</option><option value='B0004'>B0004</option><option value='B0005'>B0005</option><option value='B0006'>B0006</option><option value='B0007'>B0007</option><option value='B0008'>B0008</option><option value='B0009'>B0009</option><option value='B0010'>B0010</option><option value='B0011'>B0011</option><option value='B0012'>B0012</option><option value='B0013'>B0013</option><option value='B0014'>B0014</option><option value='B0015'>B0015</option><option value='B0016'>B0016</option><option value='B0017'>B0017</option><option value='B0018'>B0018</option><option value='B0019'>B0019</option><option value='B0020'>B0020</option>
</select>
<input type="submit" name="submit" value="Remove Book" style="width:auto;">
</form>
Thank you for your help in advance!
Try to print and see whether you are getting the selected Book ID.
Whenever you get a prob in query print and see.
add this line
print "DELETE FROM books WHERE book_id=$books";
before
$result=mysql_query("DELETE FROM books WHERE book_id=$books");
I think you did not receive the Book Id in proper format.
Change the line
echo "<option value=\"".$book_id."\">".$book_id."</option>";
as
echo "<option value='".$book_id."'>".$book_id."</option>";
And also use single quotes to encapsulate a value.
Change
$result=mysql_query("DELETE FROM books WHERE book_id=$books");
to
$result=mysql_query("DELETE FROM books WHERE book_id='".$books."'");
IF your book_id field is varchar or text, you should add quotes between $books
...WHERE book_id='$books'
I'm building a custom CMS and I've written a script that is supposed to edit already existing information in my database.
I've used the code for a different database before and it has worked without any troubles, but I've changed the index names to reference a new database and now it won't work.
The information is displayed on a page with an 'edit' button the links the user to a html form which displays the selected piece of info in a text box.
There's no problem displaying the info in the form, but once the submit button is pressed the code does not execute it, and the info is not updated and no error message is displayed..
so I'm fairly sure there's a problem somewhere in this... (Ignore the comments)
if (isset($_GET['edittimeslot']))
{
$timeslotid = $_GET['timeslotid'];
try
{
$sql = "SELECT timeslotid, Time FROM timeslots WHERE timeslotid = timeslotid" ;
//echo $sql;
$data = $pdo->query($sql);
$timeslots = $data->fetch();
//print_r($acts);
}
catch(PDOException $e)
{
echo "this didnt work" .$e->getMessage() ;
}
$pagetitle = 'Edit your date here';
$timeslotid = $timeslots['timeslotid'];
$time = $timeslots['Time'];
$button = 'Edit timeslot';
include 'timeslot.form.php';
exit();
}
// is all of the requested feilds appropiate
if (isset($_POST['submit']) && $_POST['submit'] == 'Edit timeslot')
{
// get the form data that was posted ready to insert into the stage database
$timeslotid = $_POST['timeslotid'];
$time= htmlspecialchars($_POST['time']);
try
{
// prepare the query to insert data into stages table
$sql = "UPDATE timeslots
SET Time = :Time,
WHERE timeslotid = :timeslotid";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Time', $time);
$stmt->bindParam(':timeslotid', $timeslotid);
$stmt->execute();
}
catch(PDOException $e)
{
//error message goes here if the insert fails
}
}
HTML:
<!doctype html>
<head>
<style type="text/css">
.container {
width: 800px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<h1><?php echo $pagetitle;?></h1>
<form action='.' method='post'>
<!-- stage name -->
<p><label for='time'> What is the timeslots you would like to add? 00:00-00:00 </label></p>
<p><input type='text' name='time' id='time' value='<?php echo $time;?>'> </p>
<p><input type='submit' name='submit' value='<?php echo $button;?>'></p>
</form>
</div>
</body>
Shouldn't WHERE timeslotid = timeslotid be WHERE timeslotid = $timeslotid ?
Also, using a form value directly is a bad idea. Use it at least like $timeslotid = (int)$_GET['timeslotid'];.
Okay one thing that I see right away is this line:
$timeslotid = $_POST['timeslotid'];
Where is that form field in your form? I don't see it anywhere. Also try to assign the execution to a variable and var_dump it so you can see if it returns TRUE or FALSE:
$success = $stmt->execute();
var_dump($success);
Furthermore make sure that you DB column is named Time and not time with all lowercase.
I'm trying to write a function that will allow a user to enter a name into a field, insert the field to a MySQL table and then update a dropdown menu to include those names (while allowing for further additions).
On first load of the page, the dropdown menu shows the correct names that I seeded into the table. When I input a name into the form, it inserts to the table correctly, but then none of the options show in the dropdown list and it removes my entry form. If I refresh the page, everything comes back fine, and the names previously entered show up in the list.
I know I'm missing something obvious in the code to refresh the page, but I'm not even sure what to search for. I thought that by setting my form action to .$_SERVER['PHP_SELF']. it would cause the page to process and reload. I have a hunch this is where my problem is, but I'm not sure what it is.
The dropdown code was something I found off the web, perhaps I have to rewrite it myself, though it's the one part of this mess that's actually working.
Also, the mysql login is hardcoded in db_tools.php b/c I can't get it to work otherwise.
Sorry for the following wall of text, but I'm just trying to provide the most information possible. Thank you for your replies and pointing me in the right direction.
I have 2 files, db_tools.php and dropdown.inc
db_tools.php:
<?php
require_once 'db_login.php';
require_once 'MDB2.php';
require_once("dropdown.inc");
//Define a function to perform the database insert and display the names
function insert_db($name){
//initialize db connection
//$dsn = 'mysql://$db_username:$db_password#$db_hostname/$db_database';
$dsn = "mysql://redacted";
$mdb2 =& MDB2::connect($dsn);
if (PEAR::isError($mdb2)) {
//die($mdb2->getMessage());
die($mdb2->getDebugInfo());
}
//Manipulation query
$sql = " INSERT INTO participants (id, name) VALUES (NULL, \"$name\");";
$affected =& $mdb2->exec($sql);
if (PEAR::isError($affected)){
//die($affected->getMessage());
die($affected->getDebugInfo());
}
//Display query
$query = "SELECT * FROM participants;";
$result =& $mdb2->query($query);
if (PEAR::isError($result)){
die ($result->getMessage());
}
while ($row = $result->fetchRow()){
echo $row[1] . "\n";
}
$mdb2->disconnect();
}
?>
<html>
<head>
<title>Event Bill Splitter</title>
<body>
<?php
$name = $_POST['name'];
if ($name != NULL){
insert_db($name);
}
else {
echo '
<h1>Enter a new participant</h1>
<form name="nameForm" action="'.$_SERVER['PHP_SELF'].'" method="POST">
Name:<input name="name" type="text" />
</form>';
}
?>
<p>Participants:<br />
<?php dropdown(id, name, participants, name, participant_name1); ?></p>
</body>
</head>
</html>
dropdown.inc
require_once ('db_login.php');
$connection = mysql_connect($db_host, $db_username, $db_password);
if (!$connection) {
die ("Could not connect to the database: <br />". mysql_error() );
}
$db_select = mysql_select_db($db_database);
if (!$db_select) {
die ("Could not select the database: <br />". mysql_error() );
}
function dropdown($intNameID, $strNameField, $strTableName, $strOrderField, $strNameOrdinal, $strMethod="asc") {
//
// PHP DYNAMIC DROP-DOWN BOX - HTML SELECT
//
// 2006-05, 2008-09, 2009-04 http://kimbriggs.com/computers/
echo "<select name=\"$strNameOrdinal\">\n";
echo "<option value=\"NULL\">Select Value</option>\n";
$strQuery = "select $intNameID, $strNameField
from $strTableName
order by $strOrderField $strMethod";
$rsrcResult = mysql_query($strQuery);
while($arrayRow = mysql_fetch_assoc($rsrcResult)) {
$strA = $arrayRow["$intNameID"];
$strB = $arrayRow["$strNameField"];
echo "<option value=\"$strA\">$strB</option>\n";
}
echo "</select>";
}
?>
The problem of the form disappearing is simple, just remove the else after the insert section:
<body>
<?php
$name = $_POST['name'];
if ($name != NULL){
insert_db($name);
}
// else { // gone
echo '
<h1>Enter a new participant</h1>
<form name="nameForm" action="'.$_SERVER['PHP_SELF'].'" method="POST">
Name:<input name="name" type="text" />
</form>';
// } // gone
?>
Apart from that I would definitely re-write the dropdown code and add some security, a whitelist for table names, etc.
By the way, you are calling your function in a strange way:
<?php dropdown(id, name, participants, name, participant_name1); ?>
I assume these are variables so it should be $id etc, but where do they come from? If you mean to send values directly, it should be:
<?php dropdown('id', 'name', 'participants', 'name', 'participant_name1'); ?>