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.
Related
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 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>
Ive written PHP code to add a record to my database. When I click on the save button, then it should say "saved successfully", But all that happens is that the page refreshes with no added records in the database and no "saved successfully" message pops up.
My database connection works properly. So I cant figure out what the problem could be.
here is the PHP code:
<?php
error_reporting(0);
$con = mysqli_connect("localhost", "root", "password") or die("error");
if($con) {
mysqli_select_db("maplibrary",$con);
}
if (isset($_POST["save"])) {
$sql = mysqli_query("INSERT INTO member (memberID, firstName, surname, contactDetails)
VALUES('{$_POST['memberID']}',
'{$_POST['firstName']}',
'{$_POST['surname']}',
'{$_POST['contactDetails']}'
)");
if ($sql) {
echo "save successfully";
}
}
?>
here is the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>ViewMembers</title>
</head>
<body>
<form action="" method="post">
<table style="border:1 #F00 solid;width:500px;overflow:auto;margin:auto;background:#999;">
<tr>
<td>Member ID</td>
<td><input type="text" name"memberID" /></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name"firstName" /></td>
</tr>
<tr>
<td>Surname</td>
<td><input type="text" name"surname" /></td>
</tr>
<tr>
<td>Contact Details</td>
<td><input type="text" name"contactDetails" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save" name="save" /></td>
</tr>
</table>
</form>
</body>
</html>
You didn't add $conn as parameter of mysqli_query function.See usage :
http://www.w3schools.com/php/func_mysqli_query.asp
<?php
error_reporting(0);
$con = mysqli_connect("localhost","root","password") or die("error");
if($con)
{
mysqli_select_db("maplibrary",$con);
}
if (isset($_POST["save"]))
{
$sql = mysqli_query($con, "INSERT INTO member
(memberID,firstName,surname,contactDetails)
VALUES('{$_POST['memberID']}',
'{$_POST['firstName']}',
'{$_POST['surname']}',
'{$_POST['contactDetails']}'
)");
if ($sql)
{
echo "save successfully";
}
}
?>
Try this one:
<?php
$servername = "localhost";
$username = "username";//YOUR USER NAME!
$password = "password";//YOUR PASSWORD!
$dbname = "myDB"; //YOUR DB NAME!
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST["save"])){
$var1 = $_POST['memberID'];
$var2 = $_POST['firstName'];
$var3 = $_POST['surname'];
$var4 = $_POST['contactDetails'];
$sql = "INSERT INTO member(memberID,firstName,surname,contactDetails)
VALUES ('".$var1."', '".$var2."', '"$var3."', '"$var4."')";
if ($conn->query($sql) === TRUE) {echo "successfully saved";}
else {echo "Error: " . $sql . "<br>" . $conn->error;}
}
$conn->close();
?>
hope i understood your problem... :)
BTW i suggest you to create a php file that will contain only the connection, because you may will need to connect to the database again in some point so you do not want to copy your code again and again...
so you can create a connect.php that will contain only the connection lines, you can include it (connect.php) inside of any page you want. it will make kit much easier.
look at: php include
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 am a PHP/MySQL Greenback here, and I have run into an issue with a simple form I am trying to feed into a MySQL database via PHP, that keeps feeding blank entries.
The form is live, connecting and feeding to the DB, however whenever I submit an entry, my confirmation echo's back that it Connected successfullyINSERT INTO db_name.events (eventname, eventprice, eventabout) VALUES ('', '', '') Works! even though the values were populated in the HTML form. Then when I log in and check the MySQL Database through PHPmyadmin I can see that it indeed created a new row in the table, but it is blank.
I have spent hours combing the syntax line by line and can't seem to find anything out of place and I have now added a bunch of troubleshooting steps in to try and solve it.
Any help is greatly appreciated!
The HTML form is as follows:
<form method="post" action="eventtestconnect.php"><table style="border: 0; margin-left: auto; margin-right:auto;text-align: left">
<tr>
<td>Event Name:</td>
<td><input name="name"></td>
</tr>
<tr>
<td>Event Price:</td>
<td><input name="price"></td>
</tr>
<tr>
<td>Event Description:</td>
<td><textarea name="description" cols="40" rows="5">
</textarea></td>
</tr>
</table>
<br><br>
<input type="submit" value="Submit">
</form>
And the PHP file that connects to this form is:
<?php
// connect to database
$dbhost = '111.111.11.111';
$dbuser = 'db_name';
$dbpass = 'pwpwpw';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
//select database
mysql_select_db("db_name", $conn);
if ($_POST)
{
// scrub inputs
$name = mysql_real_escape_string($conn, $_POST['name']);
$price = mysql_real_escape_string($conn, $_POST['price']);
$description = mysql_real_escape_string($conn, $_POST['description']);
// prepare query
$sql = "INSERT INTO db_name.events (eventname, eventprice, eventabout)
VALUES ('$name', '$price', '$description')";
// execute query
mysql_query($sql);
// close connection
mysql_close($conn);
echo $sql;
}
?>
Thanks in advance for any help, I have been browsing these forums grabbing help and tips. Seems like a great community!
You passing in the arguments to mysql_real_escape_string in the wrong order. It should be:
$name = mysql_real_escape_string($_POST['name'], $conn);