Updating SQLite database with PHP - php

I have been working on this problem for the past 3 or 4 hours. I have an SQLite database which interacts with PHP. So far, I have been able to perform 3 of the 4 CRUD operations. The only one which won't work is the the U part (update). I am able to print data into my form, but clicking on the submit button will just make the app hang for some time until I get a custom error message from my app. Also, the record doesn't get updated.
Your help is very much appreciated!
Here is my current code for the edit/update form and page from my app:
<?php
// $db->close();
// echo $_GET['id'];
?>
<!-- get database content -->
<?php
// define PDO - tell about the database file
$db = new PDO("sqlite:database.db");
try {
$sql = "SELECT * FROM students_tb WHERE id=:myId";
// prepare statement
$statement = $db->prepare($sql);
// get value from querystring and bind
$id = filter_input(INPUT_GET, "id");
$statement->bindValue(":myId", $id, PDO::PARAM_INT);
// execute the query
$statement->execute();
// create array of records
$r = $statement->fetch();
$db = null;
// check contents of array
if (!$r) {
echo "No record found";
} else {
echo "record found";
}
}
catch (PDOException $e) {
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
?>
<!-- print database content -->
<?php
// has the form been submitted?
// if not, show the HTML form
if (!isset($_POST['submit'])) {
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF'] . "?id=" . $r['id']); ?>" method="post">
<label for="sname">Student's Name</label>
<input type="text" name="sname" required value="<?php echo htmlspecialchars($r['sname']); ?>">
<label for="score">Score</label>
<input type="number" name="score" required value="<?php echo htmlspecialchars($r['score']); ?>">
<button type="submit" name="submit">Submit</button>
</form>
<!-- update database content -->
<?php
} else {
try {
$id = $_POST['id'];
$db = new PDO("sqlite:database.db");
// print out error messages is something goes wrong
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE students_tb SET sname = :sname, score = :score WHERE id = $id";
// UPDATE table_name
// SET column1 = value1, column2 = value2...., columnN = valueN
// WHERE [condition];
$stat = $db->prepare($sql);
// named params
$sname = filter_input(INPUT_POST, "sname");
$stat->bindValue(":sname", $sname, PDO::PARAM_STR);
$score = filter_input(INPUT_POST, "score");
$stat->bindValue(":score", $score, PDO::PARAM_INT);
$success = $stat->execute();
// does the value exist?
if ($success) {
echo "The student has been updated in the database.";
echo "<p><a href='/'>Go back to the main page.</a></p>";
} else {
echo "The student has NOT been updated in the database.";
echo "<p><a href='/'>Go back to the main page.</a></p>";
}
$db = null;
} catch (PDOException $e) {
// for development
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
}
?>

After browsing your source files, it is found that the record will be locked because you are doing the select and then doing the update immediately (which is of course not necessary, in all cases).
Hence, Please use the following code to fix the problem (I have included a hidden field known as actionx to prevent the PHP to do both select and update at the same time) :
So for the edit.php, it should be:
<?php
// $db->close();
// echo $_GET['id'];
?>
<?php if ($_REQUEST["actionx"] =="") { ?>
<!-- get database content -->
<?php
// define PDO - tell about the database file
$db = new PDO("sqlite:database.db");
try {
$sql = "SELECT * FROM students_tb WHERE id=:myId";
// prepare statement
$statement = $db->prepare($sql);
// get value from querystring and bind
$id = filter_input(INPUT_POST, "id");
$statement->bindValue(":myId", $id, PDO::PARAM_INT);
// execute the query
$statement->execute();
// create array of records
$r = $statement->fetch();
$db = null;
// check contents of array
if (!$r) {
echo "No record found";
} else {
echo "record found";
}
}
catch (PDOException $e) {
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
?>
<form action="edit.php" method="post">
<label for="sname">Student's Name</label>
<input type="text" name="sname" required value="<?php echo htmlspecialchars($r['sname']); ?>">
<label for="score">Score</label>
<input type="number" name="score" required value="<?php echo htmlspecialchars($r['score']); ?>">
<input type=hidden name=id value="<?php echo $_REQUEST["id"]; ?>">
<input type=hidden name=actionx value="update">
<button type="submit" name="submit">Submit</button>
</form>
<?php } ?>
<?php if ($_REQUEST["actionx"] !="") { ?>
<?php
try {
$id = $_POST['id'];
$db = new PDO("sqlite:database.db");
// print out error messages is something goes wrong
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE students_tb SET sname = :sname, score = :score WHERE id = :id";
$stat = $db->prepare($sql);
// named params
$sname = filter_input(INPUT_POST, "sname");
$stat->bindValue(":sname", $sname, PDO::PARAM_STR);
$score = filter_input(INPUT_POST, "score");
$stat->bindValue(":score", $score, PDO::PARAM_INT);
$id = filter_input(INPUT_POST, "id");
$stat->bindValue(":id", $id, PDO::PARAM_INT);
$success = $stat->execute();
// does the value exist?
if ($success) {
echo "The student has been updated in the database.";
echo "<p><a href='index.php'>Go back to the main page.</a></p>";
} else {
echo "The student has NOT been updated in the database.";
echo "<p><a href='index.php'>Go back to the main page.</a></p>";
}
$db = null;
} catch (PDOException $e) {
// for development
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
}
?>
On the other hand, for the one.php (displaying a single record), please use this:
<?php
echo $_GET['id'];
?>
<?php
// define PDO - tell about the database file
$db = new PDO("sqlite:database.db");
try {
$sql = "SELECT * FROM students_tb WHERE id=:myId";
// prepare statement
$statement = $db->prepare($sql);
// get value from querystring and bind
$id = filter_input(INPUT_GET, "id");
$statement->bindValue(":myId", $id, PDO::PARAM_INT);
// execute the query
$statement->execute();
// create array of records
$r = $statement->fetch();
$db = null;
// check contents of array
if (!$r) {
echo "No record found";
} else {
echo "record found";
}
}
catch (PDOException $e) {
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
?>
<h1><?php echo htmlspecialchars($r['id']); ?></h1>
<p>Description: <?php echo htmlspecialchars($r['sname']); ?></p>
<p>Score: <?php echo htmlspecialchars($r['score']); ?></p>
<form action="<?php echo 'delete.php?id=' . htmlspecialchars($r['id']) ?>" method="POST">
<button type="submit" name="delete">Delete this record</button>
</form>
<form action="edit.php" method="POST">
<button type="submit" name="delete">Edit this record</button>
<input type=hidden name=id value="<?php echo $r['id']; ?>">
</form>

Related

SQL query using string concatenation

I am new to php and I have a table "abc" where I have columns: id, name and age.
I want to do the following:
Only if a name is entered in the input field, corresponding data (id and age) should be shown using string concatenation to build SQL query.
This is for search functionality
What should be the SQL query for this question?
// Create connection
$conn = new mysqli($SERVER_NAME, $USER_NAME, $PASSWORD, $DATABASE_NAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = " SELECT name, CONCAT(id,'.',age) FROM personene WHERE name = 'VALUE_FROM INPUT_NAME'";
$result = $conn->query($sql);
$error = mysqli_error($conn);
// Store results
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php if(!empty($error))
echo "<p style='color:red'>$error</p>";
?>
<p>Please enter the name:</p>
<form action="<?=$_SERVER['PHP_SELF']?>" method="GET">
<input type="input" name="name" value="" />
<br/>
<input type="submit" name="sendbtn" value="Send" />
</form>
<?php
if(!empty($data)) {
echo "<h1>Persons:</h1><table border='1'><tr><th>Id</th><th>Firstname</th><th>Age</th></tr>";
foreach($data as $row) {
echo "<tr><td>".$row["id"]."</td>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["age"]."</td></tr>";
}
echo "</table>";
}
else
echo "No data available";
echo '(Query: '.$sql.')';
?>
</body>
</html>
It is not clear why you want to concatenate fields in the SQL query when clearly in the html these fields are displayed in their own columns. The code you have is wide open to SQL Injection so you need to consider using a prepared statement to handle the user supplied input safely.
<?php
$data=[];
error_reporting( E_ALL );
if( $_SERVER['REQUEST_METHOD']=='GET' && !empty( $_GET['name'] ) ){
$SERVER_NAME='';
$USER_NAME='';
$PASSWORD='';
$DATABASE_NAME='';
mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$conn=new mysqli( $SERVER_NAME, $USER_NAME, $PASSWORD, $DATABASE_NAME );
try{
$sql = 'select `name`, `id`, `age` from `personene` where `name` = ?';
$stmt=$conn->prepare( $sql );
$stmt->bind_param('s', $_GET['name'] );
$stmt->execute();
$stmt->bind_result( $name, $id, $age);
while( $stmt->fetch() )$data[]=[
'name' => $name,
'id' => $id,
'age' => $age
];
$stmt->free_result();
$stmt->close();
$conn->close();
}catch( mysqli_sql_exception $e ){
exit( $e->getMessage() );
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Fetch user details</title>
</head>
<body>
<p>Please enter the name:</p>
<form method='GET'>
<input type='input' name='name' />
<br/>
<input type='submit' name='sendbtn' value='Send' />
</form>
<?php
if( !empty( $data ) ) {
echo "
<h1>Persons:</h1>
<table border='1'>
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Age</th>
</tr>";
foreach( $data as $row ) {
echo "
<tr>
<td>{$row["id"]}</td>
<td>{$row["name"]}</td>
<td>{$row["age"]}</td>
</tr>";
}
echo "</table>";
} else {
echo "No data available";
}
?>
</body>
</html>
For the SQL query to find records related with name, you have to use this query,
select concat('id', '-', 'age') as user_data from abc where name = $REQUEST['search_name'];
OR you can use LIKE(check here) condition to get the records from the table.
select concat('id', '-', 'age') as user_data from abc where name like
$REQUEST['search_name'];
Here is an update for your code,
<?php
// Create connection
$conn = new mysqli($SERVER_NAME, $USER_NAME, $PASSWORD, $DATABASE_NAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// echo "Connected successfully";
$data = [];
$sql = "Please submit the form.";
if(isset($_GET['sendbtn']) ) {
$sql = " SELECT id, name, age FROM personene WHERE name = '". $_GET['name'] ."'";
$result = $conn->query($sql);
$error = mysqli_error($conn);
// Store results
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
if(!empty($error))
echo "<p style='color:red'>$error</p>";
?>
<p>Please enter the name:</p>
<form action="<?=$_SERVER['PHP_SELF']?>" method="GET">
<input type="input" name="name" value="" />
<br/>
<input type="submit" name="sendbtn" value="Send" />
</form>
<?php
if(isset($data) && !empty($data)) {
echo "<h1>Persons:</h1><table border='1'><tr><th>Id</th><th>Firstname</th><th>Age</th></tr>";
foreach($data as $row) {
echo "<tr><td>".$row["id"]."</td>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["age"]."</td></tr>";
}
echo "</table>";
} else {
echo "No data available";
}
echo '(Query: '.$sql.')';
?>
</body>
</html>

Failed to run query: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

I have a problem here. I keep getting this error which is number of bound variables does not match number of tokens. I double check my code and doesn't seems to have an error on it. Anyway, I am new to these PDO thing.
This is the code how I call the data from database to echo in the form
if(isset($_GET['idstudent'], $_GET['idbook'])){
$_SESSION['link']=$_GET['idstudent'];
$_SESSION['link2']=$_GET['idbook'];
$sessionidstudent = $_SESSION['link'];
$sessionidbook = $_SESSION['link2']; }
$query = "
SELECT
*
FROM viewlibrary
WHERE
id = :sessionidstudent AND
serialno = :sessionidbook
";
$query_params = array(
':sessionidstudent' => $_SESSION['link'],
':sessionidbook' => $_SESSION['link2']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$r=$stmt->fetch(PDO::FETCH_ASSOC); ?>
This is my HTML code
<form action="editpage.php" method="post" class="login, reminder">
<p>Student Matric Number:
<input type="text" class="login-input" name="addmatricno" id="addmatricno" value="<?php echo $r['matricno'] ?>" placeholder="Enter student matric number">
Student Name:
<input type="text" class="login-input" name="addname" id="addname" value="<?php echo $r['studentname'] ?>" placeholder="Enter student name">
Programme:
<input type="text" class="login-input" name="addprogramme" id="addprogramme" value="<?php echo $r['programme'] ?>" placeholder="Enter student programme">
Education Level:
<?php
if($r['education_level'] == "PHD"){
echo '<select name="selectedulevel" id="selectedulevel" class="login-input">';
echo '<option disabled>Please select education level</option>';
echo '<option value="PHD" selected>PHD</option>';
echo '<option value="MASTER">MASTER</option>';
echo '<option value="PHD">DEGREE</option></p></select>';
}
else if($r['education_level'] == "MASTER"){
echo '<select name="selectedulevel" id="selectedulevel" class="login-input">';
echo '<option disabled>Please select education level</option>';
echo '<option value="PHD">PHD</option>';
echo '<option value="MASTER" selected>MASTER</option>';
echo '<option value="PHD">DEGREE</option></p></select>';
}
else{
echo '<select name="selectedulevel" id="selectedulevel" class="login-input">';
echo '<option disabled>Please select education level</option>';
echo '<option value="PHD">PHD</option>';
echo '<option value="MASTER">MASTER</option>';
echo '<option value="PHD" selected>DEGREE</option></p></select>';
}
?>
<input type="submit" name="updatestudent" id="updatestudent" value="Update Student" class="login-submit" style = "width: 20%; text-align: center">
Last but not least, my query code.
$query = "
UPDATE student
SET
matricno = :addmatricno,
studentname = :addname,
programme = :addprogramme,
education_level = :selectedulevel
WHERE
id = :sessionidstudent
";
$query_params = array(
':addmatricno' => $_POST['addmatricno'],
':addname' => $_POST['addname'],
':addprogramme' => $_POST['addprogramme'],
':selectedulevel' => $_POST['selectedulevel']
);
try
{
// Execute the query to create the user
$stmt = $db->prepare($query);
//$stmt->bindValue(':sessionidstudent',$sessionidstudent);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// This redirects the user back to the login page after they register
echo '<script language="javascript">';
echo 'alert("Info updated successful.")';
echo '</script>';
header("Refresh: 0; updatebooks.php");
die();
note: $db refer to $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); where I put on other file and i can sure my connection to database has no problem at all.
I have check my code many times but still getting the same error.
In the query params variable you forgot to add the :sessionidstudent in the update query, add that and the error will be gone

Update in php using sql and phpmyadmin

I am trying to create an update form to update to the database table. I have created a function that uses sql to create the update, and a function that updates the table. I have also created the code that calls these functions. The error is that nothing is posting or changing when I press submit. It isn't running or editing or updating any of the data.
Please help me get this code working!
Thanks
function updateSingleValue($ID, $Name)
{
$sql = "UPDATE faculty SET Name=$Name WHERE ID=$ID";
$mysqlConnection = getConnection();
$statement = $mysqlConnection->prepare($sql);
$bReturn = false;
try
{
$statement->execute();
$bReturn = true;
}
catch (PDOException $e)
{
echo $e->getMessage();
}
return $bReturn;
}
function getUpdateResults($tablename)
{
$mysqlConnection = getConnection();
$sql = "SELECT * FROM ".$tablename;
$ResultSet = $mysqlConnection->query($sql);
return $ResultSet;
}
<?php
include_once 'db.php';
if(isset($_POST['update']))
{
$success = updateSingleValue($_POST['ID'], $_POST['Name'], $_POST['update']);
echo $success;
if(!$success)
{
echo 'Sorry, the update failed.';
}
}
$Results = getUpdateResults('faculty');
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<label id="lblUpdate" for="update">Update</label>
<input type="text" name="update" />
<input type="text" name="ID" />
<input type="text" name="Name" />
<input type="submit" name="submit" value="Submit"/>
</form>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<?php
if(isset($Results))
{
foreach($Results as $row)
{
echo '<tr><td>';
echo $row['ID'];
echo '</td><td>';
echo $row['Name'];
echo '</td></tr>';
}
}
?>
</table>
Iv'e noticed something with this:
function getUpdateResults($tablename)
{
$mysqlConnection = getConnection();
$sql = "SELECT * FROM ".$tablename;
$ResultSet = $mysqlConnection->query($sql);
return $ResultSet;
}
try doing concatinating your tablename like this
$t = $tablename;
$sql = "SELECT * FROM $t";
Please close the open connection at the end....
mysql_close($mysqlConnection);

show single entry on a new page with sending id of row

i am very novice to php and mysqli and found a great tutorial but am needing some help.
i am wanting a row to be linkable and send it to another page named single.php?id=ROWID so it will show the single entry
this is what i got so far.
<html>
<head>
<title>MySQLi Tutorial</title>
</head>
<body>
<?php
//include database connection
include 'db_connect.php';
$action = isset($_GET['action']) ? $_GET['action'] : "";
if($action=='delete'){ //if the user clicked ok, run our delete query
$query = "DELETE FROM users WHERE id = ".$mysqli->real_escape_string($_GET['id'])."";
if( $mysqli->query($query) ){
echo "User was deleted.";
}else{
echo "Database Error: Unable to delete record.";
}
}
$query = "select * from users";
$result = $mysqli->query( $query );
$num_results = $result->num_rows;
echo "<div><a href='add.php'>Create New Record</a></div>";
if( $num_results ){
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th><a href=\"single.php?id={$id}\">Firstname</></th>";
echo "<th>Lastname</th>";
echo "<th>Username</th>";
echo "<th>Action</th>";
echo "</tr>";
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$firstname}</td>";
echo "<td>{$lastname}</td>";
echo "<td>{$username}</td>";
echo "<td>";
echo "<a href='edit.php?id={$id}'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{
//if table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
<script type='text/javascript'>
function delete_user( id ){
//this script helps us to
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'index.php?action=delete&id=' + id;
}
}
</script>
</body>
</html>
i am right in thinking i would be sending the rows id in the url ?
echo "<th><a href=\"single.php?id={$id}\">Firstname</></th>";
but i am having issues with single.php what code would i have to put to show the single entry?
i have been on this a while and got no were near so i deleted the code and swallowed my pride to seek some help :/
thanks in advance
Thank you for the interesting question.
First, let me inform you that, although you are using a moder-looking database access library, the way you are using it is as ancient as a mammoth fossil.
Several things to consider
Never use mysqli as is, but only in the form of some higher level abstraction library.
Never use real_escape_string in the application code but use prepared statements only.
Never mix your database code with HTML output. Get your data first, then start for output.
Never use GET method to modify the data.
Here goes the example based on the above principles. It does ALL basic CRUD operations:
<?
include 'safemysql.class.php'; // a library
$db = new SafeMysql();
$table = "test";
if($_SERVER['REQUEST_METHOD']=='POST') {
if (isset($_POST['delete'])) {
$db->query("DELETE FROM ?n WHERE id=?i",$table,$_POST['delete']);
} elseif ($_POST['id']) {
$db->query("UPDATE ?n SET name=?s WHERE id=?i",$table,$_POST['name'],$_POST['id']);
} else {
$db->query("INSERT INTO ?n SET name=?s",$table,$_POST['name']);
}
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
exit;
}
if (!isset($_GET['id'])) {
$LIST = $db->getAll("SELECT * FROM ?n",$table);
include 'list.php';
} else {
if ($_GET['id']) {
$row = $db->getRow("SELECT * FROM ?n WHERE id=?i", $table, $_GET['id']);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
}
It is using templates to display the data:
list.php
Add item
<? foreach ($LIST as $row): ?>
<li><?=$row['name']?>
<? endforeach ?>
and form.php
<form method="POST">
<input type="text" name="name" value="<?=$row['name']?>"><br>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="submit"><br>
Return to the list
</form>
<? if ($row['id']):?>
<div align=right>
<form method="POST">
<input type="hidden" name="delete" value="<?=$row['id']?>">
<input type="submit" value="Удалить"><br>
</form>
</div>
<?endif?>
here goes the part for display.
if ($_GET['id']) {
$row = $db->getRow("SELECT * FROM ?n WHERE id=?i", $table, $_GET['id']);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
if you don't want to show the form - create another template called single.php with whatever markup you wish
Single.php
I Use PDO if u want you can make it with MySQLi too.
<?php
include("db_connect.php"); // database configuration file
if(isset($_GET['id'])
{
$id = (int) $_GET['id'];
$sql = "SELECT * FROM `users` WHERE id=?";
$query = $conn->prepare($sql); // $conn is PDO object yours can be different
$query->bindValue(1,$id);
$query->execute();
if($query){
$row = $query->fetch(); //
}else{
echo "Error with Database";
}
}
else // Error for the Id selection
{
echo("ID is not selected");
}
?>
No while loop because you want just 1 record. $row variable is just for test because i don't know your fields in your DB
<table border="1">
<tr>
<td>ID</td>
<td>Firstname</td>
<td>Lastname</td>
</tr>
<tr>
<td><?php echo $row['id]; ?></td>
<td><?php echo $row['firstname']; ?></td>
<td><?php echo $row['lastname']; ?></td>
</tr>
</table>
in your single.php
$id=$_GET['id'];
$query="select * from users where id='".$id."'";

php form arrays and sqlite - updated

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 "lookuptable" 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 user which updates the new value in the "roster" table 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.
How do I post "firstname" and "lastname" from the user to the roster table instead of of the number on the array table?
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>
Person : <select name="name">
<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 lookuptable where ID = '340' ");
$rowarray = $stmt2->fetchall(PDO::FETCH_ASSOC);
$cntr = 0;
foreach($rowarray as $row)
{
echo "<option value = $cntr >$row[FirstName] $row[LastName]</option>";
$cntr++;
}
?>
</select><br>
<p>
<input type="submit" name="update" value="update">
</p>
</form>
</body>
</html>
PHP Code: Post.php
<?php
$name = sqlite_escape_string($_POST['name']);
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
if (!empty($person)) {
try
{
$stmt = $db->prepare("UPDATE roster SET rotationplace = :name WHERE ID = '340'");
$stmt->bindParam(':name', $name,PDO::PARAM_STR);
$stmt->execute();
}
catch(Exception $e)
{
echo $e->getMessage();
}
echo "submitted successfully";
}
?>
Try:
echo "<option value = $INSERT_NAME_HERE_NOT_COUNTER >$row[FirstName] $row[LastName]</option>";

Categories