I want to put two html edittext fields with a label next it saying please input a reg number and a button in the end, whereby the user can input a new registration number. I want to do it within the php script, but I don't know how to incorporate it
Thing is, I am not quite sure how to do this and how to validate the button on click. Like how do I get the values on button click?
This is what I have so far:
<?php
include "init.php"
if(!empty($_POST['driverNo'])){
$driverNoText = $_POST['driverNo'];
$stmt = "SELECT registrationNo FROM cars WHERE driverNo = ?";
$result = $conn->prepare( $stmt );
$result->bind_param( 's', $driverNoText );
$result->execute();
$result->store_result();
$result->bind_result( $registrationNo );
while( $result->fetch() )
{
echo $registrationNo;
}
$result->free_result();
?>
Is this even possible or would I have to create a html file and then include this php script?
Sorry, I am quite new to all this web dev stuff
Usually the flow for this kind of single purpose PHP file is that you can include html codes at the end of the PHP script. Treat PHP just like a html file, with a little bit advance thing that it's capable to do more than just HTML.
Which means, the file can be in this kind of format:
<?php
//------------------------
// Start of your php inits
// .....................
//------------------------
// Section where you have your code checking
//
if (!empty($_POST...
//do something useful, sanitize inputs, insert into db
//echo out something like "thanks for submission here"
} else {
//you can close the php tag here and put your html codes here
?>
<!doctype html>
.....
<form action="<?php echo $_SERVER['PHP_SELF'] ?>>
<input...>
<input type="submit" />
</form>
<?php
//and don't forget the closing bracket
}
If you are new and trying out PHP, go ahead and have this as the sample. This is generally not recommended anyway because it's a maintenance nightmare if your code grows. Generally you will need to look for frameworks that can help you with these tedious tasks.
Related
I've made a HTML file containing only a form with a textbox and a submit button.
The form calls a php that will check if the text from the textbox represents a register in the database.
Html file:
<form action="index.php" method="post">
<input type="text" name="nome"/>
<input type="submit" value="Rodar"/>
</form>
PHP file:
<?php
$nome = $_POST['nome'];
$pdo = new PDO('mysql:host=myhost;dbname=mydb', 'user', 'pw');
if ($pdo->query("SELECT * from renatinho where nome='".$nome."'")->fetchColumn() > 0){
foreach($pdo->query("SELECT * from renatinho where nome='".$nome."'") as $row) {
echo $row['id'] . $row['nome'];
}
$pdo = null;
}
else{
echo "Não há ninguém com esse nome.";
}
?>
The thing is: when I press the button it calls and displays the php file. The php file has no layout. I want the results to be displayed in the HTML file, cause i don't want to make a whole new page just to display the values.
I want the results to be in the same page where the form is.
I've being googling it for 2 days, but I don't know what exactly to search. All the results I got are tutorials that displays the php file, and that's what I'm doing now but that's not what I want.
You have a few options:
Combine the two files into one PHP file that has both HTML and PHP. Put your PHP code at the top of the script. Check if the form is being submitted like this: if ($_POST['submit'] == 'Rodar') { /* process form */ }. If the form was not submitted, your code that processes the form will be skipped and the form will just be displayed. If the form has been submitted, it will be processed and the form will be displayed again. This is probably the most common solution.
After processing the form in your PHP file, redirect back to the HTML file using header('Location: html_file.html'); die();. Just make sure you don't output anything to the screen before doing this (ie. echo).
You could submit your form using AJAX. This is a JavaScript call over HTTP to your server without reloading the page. Just google AJAX and you'll find a boatload of tutorials.
For clarification, it seems like you may not realize that you can combine HTML and PHP in a .php file. you can do this. You just either echo the HTML to the screen, or break out of your <?php tag with a ?> tag and start writing your HTML.
You can use just PHP/HTML to solve this. You can add the following to the page with the form on (which must be a PHP page, but that's easy to do).
To check if the user has submitted the form, you should see if there is data in one of the POST variables using if(isset($_POST['nome']) (where nome is one of the fields).
if(isset($_POST['nome'])) {
$nome = $_POST['nome'];
$pdo = new PDO('mysql:host=myhost;dbname=mydb', 'user', 'pw');
if ($pdo->query("SELECT * from renatinho where nome='".$nome."'")->fetchColumn() > 0){
foreach($pdo->query("SELECT * from renatinho where nome='".$nome."'") as $row) {
echo $row['id'] . $row['nome'];
}
$pdo = null;
else {
echo "Não há ninguém com esse nome.";
}
}
As for your form, to submit your form to the same page, just don't set the action attribute (in HTML5).
<form method="post">
(Remember to put <!doctype html> at the top of your page so that HTML5 is used)
Hope this helps.
You should use AJAX to send a request to the server, possibly returning data to show on the page.
#worldofjr makes a good point; you can check $_POST data to see if something was submitted, if you're OK with the user making another request to the page anyway
<?php
if(isset($_POST['fieldname'])){
//whatever code here
}
?>
<form method="post">
...inputs here...
</form>
Well I am a newbee so kindly please ignore if there is any mistake in my question,I have this question on my mind.Iam just creating a small website like a profile information.
Okay see when user logs in with his email into the website, we use php scripting and retrieve the data from mysql and put that data in the page using mostly printf or echo
So there is possibilty of 2 ways to do
for example one of the table of my database looks like this
name birthday aboutme gender dreams music movies blabla//
someperson xx xx xx xx xx xx
first method demo.php
<html>
<body>
name: <?some php script to get user name?>
<20 lines of html tags and data>
birthday: <?some php script to get user name?>
<20 lines of html tags and data>
about user <?some php script to get user about?>
<some more html data>
<?some more php scripting?>
In the first method we are always connecting to the database and getting the data and then after 20 lines of html code and then again we are connecting to the same table and database and getting the next columns value and disconnecting it and then again we are connecting to the server and more. In this process we are connecting and disconnecting from server
So in the first method we are always connecting and disconnecting from server, I was just thinking it may cause a serious overhead on the server as we are connecting and disconnecting for every 10 lines of code.is my thinking true or is there anything wrong?
second method demo.php
<?php
retrieve all the data you need at a time here and then use
echo "<html>"
echo "<body>"
echo "name: <?just php variable value that was retrieved?>
echo "<20 lines of html tags and data>"
echo "birthday: <?just php variable value that was retrieved?>
?>
In the second method we are using the php script run by server just get the data at the start and then just echo them with the html tags and data that was retrieved, but i was thinking it is so unneccasary because we are making the server to execute the html tags where a normal browser clearly would do
I am finding both ways causing a serious overhead issue on the server.could anyone explain what is the best way to do it? is there any other way the professionals choose , I am not sure how they make through it.
Well is there a way to retrieve the data at once from the database and then just echo it back between the html tags?
simply like
<?get all the data from database here>?
<div> echo 'some php variable'
<span> echo 'some php variable'
Is there a way like this? Kindly let me know the best approach to do it.Thanks
any help is greatly appreciated
You are correct in thinking that you do not have to declare all of your html using php echo. The php generates the HTML as it moves down your code. So you can declare HTML inbetween php calls.
For example:
<html>
<body>
<?php
$results = mysql_query(SELECT name,gender FROM table WHERE id='34';
// Additional code to assign $results array to variables
?>
<div><?=$name;?></div>
<div><?=$age;?></div>
</body>
</html>
The most important thing to note is that you can call php multiple times through out your document and it will continue to work off past php calls. All variables and functions are stored throughout the page.
Hope this helps.
If all your data is in the same table then you only need a single query. And you should switch in and out of php instead of composing the html inside php. It might look something like this:
<?php
$db = new PDO($dsn, $user, $password);
$stmt = $db->prepare('SELECT * FROM user_profile WHERE user_id = ?');
$stmt->execute(array($user_id));
$profile = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->close();
?>
<html>
<head>
<title> <?php echo $profile['username']; ?> Profile</title>
</head>
<body>
<div>
<div>
<div>
<?php foreach($profile as $attribute => $value): ?>
<div>
<span class="label"><?php echo $attribute ?></span>
<span class="profile_value"><?php echo $value; ?> </span>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
</body>
</html>
Yes, I would get all of the data up front if that is possible (if it is not dependent on anything else in the execution of your script).
If I follow what you are saying correctly, you are pretty close in your pseudocode at the end there. You seem to want something like this:
<?
// here is where you get all the data from MySQL using PHP
?>
<!-- HTML now -->
<div>
<?
//PHP starts again
echo $something;
//PHP ends
?>
<!-- HTML again -->
</div>
You can jump in and out of PHP as many times as you'd like, whenever is most appropriate.
I want to insert data in a MySQL database with PHP and XHTML.
I have my functions of database in a single file: database.inc.php, in this file I wrote a lot of functions: function insert_city($_POST), function insert_state($_POST), function insert_customer($_POST), etc.
I'd like know the best way to call these functions. For each transaction I have a XHTML file.
For example. This is the structure of my addcustomer form:
<form action="addcustomer.php" method="POST">
<input>...
</input>
</form>
From this file I am calling to another PHP file called addcustomer.php. This file has more or less the following content:
<?php
include('database.inc.php');
if (insert_state($_POST)){
echo "Good";
} else {
echo "Bad insertion";
}
?>
With this approach I am losing my forms, after the user inserts its data I'd like to show the form and the error message or success.
I know is a good practice group the functions into one file, but I don't like to write scripts like the one above, I'd prefer write each function in different file.
Tips, advices or reprimands?
Set the action of the form to "" or $_SERVER['PHP_SELF'] so that when the form is submitted the same file is loaded.
Then at the top of that file you add something like:
if ( $_SERVER['REQUEST_METHOD'] == 'post' ) {
require( 'addcustomer.php' );
if (insert_state($_POST)){
$form_status = "Good";
} else {
$form_status = "Bad insertion";
}
}
Then you can use $form_status to display a message in your form.
Ideally though you want to separate the code from the html, but that a different lesson.
This is my super-simplified index.php:
<?php
require_once 'DeleteOrAdd.php'; // handles adding/deleting a db record
doAddDeleteRecord();
// other functions are called here, left out though for brevity
?>
Here's DeleteOrAdd.php (much simplified)
<?php
function doAddDeleteRecord()
{
echo <<<_END
<form action="index.php" method="post">
// the other form html not shown here
<input type="submit" value="ADD RECORD" />
</form>
_END;
// NOT SHOWN -- code to handle the form when it is POST'd
}
?>
So it's late 10:30pm, I'm new to PHP, okay /excuses.
Can't figure out how to do this.
I want to change my form action="index.php" above to form action="DeleteOrAdd.php"
(ie. I want to re-post to the same file that this form is in,
not to index.php, so the code is cleaner).
but it won't work because I have all the form-handling logic for the POST --
inside the doAddDeleteRecord() function, so if I set my form action="DeleteOrAdd.php"
it won't work.
Is it possible to do something like form action="DeleteOrAdd.php:doAddDeleteRecord()?
I don't want to put this in classes.
I also want to keep my index.php just as it is above -- calling functions and no major
inline code beyond that.
Any ideas?
Originally, all the code was inline inside index.php (got it from a PHP book's sample)
and I then divided the code into logically-named PHP files in the Netbeans project
to clean it up, and to put stuff in functions that get called from index.php.
remove the action value completly from the form, default it will post always back to the url on which it is displayed.
<form action="" method="POST">
Your application is not well structured. I would recommend to follow MVC pattern.
But for your current problem you can do something like this
just set the action to your <form action="DeleteOrAdd.php" or you can leave the action completely blank which post your data on the same file in which the form is created.
When the form is posted your could do below in your DeleteOrAdd.php file.
if (isset($_POST['submit']))
{
doAddDeleteRecord();// this will call your
}
but in this case you may have to change the code of your index.php
I think the problem you have here is being able to make your PHP page discern between whether or not its a fresh load or whether or not its submission of the form, and that is why your incorporating the index page in your action parameter. However, this is not necessary.
Set the id and name (for valid markup) attribute of your submit element to a unique name. Such as "form_submit" so here is an example.
<form action="" method="post">
<input type="submit" id="form_submit" name="form_submit" value="ADD RECORD" />
</form>
So what you put in your PHP script (doAddorDelete.php) is this ...
if (array_key_exists('form_submit', $_POST)) {
//this is the code to execute on form submit
//use print_r($_POST) to view variables you can use here
//make sure you validate all data passed here especially if using a database
//ie if MySQL
//$validated_userinput = mysql_real_escape_string(strip_tags(htmlentities(trim($_POST['userinput']))), $link_resource); for text
//(int) $_POST['userinput']; for numbers
} else {
echo <<<_END
<form action="" method="post">
// the other form html not shown here
<input type="submit" id="form_submit" name="form_submit" value="ADD RECORD" />
</form>
_END;
}
Hope this helps! :)
Foreword: Since you say this as a learning exercise, I'll skip past the sanctimonious manifesto on best practice and the many and sundry virtues of OOP. ;) Your book probably details every dire warning / stern lecture I'd normally prepend to a solution like this anyway.
Is it possible to do something like
form
action="DeleteOrAdd.php:doAddDeleteRecord()
?
In short, yes. The easiest way to accomplish your goal is to just reference your file in your form action, as you've done:
<!-- form.php -->
<form action="DeleteOrAdd.php" method="POST">
And then in DeleteOrAdd.php, trigger your function by testing the $_POST data your form submit will send in, like so:
<?php
// DeleteOrAdd.php
if(isset($_POST['some_form_variable']) && $_POST['some_form_variable'] != null) {
$data = array();
foreach($_POST as $post) {
array_push($data, $post);
}
doAddDeleteRecord($data);
}
function doAddDeleteRecord($data) {
// ...your processing code, etc.
The upshot to a purely procedural approach like you've specified is quite frankly, you can do stuff like this. You wouldn't want to develop like this in real life (skipping this deep-dive too, I guarantee your book explains why not in exhaustive detail.)
Important note!! Since I didn't see a return value in the code snippet you posted, and you say you're just getting started, I'm going to take a minute and point out a hidden pitfall here just in case:
--> Your code might work perfectly with those six lines I added above your function, and you'd never know it if you're not
returning a value (which proves the code ran, if nothing else) and
capturing said value so you can act on it / display it / otherwise show yourself that
a. something happened -- and ideally,
b. what that something was.
Otherwise, all you've got is ambiguity: no indication it's either working or breaking (not throwing errors, warnings, etc). Frustrating to debug, to say the least.
So, that stated -- presuming you've got your function returning something (true on success, string with a message, whatever) it probably goes something like this:
function doAddDeleteRecord($data) {
// ... your function code, etc.
$sql = "INSERT INTO mytable VALUES(".implode(',',$data).")";
if (mysql_query($sql) == true) {
$message = "Record saved";
} else {
$message = false;
}
return $message;
}
Any value your function returns needs a variable to capture it or it won't be set. Capture it with a variable assignment when you call your doAddDeleteRecord() function:
... // same 6 little lines of conditional code ...
}
$result = doAddDeleteRecord($data);
}
// maybe just echo it out or something...
echo $result;
-- or --
... // still the same 6 lines ...
}
$result = doAddDeleteRecord($data);
}
// maybe have a new test based on the outcome of the last one...
if ($result == false) {
// do something about the fail...
} elseif (is_string($result)) {
// do something about the success...
}
Good luck, HTH. :)
So I have a form that I post to a page and in the form I'm posting certain variables that I build one of my queries with and then call them on my page. How can I post data and also build a query and display the answer on one call?
Maybe I'm not wording it right and I'm learning this stuff, but I just don't know. Should I post to an intermediate page first?
Example: form (variables A & B) to-> page (A & B used in query) and then result is on that same page.
can this be done and what's the method?
Thanks!
This is the basic priniciple, but you must sanitize you input data from the form. For example using mysql_real_escape_string().
But in a single page you can have code like this (it is not tested, I'm not able to on this computer):
<?php
if(isset($_POST['name']))
{
$query = "SELECT * FROM table WHERE firstname = '"+ mysql_real_escape_string($_POST['name']) +"'";
while($node = mysql_fetch_rows())
{
echo "The result: " . $node['id'];
}
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name" />
</form>
This will post to it self, run the query and echo the result, and show the form again.
For small tools and the like, this is an ok approach, but for larger websites I would recommend not mixing the request handling code with the html. Look into using a framework for applying the mvc pattern or something like that.
Without specific examples it's hard to write it, but it's fairly simple.
In a very basic way:
File1.php:
--your form submits to file2.php--
File2.php:
function processForm(inputs) [
--MySql query goes here--
]
function displayResults() [
--Process your query results--
]
processForm($_POST['vars']...);
displayResults();
Does that make sense? Simply make a function that processes and then displays the results again.
If you want to get really fancy you can even do it all in a single file, but you should probably master this technique first if you are first learning.