I am trying to make a webpage that connects to my SQL database and fetches information from a table and place it into a text box. The information it fetches is dependent on what is entered into another text box. Essentially its an "autofill" of information. I was curious whether this was possible.
To create a better understanding here is a layout of text boxes:
<html>
<head>
<?php
$con = mssql_connect("abc", "123", "password");
if (!$con)
{
die('Could not connect: ' . mssql_get_last_message());
}
mssql_select_db("db1", $con);
$result = mssql_query("SELECT * FROM FormData");
<head>
<title>test</title>
</head>
<body>
<h1>test</h1>
<form action="#">
<p>Enter ID</p>
<input type="text" name="ID"/>
<input type="text" name="NAME"/>
<input type="text" name="LASTNAME"/>
<input type ="button" value="submit" onclick="check(ID)" />
</form>
</body>
Here an ID would be entered into a text box and then once the submit button was pressed, it would fetch the rest of the information from my sql database into the next boxes. I don't even know whether this is possible, whether I can use Javascript in conjunction with this or something. I searched but couldn't find much help on the subject.
I'm not even sure if its possible to do "if" statements within SQL - whenever I try I end up with a 500 error due to improper syntax.
If I understand you correctly, all you need to do is on the submission of the form capture the ID they entered.
If the ID has not been submitted yet (either their first time hitting the page, or they failed to enter an ID) you should not perform any query and create a blank $row array like so:
$row = array("ID" => "", "NAME" => "", "LASTNAME" => "");
You should then fill your form fields using this array <input type="text" name="NAME" value="<?php echo $row['NAME']; ?>"/>.
If the ID has been submited you then use this ID in your SQL query "SELECT * FROM FormData WHERE ID = $_POST['ID']" (Note: This is an example. You will need to escape the POST data to prevent SQL injection).
You need to then pull this result into your $row array $row = mysql_fetch_row($result) which in turn is used by your fields to populate the value.
This entire procedure could be done with AJAX so that you don't have to perform a full page submit however based on your example the solution I have provided should be good enough.
Related
I have a form in HTML which posts two values hostname and ip_address.
<form action="demo-select.php" method="post" />
<p>HOSTNAME/IPADDRESS: <input type="text" name="HOSTNAME" name="IP_ADDRESS" /></p>
<input type="submit" value="Submit" />
</form>
If I enter the hostname/ip_address and submit it, it will take me to demo-select.php script.
In demo-select.php script I'm able to get the output for hostname from my MySQL db. How should I get the output based on ip_address?
$value = $_POST['HOSTNAME'];
$query = "SELECT * FROM <tablename> WHERE HOSTNAME='$value'";
$result = mysql_query($query);
This script connects to a MySQL db and gets the output based on the hostname. What modifications should I make to get the output based on ip_address as well?
Table columns:
HOSTNAME
IP_ADDRESS
cpus
MEMORY
HTML:
You can't assign two names to an HTML element. I'd suggest that you either use two fields or use a dropdown / radio button along with the form field for the user to specify whether they're entering a hostname or an ip_address:
<form action="demo-select.php" method="post" />
<select name="address_type">
<option value="ip"> IP Address </option>
<option value="host"> Host Name </option>
</select>
<input type="text" name="host_name_or_address" />
<input type="submit" value="Submit" />
</form>
An assumption here is that you'd want the user to enter as input only one of hostname or ip_address in a single submit. If you want both to be relayed to the PHP at once, then please get rid of the select dropdown and use two input fields instead.
PHP:
Check what's been received in address_type and determine what query to use accordingly:
$address_type = $_POST['address_type'];
$value = $_POST['host_name_or_address'];
if($address_type == "host"){
// If looking for partial matches, use... WHERE HOSTNAME LIKE '%$value'
$sql = "SELECT * FROM <tablename> WHERE HOSTNAME = '$value' ";
}
else{
$sql = "SELECT * FROM <tablename> WHERE IP_ADDRESS = '$value' ";
}
Again, if you want both fields to be searched for at once, then along with the HTML edits indicated in the narration above, you'll have to receive in a PHP variable the value of the second input field too. Also then please get rid of the if-else construct here above and write a single, combined query as:
$sql = "SELECT * FROM <tablename> WHERE HOSTNAME = '$value1' AND IP_ADDRESS = '$value2' ";
Finally, please don't use mysql_*() functions in any PHP code. They're long deprecated and are very vulnerable to SQL Injection Attacks as Daniel has already suggested in his answer. Please have a look at MySQLi and PDO Prepared Statements instead. These utilities provide a cleaner way to write your queries and also a much safer mechanism to shield them against potential risks.
Being new to PHP and SQL, I have build a simple HTML form with 20 inputs, allowing users to enter specific data through input type=text or file. I have built a mysql database where this user data is inserted / saved. All is working, this is a major accomplishment for me.
I'm asking for help on this next step, I think this step would be called “edit”?
This step would allow users to recall the mysql data they entered, at a later time, to edit and save. Would like to have this recalled data injected directly into the original HTML form. Now, it seems necessary to have a method, (possibly a HTML form ”id “input), that calls from the data base, the specific record (including all 20 data inputs) that is associated with this user. Am I thinking correctly?
I'm asking for help / direction with simple yet detailed approach to solve this step. Note, my few attempts at this “edit” step, using some examples, have failed. I do not have a firm grasp of this PHP, yet have strong desire to become proficient.
This is a model, stripped down version of my current working code. I eliminated the $connection = mysql_connect.
This is the PHP I built, working great!
<?php
require('db.php');
if (isset($_POST['first_name'])){
$first_name = $_POST['first_name'];
$favorite_color = $_POST['favorite_color'];
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `form_data` (first_name, favorite_color, trn_date) VALUES ('$first_name', '$favorite_color', '$trn_date')";
$result = mysql_query($query);
if($result){
echo "<div class='form'><h1>First Name & Favorite Color POST to db was successfull.</h1>
<br/><h3>Click here to return <a href='https://jakursmu.com/tapcon_builder/tb_form_data_1.1.php'>TapCon Builder</a></h3>
</div>";
}
}else{
?>
This is the HTML user form, works great with the PHP script:
<div class="form">
<h1>First Name & Favorite Color "POST" to db Test</h1>
<form target="_blank" name="registration" action=" " method="post">
<p> First Name<input name="first_name" type="text" placeholder="First Name" /> </p>
<p> Favorite Color <input name="favorite_color" type="text" placeholder="Favorite Color" /> </p>
<p> <input type="submit" name="submit" value="Submit / Update to db" /></p>
</form>
</div>
Suppose the user queries the database using their “first_name”, when this “edit” step is completed, the final result will render / inject the users “first_name” and “favorite_color” back into the original HTML form. Does this make sense?
The database I created for this help post, looks like this:
database image
When a user wishes to edit their data, they can enter their "first_name", in a form text input, (im assuming?) where their "first_name" will be found in the data base. The ouutput result of this database query will be injected into the original form, ready for any user edit.
User Edit for: Results (in origingal form):
Jack Jack Black
Jeff Jeff Green
Randall Randall Red
So on.........
I hope this explanation makes sense where any experienced help or direction is offered.
Thanks for viewing!
just for practice purposes, but can look into prepared statements at you liesure time.
first create ur php file
<form method="post" action="edit.php">
<?php
//in ur php tag. select items from the row based on an id you've passed on to the page
$sql = "select * from 'form_data' where blah = '$blah'";
$result = mysqli_query($connection, $sql);
if($result){
$count = mysqli_num_rows($result);
if($count > 0) {
while($row = mysqli_fetch_assoc($result)){
$name = $row['firstname'];
$lname = $row['lastname'];
//you can now echo ur input fields with the values set in
echo'
<input type="text" value="'.$name.'" >
';//that how you set the values
}
}
}
?>
</form>
Finally you can run and update statement on submit of this you dynamically generated form input.
Also please switch to mysqli or pdo, alot better that the deprecated mysql.
look into prepared statements too. Hope this nifty example guides you down the right path...
so I've finally figured out how I can get values from my mySQL-db into a dropdown form in PHP. My problem is, how can I use/work with the option that was selected by the user?
My goal is a functioning email-signature generator. I want the user to be able to insert unique data like their name, and select the office where they work from the dropdown form. After they hit the submit button, they should then be lead to the next site that displays their name with the signature for the selected office.
The name is no problem, that is only a simple html-form with a post method, I know how I can retrieve and access that.
But how can I work with the option that was selected by the user in the dropdown?
After selecting an option and hitting submit, the whole "row" in the mySQL-db should be displayed, in formated form.
My current situation is that the dropdown shows the correct values from the mySQL-db, and the two name fields, that are also working as they should.
The name of the mySQL database is "firmen", the name of the column I use is "niederlassung".
I'm happy to provide more information if needed.
My code:
[...]
<form action="php-verarbeitung.php" method="post">
<div>
<label for="1">Vorname: </label>
<input type="text" name="vorname" id="1" value=""><br><br>
</div>
<div>
<label for="2">Nachname: </label>
<input type="text" name="name" id="2" value=""><br><br>
</div>
<input type = "submit" name = "button" value = "Senden"><br><br>
<?php
// Establish mySQL PDO Connection
$server='mysql:host=*****.com.mysql;dbname=*****'; // Host and DB-Name
$user="******"; // Username
$password="*****"; // Password
$pdo=new PDO($server, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Write out the query
$query = "SELECT niederlassung FROM firmen";
// Execute it, or let it throw an error message if there's a problem
$stmt = $pdo->query($query);
$dropdown = "<SELECT name='firmen'>";
foreach ($stmt as $row) {
$dropdown .= "\r\n<option value='{$row['niederlassung']}'>{$row['niederlassung']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
</form>
</body>
</html>
Thanks for any help in advance!
you are passing the variables through the form to php-verarbeitung.php. On that page you can load the content based on the $_POST variables that are sent through the form. so you can query the DB again on the second page to get the info you need, and present formated html using the values from the form passed through the post array, in your case
$_POST['vorname'], $_POST['name'] and $_POST['firmen'] should all be accessible when the php-verarbeitung.php page is called using your script above.
I am very new to SQL and to say the least, I am struggling.
My table looks like this:
All I want to do is be able to increment any of these values by one upon the press of a button, like this:
This is how it looks on the website, but nothing is functional at all yet.
I have an understanding of HTML, CSS, and PHP, so if I were to know the correct way to do this with SQL, I should be able to implement it.
Thanks.
Ok, I see people suggesting AJAX ("elsewhere" as well as here), but you are unfamiliar with this. I'm going to suggest a completely non-Javascript solution, sticking with HTML, PHP, and MySQL, as you already know these. I would definitely recommend learning Javascript at some point though.
I've no idea of your level of understanding, so please let me know any bits of the following code you don't follow, and i'll explain in more detail.
<?php
/* Initialise the database connection */
$db = new mysqli("localhost", "username", "password", "database");
if ($db->connect_errno) {
exit("Failed to connect to the database");
}
/* First, check if a "name" field has been submitted via POST, and verify it
* matches one of your names. This second part is important, this
* will end up in an SQL query and you should NEVER allow any unchecked
* values to end up in an SQL query.
*/
$names = array("Anawhata","Karekare","Muriwai","Piha","Whatipu");
if(isset($_POST['name']) && in_array($_POST['name'], $names)) {
$name = $_POST['name'];
/* Add 1 to the counter of the person whose name was submitted via POST */
$result = $db->query("UPDATE your_table SET counter = counter+1 WHERE name = $name");
if(!$result) {
exit("Failed to update counter for $name.");
}
}
?>
<table>
<?php
/* Get the counters from the database and loop through them */
$result = $db->query("SELECT name, counter FROM your_table");
while($row = $result->fetch_assoc()) {
?>
<tr>
<td>
<p><?php echo $row['name'];?></p>
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<input type="hidden" name="name" value="<?php echo $row['name']; ?>" />
<input type="submit" name="submit" value="Add One" />
</form>
</td>
<td><?php echo $row['counter']; ?></td>
</tr>
<?php
} // End of "while" each database record
?>
</table>
One way is to use AJAX on sending the form to make calls to a php script that handles the mysql query and "adds one". You should put a hidden input with the name of the person you want to increment. That's if you don't want to refresh the page.
If you don't mind refreshing, make every button part of a form, and send to the same php file.
I recently came across a library, called meteor.js that is capable of doing all this. I have not yes tested it, though.
I am trying to make my own booking diary with php, sql and html.
I would like to be able to prevent found booking on my booking form by checking my database to see if a record already exists before allowing my insert statement to execute.
I would ideally like to be able to do a select statement to check if a booking already exists.
IF the TIME AND DATE DOES NOT exist I would like the RADIO BUTTON PRESENT
ELSE
IF the TIME AND DATE DOES I would like the radio button NOT PRESENT .
I have been thinking long and hard but cannot think of a way to do it.
Please could I have some suggestions on how I can overcome my problem?
Thanks
My SQL Table is as follows
TABLE Bookings(
bDate Date,
bTime Time,
bName CHAR(30),
bNumber CHAR(30),
bReg CHAR(30),
bMakeModel CHAR(30)
)
This is what I have so far, but I can't think how to do it, I think I may be going about this the wrong way and perhaps a incremented for loop would be better suited:
<?php
$result = mysqli_query($con,"SELECT * FROM Bookings WHERE bDate = '$_POST[bDate]' ORDER
BY bTime;");
while($row = mysqli_fetch_array($result)){
if $_POST["bDate"] = $row['bDate'] AND $_POST["bTime"] = !$row['bTime']{
<input type="radio" name="bTime" value="08:00:00"> 8:00
}
?>
<input type="radio" name="bTime" value="08:00:00"> 8:00
<input type="radio" name="bTime" value="09:00:00"> 9:00
<input type="radio" name="bTime" value="10:00:00"> 10:00
<input type="radio" name="bTime" value="11:00:00"> 11:00<br>
<input type="radio" name="bTime" value="13:00:00"> 13:00
<input type="radio" name="bTime" value="14:00:00"> 14:00
<input type="radio" name="bTime" value="15:00:00"> 15:00
<input type="radio" name="bTime" value="16:00:00"> 16:00<br>
Until you post some code for a better help, database structure and eventually an exemple of one one or 2 rows. Here are the steps.
For checking part (form) :
If you haven't submitted your form, use AJAX to check in your database.
If you've submitted form, just execute a query on your database.
For SQL part :
A simple count can do the trick (return 0 if no rows found and n if n rows found), but retrieving an ID is better (NULL if no rows found). If you need help on query, describe the table structure, and the fields you are checking.
For the last part (showing or not the label :
In PHP, just need to test your SQL return and implement a condition test on the count value (> 0 or not), or ID (NOT NULL if row found, else NULL).
You can add the radio button (or not) depending of your test result
Tip :
Using ID is better because you can add it in an hidden INPUT tag if you've found a row. If later you decide to update it, it will be possible with this id.
Edit (with your code now) :
In your PHP code you have many errors :
-> your if condition isn't surrounded by the parentheses
-> Logical operators in PHP statement aren't like in SQL : AND (SQL) = && (PHP)
-> Inside your if, the input tag isn't in an echo. input tag is HTML not PHP
Tips :
- Are you sure you have a good connexion ($con) ressource to database?
- In sql string no need to add the final semi-colon ";"
- Always about SQL using the star alias in query run slower than enumerating each field. If one day you need to get a huge resultset, it would be an optimization
Seems nobody answered to your question. Here is a little starting code for you. Don't forget to replace with your database server, user, password and database to connect to mysql :
<?php
$mysqli = new mysqli("host", "user", "password", "database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>sans titre</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 1.23.1" />
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>Date : <input type="text" id="bDate" name="bDate" value="" /></p>
<p>Time : <input type="text" id="bTime" name="bTime" value="" /></p>
<input type="submit" value="Send" />
</form>
<hr />
<?php
/* Check if form is submitted */
if (isset($_POST["bDate"])) {
// Need a bDate format = 'YYYY-MM-DD'
if (!preg_match("/^\d{4}\-[0-1][0-9]\-[0-3][0-9]$/", $_POST["bDate"])) {
printf("dDate pattern error for SQL. Waiting YYYY-MM-DD");
exit();
}
/* Execute query */
$query = "SELECT `bDate` , `bTime` , `bName` , `bNumber` , `bReg` , `bMakeModel` FROM `Bookings` WHERE `bDate` = '". $_POST["bDate"] . "' ORDER BY 2";
$result = $mysqli->query($query);
/* Parsing result set */
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
printf ("%s (%s)<br />", $row["bDate"], $row["bTime"]);
if ($_POST["bDate"] == $row["bDate"] && $_POST["bTime"] != $row["bTime"]) {
printf ("<input type=\"radio\" id=\"bTime\" value=\"%s\" /> %s<br />", $row["bTime"], $row["bTime"]);
}
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
</body>
</html>
You have some checking on mysql connection, POST dDate variable. Also use the free once result set is no more necessary. Hope this help you.