How can I create a submit button that allow multiple action? In this case I would like the button to add new data and print the new data using one single submit button.
However, after added onclick="printContent('div1')" on my submit button, the INSERT query does not work. Thus, it will print old latest info because no new data was added.
index.php:
<html>
<?php
// Turn off all error reporting
error_reporting(0);
include 'dbconnect.php';
?>
<head>
<script>
// script to print partial information only
function printContent(el){
var restorepage = document.body.innerHTML;
var printcontent = document.getElementById(el).innerHTML;
document.body.innerHTML = printcontent;
window.print();
document.body.innerHTML = restorepage;
}
</script>
</head>
<body>
<form method="POST" action="">
<button name="submit" type="submit" id="printStuff" class="btn v-btn no-three-d" onclick="printContent('div1')">PRINT!</button>
</form>
<?php
if(isset($_POST["submit"])){
$sql2 = "INSERT INTO Q_postitem (service_ID, created_time, queue_No)
SELECT 1, CONVERT_TZ(CURRENT_TIMESTAMP,'+00:00','+8:00'), max(queue_No)+1 FROM Q_postitem WHERE service_ID=1";
if (mysqli_query($con, $sql2)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql2 . "" . mysqli_error($con);
}
echo "<br>".$sql2;
mysqli_close($con);
}
?>
<div id="div1" style="display: none;">
//ECHO NEW ADDED DATA HERE TO PRINT
</div>
</body>
</html>
Related
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; ?>
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.
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 have a form in html:
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
and I want to get the value of this input in php without submitting it in a form.
this is my javascript:
var pName= null;
$(document).ready(function(){
$('img').click(function(){
pName= $(this).attr("name");
console.log(pName);
});
});
My php:
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
what I want is. you click on the picture,
1.the value of the name attribute of the picture is going to be saved into the variable pName (javascript),
2.it then goes into the form and changes the value of the form to the variable pName (javascript),
3.php picks up the value of the form (which should now be equal to pName),
4.then stores it into a variable $pName (php).
5.I also want $pName (php) to be globally used throughout all the pages of the website.
edit
this is my index page:
<?php
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
$query="SELECT * FROM project limit 5 ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="ppo.js"></script>
<link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="bgNav">
<div id="login">
Register
Log in
</div>
<nav id="nav">
Home
</nav>
</div>
<h2 class="titlePage">Home</h2>
<div id="bgTile">
<?php
while($row = mysqli_fetch_array($results))
{
$project = $row["name"];
echo nl2br("<a href='project.php'>" ."<img name=\"$project\" width='100px' alt='Procject name' height='100px' class='tile' src=". $row['image'] ."/>". "</a>");
}
?>
<div class="tile" id="tileM"><h2>Meer</h2></div>
</div>
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
</body>
</html>
what I want: click on the image then you get sent to the project page where (php) $pName is equal to the value of (javascript) pName
project page:
<?php
$newRecord = null;
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
//insert into database
if(isset($_POST['insertComments'])){
include('connect-mysql.php');
$username = $_POST['username'];
$comment = $_POST['comment'];
$sqlinsert = "INSERT INTO user_comments (username, comment, project) VALUES ('$username', '$comment', '$pName')";
if (!mysqli_query($db_connection, $sqlinsert)){
die('error inserting new record');
}
else{
$newRecord = "1 record added";
}//end nested statement
}
//text from database
$query="SELECT * FROM user_comments where project = '$pName' ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
$query2="SELECT * FROM project where name = '$pName' ";
$results2 = mysqli_query($db_connection,$query2);
$intro2=mysqli_fetch_assoc($results2);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="ppo.js"></script>
<link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="intro">
</div>
<div id="bgNav">
<nav id="nav">
Home
<a class="rightNav" href="register.php">Register</a>
<a class="rightNav" href="login.php">Log in</a>
</nav>
</div>
<div id="projectTile">
<span id="statusCheck"><?php print_r($intro2["status"]); ?></span>
<h2 id="prTitle"><?php print_r($intro2["name"]); ?></h2>
<div id="prPic"><img width="300" height="200" src="<?php print_r($intro2["image"]); ?>"></div>
<div id="prDescription"><?php print_r($intro2["description"]); ?></div>
</div>
<div id="comments">
<?php
while($row = mysqli_fetch_array($results))
{
echo nl2br("<div class='profile_comments'>" . $row['username'] . "</div>");
echo nl2br("<div class='comment_comments'>" . $row['comment'] . "</div>");
}
?>
</div>
<div id="uploadComments">
<form method="post" action="project.php">
<label for="name"><input type="hidden" name="insertComments" value="true"></label>
<fieldset>
<legend>comment</legend>
<label>Name:<input type="text" id="name" name="username" value=""></label><br/>
<label>Comments: <textarea name="comment" id="comment"></textarea></label>
<input type="submit" value="Submit" id="submitComment">
</fieldset>
</form>
</div>
<?php
echo $newRecord;
?>
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
</body>
</html>
HTML:
do you have more then 1 image on page? its better if you add ID in image. No need for form and hidden fields for what you want done.
make sure your img has ID like <img id="imageID"...
JavaScript:
var pName= null;
$(document).ready(function(){
$('#imageID').click(function(){
pName= $(this).attr("name");
$.post("project.php", { pNameChange: pName },
function(data) {
// do something here.
});
});
});
above code should work as expected. Now in project.php > $_POST['pNameChange'] should receive the value of pName (image's name attr).
I don't understand what you want when you said $pName available globally on all pages. Please elaborate further, may be look into storing it as cookie/session?
EDIT:
Consider using session to pName value... by simple starting/resuming session in start of file:
<?PHP
session_start();
and then...
to set/update value:
if(isset($_POST["pNameChange"]))
$_SESSION["pName"] = $_POST["pNameChange"];
and then use $_SESSION["pName"] instead of $pName on all pages.
Try Ajax method in jQuery , hope it solves your problem
https://api.jquery.com/jQuery.ajax/
or
https://api.jquery.com/jQuery.post/
Actually, you do not need AJAX for this, all your index.php does it passes the image's name to project.php so try:
In index.php:
<form name='form1' method="post" action='project.php'> <!-- form attributes given -->
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
Javascript:
var pName= null;
$(document).ready(function(){
$('img').click(function(){
//onclick of image, we will save the image name into the hidden input
//and submit the form so that it goes to project.php
$('input[name="pNameChange"]').val($(this).attr("name"));
$('form1').submit()
});
});
And in your project.php:
//now project.php can get the posted value of 'pNameChange'
//There is no input field with `name`->`value`, so $_POST['value'] is invalid.
$pName = isset($_POST['pNameChange']) ? $_POST['pNameChange'] : '';
And if you need this value across multiple pages, global will not work, use sessions.
ok this "additional" answer is to focus on session only. use the codes for client-end from my previous answer and try this on server-end.
index.php Page:
<?php
session_start();
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : '';
project.php Page:
<?php
session_start();
$newRecord = null;
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : null;
if(is_null($pName) && isset($_POST['pNameChange'])) {
$_SESSION['pNameChange'] = $_POST['pNameChange'];
$pName = $_POST['pNameChange'];
}
hope it helps
my search result does not show on the same window, i would want the result to be displayed on the same window. i have found the same question but the code is different from what I'm using so i cant relate to it: Search wont show on same page
scenario 1:
if I put in the action="search_result2.php" - it will redirect the result on the other page
scenario 2:
if i used action="" in this code below, its not doing anything
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
$(document).ready(function(){
$("#results").show();
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#search").on('click',function() {
var find = $('#find').val();
var field = $('#field').val();
$.post('search_result2.php',{find:find, field:field}, function(data){
$("#results").html(data);
});
return false;
});
});
</script>
</head>
<body>
<div id="container" style="width:auto">
<div id="mainContent">
<h2>Search</h2>
<form name="search" method="post" action="">
Seach for: <input type="text" name="find" id="find" /> in
<Select NAME="field" id="field">
<Option VALUE="testA">A</option>
<Option VALUE="testB">B</option>
<Option VALUE="testC">C</option>
<Option VALUE="testD">D</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" id="search" value="Search" />
</form>
<div id="results">
</div>
</div>
</div>
</body>
</html>
here is my search_result2.php:
<?php
//This is only displayed if they have submitted the form
if (isset($_POST['searching']) && $_POST['searching'] == "yes")
{
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if (empty($_POST['find']))
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("host", "username", "passw") or die(mysql_error());
mysql_select_db("testdb") or die(mysql_error());
// We preform a bit of filtering
$find = strtoupper($_POST['find']);
$find = strip_tags($_POST['find']);
$find = trim ($_POST['find']);
$field = trim ($_POST['field']);
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM testtable WHERE upper($field) LIKE'%$find%'");
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo $result['testA'];
echo " ";
echo $result['testB'];
echo "<br>";
echo $result['testC'];
echo "<br>";
echo $result['testD'];
echo "<br>";
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
If you want to load in the same page, without refreshing the page, you'll need to make an ajax request.
If you can reload the page, the php part must be in the same "location" as your original link.
For example if you put that code on the top of the same file with the form (and rename it with a .php extension), it should work (if the php can interpret in that folder).