I wrote following code in PHP to get the details from the mysql table but I dont know how to display them in HTML form.
<?php
$servername = "localhost";
$username = "root";
$password = "icsk";
$dbname = "yusuf";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT dsl, Fname, Lname, Cid, pack FROM homereg";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['dsl']. " " . $row['Fname']. " " . $row['Lname']. " " . $row['cid']. " " . $row['pack'] ."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
The above code displays the data on the webpage with the help of echo but i want it to be displayed in form.
HTML form has following code:
<form method="POST" name = "frm" action="homerenew.php">
<div align="center">
<table border="1" width="425">
<tr>
<td width="223"><font face="Georgia"><b>Subscription Number</b></font></td>
<td width="186"><input type="text" name="T1" size="20"></td>
</tr>
<tr>
<td width="223"><font face="Georgia"><b>Your Current Pack</b></font></td>
<td width="186"><input type="text" name="T2" size="20"></td>
</tr>
<tr>
<td width="223"><font face="Georgia"><b>Renewal Options</b></font></td>
<td width="186"><select size="1" name="D1">
<option value = "1 Month">1 Month</option>
<option value = "2 Months">6 Months</option>
<option value = "1 Year>1 Year</option>
</select></td>
</tr>
<tr>
<td width="223"><font face="Georgia"><b>Balance Payable</b></font></td>
<td width="186"><input type="text" name="T3" size="20"></td>
</tr>
</table>
</div>
<p align="center"><input type="submit" value="Renew" name="B1">
<input type="reset" value="Reset" name="B2"></p>
</form>
I am new to PHP connectivity that is why little confused. Help will be greatly appreciated. Thank you
First of all you need to have .php extension of the page containing your HTML form.
After fetching data from database you could set it into form element like
<input type="text" name="T1" size="20" value="<?php echo $row['dsl'];?>">
I would recomend using a templating engin similar to PHPTal. You write your html page as an .xhtml file that contains tal: tags that are used by the template engine to insert your php values. Install instructions, example of use.
The benfit of using a template engine is you can remove all html content from your scripts and leave the display logic in the xhtml file. The php code just gathers the data and assigns it to labels your template knows about.
You can get all rows as an array and assign it to a variable name in the template object in php. That variable name is then used in the xhtml file to repeat rows in your table (or any other element).
Php:
<?php
require_once 'PHPTAL.php';
$rows = getMyDBRows();
// create a new template object
$template = new PHPTAL('my_template_file.xhtml');
$template->rows = $rows;
// execute the template
try {
echo $template->execute();
}
catch (Exception $e){
echo $e;
}
Xhtml rows section with example of repeating each row, inserting element contents, setting attributes and using a conditional statement to only display the input field for the row with index 1. Repeat method can be used for options in selects and conditional check for setting selected attribute. Phptal requires strict xhtml structure any errors in your xhtml and the page will return an error identifying where there was a problem.
<tr tal:repeat="row rows">
<td tal:content="row/dsl"><\td>
<td tal:content="row/fname"><\td>
<td><input name="lname" tal:attributes="value row/lname, style php: repeat.row.id EQ 1?'display:inline-block':'display:none" tal:content="row/lname"></input>
......
<\tr>
Related
I have a simple PHP page that posts to a DB. I actually only use it for debugging because the real app receives posts from an Arduino:
SamplePost.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<form action="data_post.php" method="post">
<table style="text-align: left; width: 100%;" border="0"
cellpadding="2" cellspacing="2">
<tbody>
<tr>
<td>Name(Temp):</td>
<td><input name="username" type="text"></td>
<td></td>
</tr>
<tr>
<td>Age(co2):</td>
<td><input name="age" type="text"></td>
<td></td>
</tr>
<tr>
<td>UVIndex:</td>
<td><input name="uvindex" type="text"></td>
<td></td>
</tr>
<tr>
<td>MQ2:</td>
<td><input name="mq2" type="text"></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit"></td>
</tr>
</tbody>
</table>
<br>
</form>
</body>
</html>
I recently used it to debug because I was having issues with the Arduino app not posting since 20 days ago. Oddly enough I discovered the DB username I had in the PHP was incomplete. Odd because it has been posting for years and I honestly don't remember having changed the DB username in the PHP, but whatever. So this is what it posts to:
data_post.php
<?php
$user = 'myusr';
$password = 'mypwd';
$server = 'localhost';
$database = 'mydb';
$pdo = new PDO("mysql:host=$server;dbname=$database", $user, $password);
$username=$_POST['name'];
$age=$_POST['age'];
$uvindex=$_POST['uvindex'];
$mq2=$_POST['mq2'];
$sql = "INSERT INTO example (name,age,uvindex,mq2,beer) VALUES (:username, :age, :uvindex, :mq2, 'NO')";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":username", $username);
$stmt->bindParam(":age", $age);
$stmt->bindParam(":uvindex", $uvindex);
$stmt->bindParam(":mq2", $mq2);
$result = $stmt->execute(array(':username'=>$username, ':age'=>$age, ':uvindex'=>$uvindex, ':mq2'=>$mq2));
if($result) {
echo "Your text has been posted";
}// end if
else {
echo '0 results';
}// end else
file_put_contents("arduinopost.txt",$username);
?>
So after I corrected the DB username in code, I used the SamplePost.html and it worked because I got my success message from the PHP if-else and I refreshed my DB read file and the post appeared:
query.php
<html>
<body>
<?php
$servername = "localhost";
$username = "myusr";
$password = "mypwd";
$dbname = "mydb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM example where id > (SELECT MAX(id) - 20 FROM example)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id=" . $row["id"]. ". Temp=" . $row["name"]. ". CO2PPM=" . $row["age"]. ". UVIndex=" . $row["uvindex"]. ". MQ2R=" . $row["mq2"]. ". Timestamp=" . $row["timestamp"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
But the weird thing is that when I look for that entry in the DB via phpMyAdmin, it's simply not there. But I can see the data printed from the query.php on my screen and I've refreshed it multiple times, it's still there...
How can data be in a PHP page that reads from the DB, but not in the DB?
I added the screenshot of phpmyadmin, where are you can see, they records are ordered by descending timestamp, so i should be seeing the latest records, right?
As a side note, the arduino app started posting to the data_post.php page again successfully and I can now see the latest record in my query.php page but I cannot see the records in the phpmyadmin. Im thinking this is gonna turn up to be something silly but i was worried whatever the cause is, that it might be related to the arduino not being able to post. But at least now posting is working again.
I am trying to figure out how to display all the rows of a database table in one page, all the values to be editable, and for there to be a single submit button at the end of it. I got half the equation figured out, but for some reason it is still not working.
What I currently have is a table displaying all the contents of a MYSQL table and all fields are editable. There is a submit button for all each field (which is not what I want, but willing to settle if I have to), but upon editing something from the database fields, it brings me to a page that gives me a syntax error:
"Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE idnum = '0000'' at line 1"
The following is from FORM.PHP
<?php
include('config.php');
$result = mysqli_query($connect,"SELECT * FROM table123");
?>
<html>
<table>
<?php while ($res = mysqli_fetch_array($result)) { ?>
<tr>
<form action="test.php" method="post">
<td><input type="text" name="ret" value="<?php echo $res['ret']; ?>"></td>
<td><input type="text" name="code" value="<?php echo $res['code']; ?>"></td>
<td><input type="text" name="status" value="<?php echo $res['status']; ?>"></td>
<td><input type="hidden" name="idnum" value="<?php echo $res['idnum']; ?>"></td>
<td><input type="submit" name="update" value="Submit"></td>
</form>
</tr>
<?php } ?>
</table>
</html>
The following is from TEST.PHP
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$connect = mysqli_connect($servername, $username, $password, $dbname);
if (!$connect) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['update'])) {
$sql = "UPDATE ssoretailerlist SET ret = '$_POST[ret]', code = '$_POST[code]', status = '$_POST[status]', WHERE idnum = '$_POST[idnum]'";
} else {
echo "Nothing was posted";
}
if (mysqli_query($connect, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($connect);
}
mysqli_close($connect);
Syntax error is because you have an extra comma. Remove the comma before WHERE and you should be fine.
$sql = "UPDATE ssoretailerlist
SET ret = '$_POST[ret]', code = '$_POST[code]', status = '$_POST[status]'
WHERE idnum = '$_POST[idnum]'";
There is a submit button for all each field. Instead of creating a new form and submit for every row inside the loop, one them each once manually outside the loop.
<?php
include('config.php');
$result = mysqli_query($connect, "SELECT * FROM table123");
?>
<html>
<table>
<form action="test.php" method="post">
<?php while ($res = mysqli_fetch_array($result)) { ?>
<tr>
<td><input type="text" name="ret" value="<?php echo $res['ret']; ?>"/></td>
<td><input type="text" name="code" value="<?php echo $res['code']; ?>"/></td>
<td><input type="text" name="status" value="<?php echo $res['status']; ?>"/></td>
<td><input type="hidden" name="idnum" value="<?php echo $res['idnum']; ?>"/></td>
</tr>
<?php } ?>
</table>
<input type="submit" name="update" value="Submit"/>
</form>
</html>
You may want to also handle the output you're inserting into the form. If the data has double quotes in it, it may break your HTML. Check out htmlspecialchars(). Based on your column titles I don't think it would, but always good to keep in mind.
However, every single row has the exact same input names. This is a problem. How will it know which ret, code, status, or idnum to choose and associate together? First you want to turn the names into arrays. Then you want to loop through the idnum array and do multiple UPDATE queries accessing the same key location in the other arrays. Post a new question if you get stuck working on that.
And finally your config.php file is pretty necessary. You may want to read this thread about require_once() vs include(). It's good to throw an error and handle it if the include fails instead of continuing to process the rest of the script.
This is my table html code. I tried sending the data using the normal insert but it only sends the last row data. I don't know how to send the full data . Can someone please help me with this.
<form action="admin_schedule_employee.php" id="schedule_employee" method="post" >
<input type="date" class="input-sm" name="scheduledate" style="margin:10px;">
<table class="table-responsive table table striped table-bordered">
<thead>
<tr>
<th style="width:20%">Employee First Name</th>
<th style="width:20%">Employee ID</th>
<th style="width:20%">Start Time</th>
<th style="width:20%">End Time</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)): ?>
<tr>
<td><input disabled name="employeename" type="text" value="<?php echo $row['fname']; ?>"></input></td>
<td><input disabled name="employeeid" type="number" value="<?php echo $row['employee_id']; ?>"></input></td>
<td><input name="starttime" type="time"></td>
<td><input name="endtime" type="time"></td>
</tr>
<?php endwhile; ?>
</thead>
<tbody>
</tbody>
</table>
<input type="submit" name="Schedule" value="Schedule">
</form>[This is how my table look like i want to send the whole data to sql database using php][1]
To start with, you will need to create multiple pages:
form.php
process.php
done.php
Creating your user form is simple, place the table in form tags like you have done above, here is an example. Save this page as form.php
<form id="new record" action="process.php" method="POST">
<table width="500px">
<tr>
<td width="50%">
<input type="text" name="fname" id="fname">
</td>
<td width="50%">
<input type="text" name="lname" id="lname">
</td>
</tr>
<tr>
<td width="50%">
</td>
<td width="50%">
<input type="submit" value="Add Record">
</td>
</tr>
</table>
</form>
Next, you will need to create a page which can process this data, and add it to your mysql database. For the following example, I have omitted my database details and substituted them, but you should add your own.
For this example, imagine my database has a table with only an fname and an lname column.
<meta http-equiv="refresh" content="0; url=/done.php" />
<?php
$servername = "your_server_name";
$username = "mysql_username";
$password = 'mysql_password';
$dbname = "database_name";
$fname = $_GET['fname'];
$lname = $_GET['lname'];
try {
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO online (fname, lname)
VALUES ('$fname', '$lname')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record inserted";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Hopefully, that will work to insert the record. Now we need a table on the done.php page which can display all the records in the database. Use the following code:
<html lang="en">
<head>
<meta http-equiv="refresh" content="5; url=/done.php" />
<meta charset="utf-8" />
<title></title>
</head>
<body>
<?php
$servername = "your_server_name";
$username = "mysql_username";
$password = 'mysql_password';
$dbname = "database_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * from table_name";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["fname"]. ": ";
echo $row["lname"]. "<br /><br />";
}
} else {
echo "No messages";
}
mysqli_close($conn);
?>
</body>
</html>
Hopefully this will work for you.
I have been battling with this code for some time and could do with some advice. I have created a mysql database of computer games and a simple search box and button within a form. If I type in any key word regarding the name of the game or its description, php should echo the results in a drop down (since there might be more than one 'hit'). At present, I'm just showing the results at the bottom of the page. My query happily runs the else statement and shows me all the games on offer, but I get no results when I type in the search criteria and no error messages. print_r($q) also draws a blank. What's going wrong?
NB. I'm not too worried about code injection at this point - 1 baby step at a time! Many thanks
<!DOCTYPE HTML>
<HTML>
<head></head>
<?php
//Connect to the Database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "Secret";
$dbname = "gaming";
//Create connection
$conn = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
// Show error if connection fails
if (!$conn){
die("Connection failed: " .
mysqli_connect_error());
}
if(isset($_REQUEST['submit'])){
$search=$_POST['search'];
$sql="SELECT* FROM gamestbl WHERE game_name LIKE '%.$search.%' OR game_description LIKE '%.$search.%'";
$q=mysqli_query($conn,$sql);
}
else{
$sql="SELECT* FROM gamestbl";
$q=mysqli_query($conn,$sql);
}
?>
<body>
<form method="post">
<table width="200" border="1">
<tr>
<td>Search</td>
<td><input type="text" name="search" value="" /></td>
<td><input type="submit" name="submit" value=" Find " /></td>
</tr>
</table>
</form>
<table>
<tr>
<td>Game ID</td>
<td>Game Name</td>
<td>Game Description</td>
<td>Game Genre</td>
<td>Game Price</td>
</tr>
<?php
print_r($q);
while($res=mysqli_fetch_array($q)){
?>
<tr>
<td><?php echo $res['game_id'];?></td>
<td><?php echo $res['game_genre'];?></td>
<td><?php echo $res['game_name'];?></td>
<td><?php echo $res['game_description'];?></td>
<td><?php echo $res['game_price'];?></td>
</tr>
<?php }?>
</table>
</body>
</html>
<?php
// get rid of data in cache and close
mysqli_close($conn);
?>
Change
$sql="SELECT* FROM gamestbl WHERE game_name LIKE '%.$search.%' OR game_description LIKE '%.$search.%'";
For
$search = mysql_real_escape_string($search); // Prevent from injection
$sql = sprintf("SELECT * FROM gamestbl WHERE concat(game_name, game_description) LIKE '%s'", '%' . $search . '%');
sprintf is the better way to add variable in a string and concat will make your sql shorter by avoiding "OR".
Instead of '%.$search.%' you have to use '%$search%' (notice skipped dots). Or even better (in my opinion) '%".$search."%'.
Currently you are passing dots in your query so instead of searching for example you are asking database for rows with .example. in name or description.
I have to post a value via "form post" and insert it into table, here is my code in both files:
<html>
<body>
<table>
<form enctype="multipart/form-data" action="<?php $_SERVER["DOCUMENT_ROOT"] ?> /contents/ad_posting_process_4.php" method="post">
<?php $cat_no = "101010"; ?>
<input type=hidden id="category" value=" <?php echo $cat_no; ?> ">
<tr> <td>Sub Category: </td><td> <input type=text id="sub_category" > </td>
<tr><td></td> <td><input type="submit" name="action" value="Post"></td></tr></tr>
</form>
</body></html>
here is ad_posting_4.php
<?php session_start();
include($_SERVER["DOCUMENT_ROOT"]."/includes/conn.php");
$category = mysql_real_escape_string($_POST['category']);
$sub_category = mysql_real_escape_string($_POST['sub_category']);
echo "category=". $category;
echo "sub_category=". $sub_category; ?>
No value sent through post.
where am I wrong?
Regards:
You need to use the name attribute:
<input type="text" name="category" />
<input type="text" name="sub_category" />
the input type needs to be enclosed in quotes ' and also have a name attribute, and not id.
<input type='hidden' name="category" value=" <?php echo $cat_no; ?> " />
<tr> <td>Sub Category: </td>
<td><input type='text' name="sub_category" > </td>
I recently did something very similar with my own website and received help from this community. On the HTML side I created a standard form and gave each input a "name." For example let's say you are trying to capture city and state:
<html>
<body>
<form>
<tr>
<td>State: </td><td> <input type="text" style="border:1px solid #000000" name="state" /></td>
<td>City</td><td><input type="text" style="border:1px solid #000000" name="city" /></td>
</tr>
</form>
</body>
</html>
Then set up a mySQL database with a column named "state" and one named "city". Next, use PHP to insert the data from the form into your database. I am new to PHP, but from what I understand using PDOs is more secure than using the old mysql commands.
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "name";
$dbuser = "user";
$dbpass = "pass";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "SELECT column_name FROM information_schema.columns WHERE table_name = '[Insert Name of your table here]'";
$q = $conn->prepare($sql);
$q->execute();
$columns = $q->fetchAll(PDO::FETCH_COLUMN, 0);
$cols = array();
foreach ($_POST as $key=>$value)
{
// if a field is passed in that doesn't exist in the table, remove it. The name of the input that is removed will be echoed so you can debug. Remove echo if you go to production.
if (!in_array($key, $columns)) {
unset($_POST[$key]);
echo $key;
}
}
$cols = array_keys($_POST);
$sql = "INSERT INTO Facilities(". implode(", ", $cols) .") VALUES (:". implode(", :", $cols) .")";
$q = $conn->prepare($sql);
array_walk($_POST, "addColons");
$q->execute($_POST);
function addColons($value, &$key)
{
$key = ":{$key}";
}
This has been working out very well for me. Note that it can only match HTML form inputs with columns of the exact same name. In my case I wanted to create over 100 inputs so this was easier. If you are dealing with 5-10 it might be easier to just insert the specific variables manually.