My assignment is to create two tables in phpMyAdmin, and then to create a simple form where the user can click a button and have the two tables displayed. I have the landing page for the assignment finished with header and search bar and button, but I'm having trouble figuring out how to bring the two tables in from the database and display them once the button is clicked.
I have had a tutor help with some of the code but I haven't been able to get it to work properly and would love any further help.
Here is the code I have now (the two separate php code chunks are two ways people tried to help me do it but I don't know which works or how to implement it):
<!DOCTYPE html>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {die("Connection Failed: " . $conn->connect_error);
}
echo "Connected Successfully";
?>
<html>
<head>
</head>
<body>
<h1>Health Club Patron and Class Information</h1>
<form name="contact-form" action="" method="post" id="contact-form">
<div class="form-group">
<label for="Search">Search</label>
<input type="text" class="form-control" search="your_name" placeholder="Search" required>
</div>
<button type="print" class="btn btn-primary" name="print" value="Print" id="submit_form">Print</button>
</form>
</body>
</html>
$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('hrmwaitrose');
$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
Try looking at examples on this website, good example's taken from W3 schools to learn with some simple examples.
https://www.w3schools.com/php/php_mysql_select.asp
And a form handling example in PHP https://www.w3schools.com/php/php_forms.asp
You setup a php file such as post.php then your form will post to that endpoint. Or if you are posting a PHP form to itself you use <?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> for the post address in the form. When learning, try taking these simpler like the example's below than building from that, so you get the basic idea.
Here's a few examples, this one just grabs the rows from the database.
<?php
$servername = "localhost"; // Server host
$username = "username"; // Database username
$password = "password"; // Database password
$dbname = "hrmwaitrose"; // Your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Select the rows name and age from employee
$sql = "SELECT name, age FROM employee";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo " - Name: " . $row["name"]. " " . $row["age"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Simple example post a form to PHP file a different URL, not posting to itself.
Filename: index.php
<html>
<body>
<form action="results.php" method="get">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit">
</form>
</body>
</html>
Then your results.php contains
Filename: results.php
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["age"]; ?>
</body>
</html>
This is an example using a form posting to itself, instead of the example's above which post to another file. Using $_GET["name"] you are grabbing the post variable's from the URL and then you can query your database, unless you are using _POST. If your posting directly to the same file you would do something like this, which I think your question is asking.
<?php if (!empty($_POST)): ?>
Welcome, <?php echo htmlspecialchars($_POST["name"]); ?>!<br>
Your age is <?php echo htmlspecialchars($_POST["age"]); ?>.<br>
<?php else: ?>
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit">
</form>
<?php endif; ?>
Related
I am basically building an extension that gets the url and title of the current tab and sends it to the SQL database at localhost using XAMPP.
This is my code
(popup.html)
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script src="jquery-3.3.1.min">
</script>
<script src="popup.js">
</script>
</head>
<body>
<form action="http://localhost/data.php" method="post">
<var id="lol">kk</var>
First Name: <input type="text" name="name">
<input type="Submit">
</form>
</body>
</html>
(popup.js)
chrome.tabs.getSelected(null,function(tab) {
var tablink = tab.url;
var tabtitle = tab.title;
document.getElementById("lol").textContent=tablink;
document.getElementById("card").textContent=tabtitle;
});
(data.php)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "uppercase";
// Create connection
$conn = mysqli_connect("$servername", "$username", "$password");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_select_db($conn,$database);
$sql = "INSERT INTO urltable (name,url)
VALUES
('$_POST[lol]','$_POST[card]')";
if (mysqli_query($conn, $sql)) {
echo("success");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I want the url and title of current tab to be saved in database(uppercase).
Even though I have specified the ID for title and url i.e(card and lol respectivesly). Nothing is getting entered in Database if I run my extension.
You're only sending one variable, named name, with this form.
You can send lol and card values with hidden fields like this :
<input type="hidden" id="lol" name="lol" value="" />
<input type="hidden" id="card" name="card" value="" />
Remove tag with id lol : <var id="lol">kk</var>
This way you'll be setting lol and card values and sending related variable to PHP.
My modal is not showing up after I add header(location: homepage.php) but modal is working fine if I remove the header. How can I possibly do it? I've also tried using echo for alert and same thing happens, so I don't know what is wrong with my code. I hope someone can help me thank you!. Here is my code
login.php
if(isset($_POST['submit']))
{
$email = $_POST['email'];
$password = $_POST['password'];
$object = new Login();
$object->getCredentials($email, $password);
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<div>
<label><b>EMAIL ADDRESS</b></label>
<input type="email" name="email" placeholder="Email"></input>
</div>
<div>
<label><b>PASSWORD</b></label>
<input type="password" name="password" placeholder="Password"></input>
</div>
<button type="submit" id="submit" name="submit">Login</button>
</form>
processlogin.php
<?php
include_once 'db.php';
class Login
{
public function getCredentials($email, $password)
{
$email = $email;
$password = $password;
$object = new Db();
$stmt = $object->connect()->prepare("SELECT * FROM user WHERE email=?");
$stmt->execute([$email]);
$stmtFetch = $stmt->fetch();
if($stmt->rowCount()==1 && $stmtFetch['email'] == $email && $stmtFetch['password'] == $password)
{
echo "<script>$('#loginsuccess').modal('show')</script>";
header("location: homepage.php");
}
}
}
I found something that might interest you here:
Interview Question: Can we have an echo before header?
The problem is that we cannot send the header after we start sending the output, and if you send the header before the echo, the echo will not be executed.
Try this:
Solution 1: (from the link above).
ob_start();
echo "<script>$('#loginsuccess').modal('show')</script>";
header("location: homepage.php");
ob_end_flush();
Solution 2: Use a javascript redirection instead of header function.
echo "<script>
$('#loginsuccess').modal('show');
window.location.replace('http://fullpath-homepage.php');
</script>";
Additional note:
You can use also:
window.location.href="http://example.com";
window.location.assign("http://example.com");
The replace method navigates to the URL without adding a new record to the history.
UPDATE: FOUND THE ANSWER
I use Yeti82's answer and this is what I did to make the delay to show modal of success and then directing to the next page.
echo "<script>
$('#loginsuccess').modal('show');
setTimeout(function() {window.location.href=\"homepage.php\";}, 1000);
</script>";
I am fairly new at PHP HTML and found some help on this site but cannot get the code to work as part of my script
On clicking the SUBMIT button a record is posted to the database table (Transactions) but the FIELD (Code) is empty, it should contain a 3 letter uppercase string e.g. ABC
The ALERT shows that the value is stored in the variable $code but an empty string is posted to the table
Your help is greatly appreciated by this novice
<?php
// Include config file
require_once 'config.php';
// Define variables and initialize with empty values
$code = "";
$code_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Validate Code
$code = strtoupper($code);
// Check input errors before inserting in database
if(empty($code_err)){
// Prepare an insert statement
$sql = "INSERT INTO Transactions (Code)
VALUES (?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_code);
// Set parameters
$param_code = $code;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records created successfully. Redirect to landing page
$url = 'http://localhost:8888/portfolio/index.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<link href="style1.css" rel="stylesheet" type="text/css"/>
<style type="text/css">
.wrapper{
width: 450px;
margin: 0 auto;
}
</style>
<script>
function getValue(obj){
alert(obj.value);
$code=(obj.value);
**alert($code);**
}
</script>
<!--Display heading at top center of screen-->
<div>
<center><h3>Peter's Portfolio - Shares</h3></center>
</div> <!-- end of Div -->
</head>
<body style="background-color:#fcf8d9">
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-6">
<div class="page-header">
<h2>Create Transaction Record</h2>
</div>
<form class="form-horizontal" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<!-- ASX CODE -->
<div class="form-group">
<label for="name" class="control-label col-xs-6">ASX Code:</label>
<div class="col-xs-6">
<?php
$conn = new mysqli('localhost', 'root', 'root', 'Portfolio') or die ('Cannot connect to db');
$result = $conn->query("SELECT Code, Coy_Nm from Companies ORDER BY Code");
echo "<html>";
echo "<body>";
echo "<select Name='Code' ID='Code'onchange='getValue(this)'>";
while ($row = $result->fetch_assoc()) {
unset($Code, $Coy_Nm);
$Code = $row['Code'];
$Coy_Nm = $row['Coy_Nm'];
echo '<option value="'.$Code.'">'.$Coy_Nm.'</option>';
}
echo "</select>";
echo "<input type='hidden' value='submit'>";
//$code=$_POST['Code'];
//echo $code;
?>
</div>
</div>
<!--Submit and Cancel Buttons-->
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Javascript and PHP cannot simply communicate to each other live.
try this
function getValue(obj){
alert(obj);// check if obj has something in it before proceeding to "value"
alert(obj.value);
}
After require_once 'config.php',
Focus on the following line :
$code = "";
When you submit form and form action is self, this means that your post data will be sent to the same file and when the code is read from your file it makes $code empty every time. of course, an empty value will be sent to DB. move this line inside if condition or change this logic.
I started making site for songs. It is lyrics site and I wanted a search engine that works something like picture below.
It should works with URL.
<form action="#" method="POST">
<input type="text" name="search"/>
<input type="submit" name="submit" value="Submit">
</form>
<?php
require "connection-to.php";
$notFound = "";
$song = "";
if(isset($_POST['submit'])){
$search = mysqli_real_escape_string($conn, $_POST['search']);
$search = strtolower($search);
$sql = "SELECT * FROM `music` WHERE `name` = '" . $search . "'";
$query = mysqli_query($conn, $sql);
$numRows = mysqli_num_rows($query);
if($numRows != 0){
while($row = mysqli_fetch_array($query)){
echo $row['lyrics'] . "<br><br><br>";
}
} else {
echo $search . " Was Not Found.";
}
}
?>
You don't want send a POST request. Change
<form action="#" method="POST">
to
<form action="" method="GET">
Then you can retrive it with $_GET['search'] instead of $_POST['search'].
Whenever I click the submit button of my login, I'm taken to a blank page which has the texts "403 Forbidden", I feel that this may be due to the URL of my login page as it is "mywebsite.com8:8888/login/" and is hosted on a different port (I'm using Tornado web server).
HTML
<form method="POST">
<fieldset id="inputs">
<input name="username" id="username" required>
<input name="password" id="password" type="password" name="Password" placeholder="Password" required>
</fieldset>
<fieldset id="actions">
<input type="submit" id="submit" value="Log in" name="submit">
<label><input type="checkbox" checked="checked"> Keep me signed in</label>
</fieldset>
</form> <div id="container"></div>
PHP
<?php header('Access-Control-Allow-Origin: *'); ?>
<?php
if (isset($_POST['submit'])){
session_start();
error_reporting(0);
$username = $_POST['username'];
$password = md5($_POST['password']);
$connection = mysql_connect("localhost", "moot", "lmlkmklmklmkl"); // Establishing Connection with Server
$db = mysql_select_db("snamr", $connection); // Selecting Database from Server
$sql="SELECT * FROM accs WHERE name='$username' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
$check = mysql_query("SELECT active FROM accs WHERE name = '$username'");
while($rows=mysql_fetch_assoc($check)){
$active = $rows['active'];
}
// If result matched $myusername and $mypassword, table row must be 1 row
if($count!=1){
echo "Wrong Username or Password";
}
elseif ($active == 0) {
echo "Your account isn't active!";
}
else {
$_SESSION['username'] = $username;
}
$time = time();
$setLogged= mysql_query("UPDATE accs SET loginstatus = '$time' WHERE name = '$username'") or die(mysql_error());
}
}
?>
JAVASCRIPT WHICH LOADS THE PHP INTO HTML (good reasons for this)
<script type="text/javascript">
$(document).ready(function(){
$("#container").load('http://mywebsite.com/sname/signing.php');
});
</script>
The login form along with the PHP works with all other files on my default port but when I take the code to my files hosted on port 8888 things go wrong. Hence why I think the main issue may be in the domain.
Any solutions?