Let say I have file1.php containing:
<!DOCTYPE html>
<html>
<head>
<title>My page</title>
</head>
<body>
<form action="file1.php" method="post">
<input type="radio" name="radio" value="1">1
<input type="radio" name="radio" value="2">2
<?php include 'file2.php'; ?>
<input type="submit" name="submit" value="Submit">
</form>
//some codes omitted here
</body>
</html>
and file2.php:
<?php
header('Content-Type: application/json');
$value_selected = 0;
if (isset($_POST['submit'])) {
if(isset($_POST['radio'])) {
$value_selected = $_POST['radio'];
}
}
include("connect_to_database.php");
$sql =
"SELECT field1, field2 FROM some_table WHERE field1 = ".$value_selected;
$query = mysql_query($sql);
$data = array();
while ($row = mysql_fetch_assoc($query)) {
$data[] = $row;
}
mysql_free_result($result);
print json_encode($data);
?>
The problem is when I run file1.php, it displays in text (JSON I believe) form because of the header in file2.php. Is there any way to make only the file2.php in JSON format but not file1.php?
If you are not quite ready for coding an AJAX call to ask for this data from your javascript then this may get you moving in the right direction.
It will load the data into a javascript variable that can be used from your other javascript
file2.php
<?php
$value_selected = 0;
if (isset($_POST['submit'])) {
if(isset($_POST['radio'])) {
$value_selected = $_POST['radio'];
include("connect_to_database.php");
$sql = "SELECT field1, field2
FROM some_table
WHERE field1 = ".$value_selected;
$query = mysql_query($sql);
$data = array();
while ($row = mysql_fetch_assoc($query)) {
$data[] = $row;
}
echo '<script type="text/javascript">';
echo 'var theData = ' . json_encode($data) . ';';
echo '<script type="text/javascript">';
mysql_free_result($result);
}
}
?>
Now call this from inside your <head> tag and you will be a little closer to what you want.
file1.php
<!DOCTYPE html>
<html>
<head>
<title>My page</title>
<?php include 'file2.php'; ?>
</head>
<body>
<form action="file1.php" method="post">
<input type="radio" name="radio" value="1">1
<input type="radio" name="radio" value="2">2
<input type="submit" name="submit" value="Submit">
</form>
//some codes omitted here
</body>
</html>
However I feel I must add
Please dont use the mysql_ database extension it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions and prepared statements.
Start here
Related
I'm starting with php (but I was quite experienced on C++) and I have some questions. The thing is that I would like to have several forms in the index.php, and to have the code more clean I would like to call functions to call the forms.
Right now, I'm having the running code as teh follow:
<html>
<head>
<title>Prueba de PHP</title>
</head>
<body>
<form id="nomfromnum" action="getCharName.php" method="GET">
<input type="number" min="1" name="charidbox" required>
<input type="submit" value="Seleccionar personaje">
</form>
<form id="despPers" method="POST">
<select name="nomChar">
<?php
include("conection.php");
$con=conectar();
$sql = "SELECT * FROM Personajes";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row["Character_id"].'">'.$row["Character_name"].'</option>';
}
?>
</select><br>
</form>
</body>
</html>
In the first form, I was able to move it into another file (getCharName.php). But for the second function (despPers), that creates a dropdown menu and populates it with its values, I wan't able to find the way to move it to another file. I tried to chance the header for and create a file despPers.php with the following code but it didn't worked.
<select name="nomChar">
<?php
function despChar($conexion){
$sql = "SELECT * FROM Personajes";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row["Character_id"].'">'.$row["Character_name"].'</option>';
}
}
include("conection.php");
$con=conectar();
despChar($con);
$con->close();
?>
</select><br>
Can anybody guide me with this? Maybe it's something basic, but I'm quite freshman on php and html.
Thanks a lot!
Oops, it was a wrong variable name.
Anyway, here you have what I have done.
On the index.php
<form id="despPers" action="despChar.php" method="POST">
<select name="nomChar">
<?php
include("despChar.php");
despChar();
?>
</select><br>
</form>
And the despChar.php is
<?php
function despChar(){
include("conection.php");
echo '<option value="0">Character</option>';
$con=conectar();
$sql = "SELECT * FROM Personajes";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row["Character_id"].'">'.$row["Character_name"].'</option>';
}
$con->close();
}
?>
So I have a script using HTML, PHP, and mysql, and I want to display a button under certain circumstances.
Here is my script:
<?php
include_once('dbconnect.php');
$q = $_POST['q'];
$q = $_GET['query'];
$query = mysqli_query($conn,"SELECT * FROM `Persons` WHERE `id` LIKE '%$q%'");
$count = mysqli_num_rows($query);
if($count != "1"){
$output = '<h2>No result found!</h2>';
}else{
while($row = mysqli_fetch_array($query)){
$s = $row['name'];
$output .= '<h2>Found: '.$s.'</h2><br>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
</head>
<body>
<form method="POST" action="index.html">
<input type="submit" name="return" value="Return">
</form>
<?php echo $output; ?>
</body>
</html>
Specifically, I want to display the return button only when the output is "No results found", when the amount of rows in the SQL database matching the given query is not 1. How could I go about accomplishing this? I'm relatively new to PHP and mySQLi, but from my research I couldn't figure out how to do such a task, any ideas?
<?php
if ($count==0) {
echo '<input type="submit" name="return" value="Return">';
}
?>
If you want a much cleaner html code, do this:
<form method="POST" action="index.html">
<?php if ($count!= "1") : ?>
<input type="submit" name="return" value="Return">
<?php else : ?>
<!-- put your other button here -->
<?php endif; ?>
</form>
You can read more about escaping from HTML here.
<?php
include_once('dbconnect.php');
$q = $_POST['q'];
$q = $_GET['query'];
$query = mysqli_query($conn,"SELECT * FROM `Persons` WHERE `id` LIKE '%$q%'");
$results = mysqli_fetch_array($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
</head>
<body>
<form method="POST" action="index.html">
<input type="submit" name="return" value="Return">
</form>
<?php if(0 < count($results)) ?>
<?php foreach($results AS $row) : ?>
<h2><?= $row['name'] ?></h2>
<?php endforeach; ?>
<?php else : ?>
<H2> No results found!</h2>
<?php endif; ?>
</body>
</html>
I am currently working on a school project and I need a little help. I am writing PHP/SQL code for a page where, when the user submits a form, a query runs that loops through and displays the user text input and also the value associated with the <select> dropdown.
(For a visual idea of what I mean, visit http://themanaclub.com/themarketplace2/themarketplace2.php)
Here is my code:
<?php
include_once ('connection2.php');
if (($_SERVER["REQUEST_METHOD"] == "POST") && (isset($_POST['card_catalog_form']))) {
$card_name = mysqli_real_escape_string($conn, $_POST['card_name']);
$card_label = mysqli_real_escape_string($conn, $_POST['card_genre']);
$insert_card_genre_query = sprintf("INSERT into card_catalog (card_name, label_id) VALUES ('%s', %u)",
$card_name,
$card_label);
$insert_card_genre = mysqli_query($conn, $insert_card_genre_query) or die (mysqli_error($conn));
$last_record = mysqli_insert_id($conn);
}
$card_genre_query = "SELECT card_genre.genre_id, card_label from `card_genre` order by genre_id desc";
$card_genre = mysqli_query($conn, $card_genre_query) or die(mysqli_error($conn));
$get_card_genre_query = "SELECT card_catalog.id, card_name, label_id, card_label from card_catalog left join card_genre on label_id = genre_id";
$get_card_genre = mysqli_query($conn, $get_card_genre_query) or die(mysqli_error($conn));
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>The Marketplace By The Mana Club</title>
<link rel="stylesheet" type="text/css" href="stylesheets2/tmp2.css">
</head>
<body>
<?php include('templatestuff2/top_of_tmp2.php'); ?>
<main>
<h1>Card Input Form:</h1>
<form id="card_name_entry" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
<h4>What Card Are You Looking For?</h4>
<textarea name="card_label" rows="5" cols="30" placeholder="Write the name of the card here"></textarea>
<p>
<select name="card_genre">
<?php while ($row_card_genre = mysqli_fetch_assoc($card_genre)) { ?>
<option value="<?php echo $row_card_genre['genre_id'];?>"><?php echo $row_card_genre['card_label'];?><?php echo $row_card_genre['card_name'];?></option>
<?php } ?>
</select>
</p>
<?php $query = "SELECT label_id from `card_catalog` right join `card_genre` on genre_id"; ?>
<p id="textareasubmit"><input type="submit"></p>
<input type="hidden" name="card_catalog_form">
</form>
<section id="all_questions">
<ul>
<?php while ($row_card_genre = mysqli_fetch_assoc($get_card_genre)) { ?>
<li><?php echo $row_card_genre['card_label'];?></li>
<?php }
$row_card_genre = mysqli_data_seek($get_card_genre, 0);
?>
</ul>
</section>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
<p id="deletethissubmit"><input type="submit" value="Delete This"></p>
<input type="hidden" name="card_catalog_delete">
<input type="hidden" name="genre_id" value="<?php echo $row_card_catalog['label_id'];?>"
</form>
<p>You're asking this at
<?php
date_default_timezone_set('America/New_York');
echo date('g:i a T \o\n l, F j, Y');
?>
</p>
<p id="backtothemarketplace">Back To The Marketplace</p>
<?php
/*if (isset($_POST['card_genre'])) {
$query = "SELECT card_catalog.card_name, card_catalog.label_id, card_genre.genre_id, card_genre.card_label FROM card_catalog, card_genre WHERE card_genre.genre_id = ?";
$stmt = mysqli_prepare($conn, $query);
$stmt->bind_param('s', $_POST['card_genre']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['card_name']." - ".$row['label_id'];
echo "<br />";
}
}*/
?>
</main>
<?php include('templatestuff2/bottom_of_tmp2.php'); ?>
</body>
</html>
If anybody has any help or constructive criticism, it would be greatly appreciated (I'm a PHP/SQL newbie so I'll take all the help that I can get).
Thanks
Messed around with the code and I fixed it. The id is now being displayed and it links to the correct page.
All that was wrong with my code was that I mixed up some of the variables and ids.
Thank you all for your help.
I have a form on one page linking to a PHP file (action), now the PHP result is being displayed in this PHP file/page. But I want the result to be displayed on the page with the form. I have searched thoroughly and couldn't find it anywhere. Perhaps any of you can help?
Code: /citizens.php (main page)
<form method="post" action="/infoct.php">
<input type="text" name="ID" placeholder="ID">
<input name="set" type="submit">
</form>
Code: /infoct.php
<!DOCTYPE html>
<html>
<head>
<!-- <meta http-equiv="refresh" content="0; url=/citizens.php" /> -->
</head>
<body>
<?php {
$ID2 = isset($_POST['ID']) ? $_POST['ID'] : false;
}
$connect = mysql_connect('localhost', 'root', 'passwd');
mysql_select_db ('inhabitants');
$sql = "SELECT `Name`, `Surname`, `DOB`, `RPS`, `Address` FROM `citizens` WHERE ID = $ID2";
$res = mysql_query($sql);
echo "<P1><b>Citizen Identification number is</b> $ID2 </p1>";
while($row = mysql_fetch_array($res))
{
echo "<br><p1><b>First Name: </b></b>", $row['Name'], "</p1>";
echo "<br><p1><b>Surname: </b></b></b>", $row['Surname'], "</p1>";
echo "<br><p1><b>Date of birth: </b></b></b></b>", $row['DOB'], "</p1>";
echo "<br><p1><b>Address: </b></b></b></b></b>", $row['Address'], "</p1>";
echo "<br><p1><b>Background information: </b><br>", $row['RPS'], "</p1>";
}
mysql_close ($connect);
?>
</body>
</html>
My fixed code thanks to Marc B
<form method="post">
<input type="text" name="ID" placeholder="ID">
<input name="set" type="submit">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$ID = isset($_POST['ID']) ? $_POST['ID'] : false;
$connect = mysql_connect('fdb13.biz.nf:3306', '1858208_inhabit', '12345demien12345');
mysql_select_db ('1858208_inhabit');
$sql = "SELECT `Name`, `Surname`, `DOB`, `RPS`, `Address` FROM `citizens` WHERE ID = $ID";
$res = mysql_query($sql);
if ($ID > 0) {
echo "<p><b>Citizen Identification number is</b> </p>";
while($row = mysql_fetch_array($res))
echo "<br><p><b>Surname: </b></b></b>", $row['Surname'], "</p>";
echo "<br><p><b>First Name: </b></b>", $row['Name'], "</p>";
echo "<br><p><b>Date of birth: </b></b></b></b>", $row['DOB'], "</p>";
echo "<br><p><b>Address: </b></b></b></b></b>", $row['Address'], "</p>";
echo "<br><p><b>Background information: </b><br>", $row['RPS'], "</p>";
mysql_close ($connect);
}
else {
echo "<p>Enter a citizen ID above</p>";
}
}
?>
DB Snap
A single-page form+submit handler is pretty basic:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... form was submitted, process it ...
... display results ...
... whatever else ...
}
?>
<html>
<body>
<form method="post"> ... </form>
</body>
</html>
That's really all there is.
Use code on the same page (citizens.php)
<?php
if (isset($_POST)) {
Do manipulation
}
?>
Else use ajax and remove action method from form.
<form method="post" id="contactForm">
<input type="text" name="ID" placeholder="ID">
<input name="set" type="buttom" id="submitId">
</form>
<script>
$("#submitId").click(function(){
var Serialized = $("#contactForm").serialize();
$.ajax({
type: "POST",
url: "infoct.php",
data: Serialized,
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function(){
alert('error handing here');
}
});
});
</script>
And in your infact.php in the end Echo the data so that ajax will have the data in return.
You could just put everything in infoct.php, like this:
<!DOCTYPE html>
<html>
<head>
<!-- <meta http-equiv="refresh" content="0; url=/infoct.php" /> -->
</head>
<body>
<form method="post" action="/infoct.php">
<input type="text" name="ID" placeholder="ID" value="<?php isset($_POST['ID']) ? $_POST['ID'] : '' ?>">
<input name="set" type="submit">
</form>
<?php
if (isset($_POST['ID'])) {
$ID2 = $_POST['ID']; // DO NOT FORGET ABOUT STRING SANITIZATION
$connect = mysql_connect('localhost', 'root', 'usbw');
mysql_select_db ('inhabitants');
$sql = "SELECT `Name`, `Surname`, `DOB`, `RPS`, `Address` FROM `citizens` WHERE ID = $ID2";
$res = mysql_query($sql);
echo "<P1><b>Citizen Identification number is</b> $ID2 </p1>";
while($row = mysql_fetch_array($res))
{
echo "<br><p1><b>First Name: </b></b>", $row['Name'], "</p1>";
echo "<br><p1><b>Surname: </b></b></b>", $row['Surname'], "</p1>";
echo "<br><p1><b>Date of birth: </b></b></b></b>", $row['DOB'], "</p1>";
echo "<br><p1><b>Address: </b></b></b></b></b>", $row['Address'], "</p1>";
echo "<br><p1><b>Background information: </b><br>", $row['RPS'], "</p1>";
}
mysql_close ($connect);
}
?>
</body>
</html>
Do not forget about string sanitization !
I have found the solutions to the folowing problems:
Display results on same page
Thanks to Marc B
A single-page form+submit handler is pretty basic:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... form was submitted, process it ...
... display results ...
... whatever else ...
}
?>
<html>
<body>
<form method="post"> ... </form>
</body>
</html>
That's really all there is.
Only first value is showing
I resolved this problem by adding this to my code:
while($row = mysql_fetch_array($res)) {
$surname=$row['Surname'];
$name=$row['Name'];
$dob=$row['DOB'];
$address=$row['Address'];
$RPS=$row['RPS'];
Now all the values are being displayed instead of only the first one.
Display results on same page
Well I've stumbled upon this with the same problem
and I found out you can simply require the other file.
include_once("PATH_TO_FILE")'.
in /citizens.php
<?php include_once="infoct.php" ?>
<form> ... </form>
<div>
<?php $yourdata ?>
</div>
$yourdata should be html.
Do not forget about string sanitization !
Make sure to remove action from the form
Better than having all logic and Html in one file.
I am just building a simple search page in PHP. I need to know how can i keep the selecte value of the drop down list upon form submission. Currently, the value resets to the first index.
Can I do this via PHP without using client-side script?
Here is the code:
<?php
mysql_connect('localhost','root','');
mysql_select_db('hotel');
$sql = "SELECT * FROM customers";
$result = mysql_query($sql);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form method="get">
<select name="field" id="field">
<?php
/*if($field == 'Active')
'selected="selected"';
*/
while($rows = mysql_fetch_array($result))
echo '<option>'.$rows['customer_id'].'</option><br>';
?>
</select>
<?php
if (isset($_GET['Search']) && $_GET['action']=='search')
{
$sql="SELECT * FROM customers WHERE customer_id=".$_GET['field'];
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
echo '<br>Customer Name: '.$row['customer_name'].'<br>';
echo 'Email Address: '.$row['Email_Addr'].'<br>';
echo 'Contact No: '.$row['Contact_No'].'<br>';
}
?>
<input type="hidden" name="action" value="search" />
<br><input type="submit" value="search" name="Search" onclick="" />
</form>
</body>
</html>
usually like this.
echo '<option';
if ($_GET['field'] == $rows['customer_id']) echo " selected";
echo '>'.$rows['customer_id'].'</option>';
And please don't use the mysql_* functions to write new code, especially when you are learning. The mysql_* functions are in the process of becoming deprecated, they will be removed in future versions of PHP. Use mysqli_* or PDO objects instead.
You can check if the get value is the same than the select value :
while($rows = mysql_fetch_array($result))
echo '<option value="'.$rows['customer_id'].'" '.($rows['customer_id'] == $_GET['field']?'selected="selected"':'').'>'.$rows['customer_id'].'</option><br>';
When printing the select options, you can check for the value and set any mathing option to selected, maybe like this:
while($rows = mysql_fetch_array($result)){
if(!empty($_GET['field']) && $_GET['field'] == $rows['customer_id']){
echo '<option selected="selected">'.$rows['customer_id'].'</option><br>';
}
else {
echo '<option>'.$rows['customer_id'].'</option><br>';
}
}