Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So the idea of this website is that when you press the button it deletes the corresponding row from the database. However, the issue with my code is that after the first press the button fills the id variable and then executes the php on the next press. How can I avoid this and get he php to fit and execute the php on the first press of the button?
Included is the HTML page with the php embedded:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<title>Untitled Document</title>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<div class="container-fluid">
<h2 style"text-align:center";>Please enter the item you want to add to the list below </h2>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$sql = "CREATE DATABASE myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CREATE TABLE freezerinventory (
id INT AUTO_INCREMENT PRIMARY KEY,
item VARCHAR(30) NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if(isset($_POST['itemx']))
{
$itemvar = $_POST["itemx"];
$sql = "INSERT INTO freezerinventory (item)
VALUES ('$itemvar')";
$add = mysqli_query($conn, $sql);
}
else {
$sql = "";
}
mysqli_close($conn);
?>
<form action="<?=$_SERVER['PHP_SELF'];?>" class="needs-validation" novalidate method="post">
<div class="form-group">
<label for="uname"></label>
<input type="text" class="form-control" id="itemx" placeholder="Enter an item for the freezer here" name="itemx" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<button id = "SubmitButton" name = "SubmitButton" type="button submit" class="btn btn-primary">Add to list</button>
</form>
</div>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$aVar = mysqli_connect('localhost','root','','myDB');
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM freezerinventory";
$result = mysqli_query($aVar, $sql);
echo "<table><tr>
<th>Item name</th>
<th>Date added</th>
<th>remove</th>
</tr> ";
while($row = mysqli_fetch_array($result)) {
echo " <tr><td>" . $row['item'] . "</td><td>" . $row['reg_date'] . "</td><td><form action='
' method='POST'>
<div class= 'input-group' > <div class='input-group-append'>
<button class='btn btn-danger' onclick='deleteitem()' id = 'delete' type='submit'>Remove</button>
<input type='hidden' name='id' value=".$row['id']." />
</div></div>
</form></td></tr>";
}
echo "</table>";
?>
<script>
function deleteitem (e) {
e.preventDefault();
<?php
$id = $_POST['id'];
$delete = "DELETE FROM freezerinventory WHERE id=$id";
$del = mysqli_query($conn, $delete);
?>
}
else {
}
</script>
<script>
function myFunction() {
confirm("I am an alert box!");
}
</script>
<script>
(function() {
'use strict';
window.addEventListener('load', function() {
// Get the forms we want to add validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
</body>
</html>
You can create a separate processing script and submit a form to the URL path 'onClick' of a button. You cannot directly call PHP function with JS code.
PHP is a language that runs only on server-side.
It is different to javascript that runs on client-side (on the browser).
If you may notice, you will never see PHP code on other websites, because (if the website uses PHP) it is processed on the server side and the return is HTML+CSS only.
Nowaday we would not create a page like this.
We would create what we call API using PHP. We would use REST-API strategy.
Let's say we would host this API on this address www.mywebsite.com/myapi/myfreezerendoint.php
And we would use JS to request or post to this endpoint with simple javascript function called fetch("www.mywebsite.com/myapi/myfreezerendoint.php", { ... }).
I found this interesting tutorial about PHP API with MySQL as database: https://webdamn.com/create-simple-rest-api-with-php-mysql/
I hope you enjoy! Keep it up
I've corrected and beautified all of the code, minimized it and this should now be it:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$sql = "CREATE DATABASE myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CREATE TABLE freezerinventory (
id INT AUTO_INCREMENT PRIMARY KEY,
item VARCHAR(30) NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)";
if(isset($_POST['itemx'])) {
$itemvar = $_POST["itemx"];
$stmt = $conn->prepare("INSERT INTO freezerinventory (item) VALUES ('?')");
$stmt->bind_param("s", $itemvar);
$stmt->execute();
} else {
//the 'itemx' post parameter isn't set, make an alert or something
}
mysqli_close($conn);
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<title>Untitled Document</title>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<div class="container-fluid">
<h2 style"text-align:center";>Please enter the item you want to add to the list below </h2>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" class="needs-validation" novalidate method="post">
<div class="form-group">
<label for="uname"></label>
<input type="text" class="form-control" id="itemx" placeholder="Enter an item for the freezer here" name="itemx" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<button id = "SubmitButton" name = "SubmitButton" type="button submit" class="btn btn-primary">Add to list</button>
</form>
</div>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$aVar = mysqli_connect('localhost','root','','myDB');
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['id'])) {
$delete = $con->prepare("DELETE FROM freezerinventory WHERE id= ?");
$delete->bind_param("s", $_POST['id']);
$delete->execute();
}
$sql = "SELECT * FROM freezerinventory";
$result = mysqli_query($aVar, $sql);
echo "<table><tr>
<th>Item name</th>
<th>Date added</th>
<th>remove</th>
</tr> ";
while($row = mysqli_fetch_array($result)) {
echo " <tr><td>" . $row['item'] . "</td><td>" . $row['reg_date'] . "</td><td><form action='' method='POST'>
<div class= 'input-group' > <div class='input-group-append'>
<button class='btn btn-danger' onclick='deleteitem(".$row['id'].")' id='delete'>Remove</button>
<input type='hidden' name='id'/>
</div></div>
</form></td></tr>";
}
echo "</table>";
?>
<script>
function deleteitem (id_data) {
$.post('<?php echo $_SERVER["PHP_SELF"];?>', {id: id_data}, function(data) {
console.log(data); //callback data
});
}
function myFunction() {
confirm("I am an alert box!");
}
(function() {
'use strict';
window.addEventListener('load', function() {
// Get the forms we want to add validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
</body>
</html>
It might still need some fixes and I left some unused html elements in there but in theory this should work. It makes use of ajax to send the data to php. You don't have to use ajax but this should in theory solve your problem. If you run into any issues just comment under my answer.
NOTE: Just to clarify, I didn't try this therefore there might be some errors in there.
Related
Basically I want to send the same message to several recipients and I want it to register with a checkbox if the email was sent to that user or unchecked if it wasn't(The user has to check the checkbox so it registers) and I can't find a way so when a user checks a checkbox it gets updated in the database. I've tried with Ajax but I've no idea how to properly use it. I need some serious help.
My index.php
<?php
include_once 'dbh.php';
include_once 'contact.php';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/reset.css">
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<br>
<div class="tabela">
<table class="scroll">
<thead>
<tr>
<th>                        
                            
          Nome da Escola                 
                           
          </th>
<th>              Email Geral da Escola         
        </th>
<th>   Enviado</th>
</tr>
</thead>
<tbody>
<?php
$execItems = $conn->query("SELECT Nome,EmailGeral,Enviado FROM escolas");
while($infoItems = $execItems->fetch_array()){
echo "
<tr>
<td>".$infoItems['Nome']."</td>
<td>".$infoItems['EmailGeral']."</td>
<td><input type=\"checkbox\"".($infoItems['Enviado']?' checked':'checked')."\" /></td>
</tr>
";
}
?>
</tbody>
</table>
<div class="mail">
<form action="" method="post">
<button class="butao" type="button" onclick="emailNext();">Adicionar Email</button>
<div id="addEmail"></div>
<script>
function emailNext() {
var nextEmail, inside_where;
nextEmail = document.createElement('input');
nextEmail.type = 'text';
nextEmail.name = 'email[]';
nextEmail.className = 'insemail';
nextEmail.style.display = 'inline-block';
nextEmail.placeholder = 'Insira o Email';
inside_where = document.getElementById('addEmail');
inside_where.appendChild(nextEmail);
return false;
}
</script>
Assunto:<br><textarea rows="1" name="subject" cols="30"></textarea><br>
Mensagem:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input class="butao" type="submit" name="submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
Here's the connection to the database that I've created:
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "escoladb";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
if (mysqli_connect_errno())
{
echo "can't connect to MySQL: " . mysqli_connect_error();
}
?>
And finally the contact so I can send emails to the schools that I want:
<?php
if(isset($_POST['submit'])){
$to = implode(',', $_POST['email']);;
$from = "g.afonso.escola#gmail.com";
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "<div style=\"font-size:25px;background-color:white;text-align:center;\"> Email Enviado </div>";
}
?>
What I'm trying to do is, SELECT * customers from a database, insert them into a dropdown menu, and when I choose a customer from that particular dropdown menu, his other data is outputted, like mobile number and email.
This is my code:
PS. Sorry about all the "echo", I had it crash on me a couple of times, I'm new to PHP
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" />
</head>
<body>
<?php $servername="localhost" ; $username="admin_default" ; $password="_" ; $dbname="admin_default" ; // Create connection $conn=n ew mysqli($servername, $username, $password, $dbname); ?>
<div class="container">
<div class="row">
<h2>Choose a customer</h2>
<hr/>
</div>
<div class="row-fluid">
<select class="selectpicker" data-show-subtext="true" data-live-search="true">
<?php // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully
<br>"; $sql = "SELECT * FROM customers"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "
<option onclick='loadData(";
echo $row[' id '];
echo ");'>"; echo $row['company_name']; echo "</option>"; } } else { echo '
<option>No customers found</option>'; } $conn->close(); ?>
</select>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>
<script type="text/javascript">
function loadData(d) {
console.log(d);
}
</script>
</body>
</html>
Try this
$query=Select * from customers
...
while($row=mysqli_fetch_array($res)){
echo "<option value="'.$row['data_id'].'">".$row['data']."</option>";
}
And your js
dropdown.on(change, function(){
Get the value of the dropdown and use it for your query to display data.
});
I am very new to php just today itself I have started learning it, I am doing a simple program from of selecting a row from mysql's database based on user input on html through php file . and my concern is when I submit the form , it redirects to to the php and the output is displayed on the php, how can I display the result on the HTML page itself I mean the user shouldn't feel there is any transition from html to php any we get the output on the html page
HTML page :
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form action="index.php" method="get">
Enter Name : <input type="text" id="txt1" name="user">
<input type="submit" name="enter">
</form>
</body>
php page :
<?php
$dbhost = "localhost";
$username = "root";
$password = "";
mysql_connect($dbhost,$username,$password);
#mysql_select_db("trynew") or die(mysql_error());
if (isset($_GET["user"])) {
$user = $_GET['user'];
}
$query = "SELECT * FROM trynewtable where name = '$user' ";
$result = mysql_query($query);
if($result==FALSE)
{
die(mysql_error());
}
$row = mysql_fetch_array($result);
echo $row[0];
echo $row[1];
echo $row[2];
echo $row[3];
mysql_close();
?>
On the user side theres no difference between html and php, php files are also html in the view of the browser. The only difference is that php files are interpreted by the server ,while html is just send. So you can put your html in your php and mix it all together:
index.php:
<body>
<div id="response">
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
//do your request
}else{
echo "please fill in the form";
}
?>
</div>
//your form etc
Simple answer You can merge the HTML and PHP files unless there is a need to separate them (if so use AJAX). Do a validation before any database interaction. Do not use mysql but mysqli_
<?php
$dbhost = "localhost";
$username = "root";
$password = "";
$col1 = $col2=$col3=$col4="";
mysql_connect($dbhost,$username,$password);
#mysql_select_db("trynew") or die(mysql_error());
if (isset($_GET["user"])) {
$user = $_GET['user'];
$query = "SELECT * FROM trynewtable where name = '".mysql_real_escape_string($user)."' ";
$result = mysql_query($query);
if($result==FALSE) {
die(mysql_error());
}
$row = mysql_fetch_array($result);
$col1 = $row[0];
$col2 = $row[1];
$col3 = $row[2];
$col4 = $row[3];
}
mysql_close();
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php echo $col1." ".$col2." ".$col3." ".$col4;?>
<form action="" method="get">
Enter Name : <input type="text" id="txt1" name="user">
<input type="submit" name="enter">
</form>
</body>
I am trying to load content into a div and auto updated in every 5 seconds.
I have searched the net and tried to use everything, But nothing works at all. I tried to load the output from pauseupdate2.php to the div pauseup
pause.php is in a folder <../user/pause.php>
<?php
include('../session/session.php');
include('../funktion/sitelocteam.php');
include('../funktion/pausecheck.php');
include('../funktion/pausetime.php');
//include('../funktion/pauseupdate.php');
include('../funktion/pauseupdate1.php');
include('../funktion/counter.php');
//include('../funktion/pauserules.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Pause Program</title>
<link href="../style/style.css" rel="stylesheet" type="text/css">
<link href="../style/menu.css" rel="stylesheet" type="text/css">
<link rel="import" href="../funktion/pauseupdate.php">
</head>
<body>
<div id="Holder">
<div id="Header"></div>
<div id="NavBar"><nav>
<ul>
<li>Pause</li>
<li>Profil
<ul>
<li>Min Pauseoversigt </li>
</ul>
</li>
<li>FAQ</li>
<li>Logout</li>
</ul>
</nav>
</div>
<div id="PageHeading">
<!-- <h3> Bruger ID: <?php echo $userid; ?></h3>-->
<h3> Intialer: <?php echo $_SESSION['login_user']; ?> </h3>
<h3> Team: <?php echo $teamname ?></h3>
<h3> Lokation: <?php echo $sitename ?></h3>
</div>
<div id="pausev">
<?php
if ($pausetime->num_rows > 0) {
// output data of each row
while($row = $pausetime->fetch_assoc()) {
echo "Du har holdt pause siden: " . $row["time"]. "<br>";
}
}
?>
<div id="pauseup"></div>
<script src="../js/jquery-1.11.3.min.js"></script>
<script src="../js/pause.js"></script>
</div>
<div id="Pause">
<!-- <?php
echo $errors;
?> <br> <br>-->
<form action="../funktion/pauserules.php">
<input type="submit" value="PAUSE!"<?php if ($pausetjek->num_rows > 0 ){?> disabled <?php }?> >
</form>
<form action="../funktion/pausestop.php">
<input type="submit" value="STOP!" <?php if ($pausetjek->num_rows === 0){?> disabled <?php }?> >
</form>
</div>
<div id="Footer"></div>
</div>
</body>
</html>
The pause.js looks like this:
$(document).ready(function()
{
// Load the content of "path/to/script.php" into an element with ID "#container".
$('#pauseup').load('../funktion/pauseupdate2.php');
// Execute every 5 seconds
window.setInterval(refreshData, 5000);
}
);
And last but least pauseupdate2.php looks like:
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "pause";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select user.username from pause LEFT OUTER JOIN user on pause.userid=user.id where pause.type=0";
$pauseupdate = $conn->query($sql);
if ($pauseupdate->num_rows > 0) {
// output data of each row
while($row = $pauseupdate->fetch_assoc()) {
echo "Hvem er til pause: " . $row["username"]. "<br>";
// print '<table>
// <tr>
// <td>'.$row['username'].'</td>
// </tr>
// </table>';
}
} else {
echo "Ingen er til pause!";
}
$conn->close();
echo 'booo';
?>
What may be wrong with my code?
I know the most of it may be bad coded, and I am new to PHP and Jquery.
Thanks in advance
You are calling a function "refreshData" but it is not defined.
Define the function, call it the first time from the $(document.ready() method, and add setInterval at the same time:
function refreshData(){
$('#pauseup').load('../funktion/pauseupdate2.php');
}
$(document).ready(function()
{
// Execute every 5 seconds
window.setInterval(refreshData, 5000);
refreshData();
});
I think the problem could come from this refreshData function that does not seem to exist...
Try with this code (very close to yours)
<body>
<h1>Load refresh...</h1>
<div class="content">
content that will be overwritten...
</div>
<script type="text/javascript">
setInterval(function(){
$('.content').load('my_url_to_reload_every_3_seconds.php');
}, 5000);
</script>
I
am trying to update the parameters the url can contain by giving a link
in the loaded php, but i am not able to view the link itself, i can
see the table being loaded but no the link in the loaded page, may be
something silly, but please help me. I tried in all the browsers
<!Doctype html>
<table border="1" id="table">
<p> <tr><th bgcolor="#9999FF">My repute</th>
</p>
</tr>
<?php
$c=$_GET['a'];
$d=$_GET['b'];
$tr=$_GET['j'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "repute system";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection_aborted(oid)
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name,repute FROM teacher ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if($c== $row['name'])
{
echo "<tr><td Repute: > " . $row["repute"]. "</tr></td>";
$rep=$row['repute'];
}
}
}
else {
echo "0 results";
}
$some = "<a href = 'index.php?param=$tr¶m1=$a¶m2=$b'>Click here to go back</a>";
$conn->close();
?>
</table>
<?php echo $some; ?>
</html>
You have to fix your HTML first to solve the problem. When the HTML have problems some tags may not be rendered by the browser.
This line is very messy and wrong
<p> <tr><th bgcolor="#9999FF">My repute</th>
</p>
</tr>
You can fix it like this
<tr><th bgcolor="#9999FF"><p>My repute</p></th></tr>
This line:
"<tr><td Repute: > " . $row["repute"]. "</tr></td>";
Become (fixed <tr><td>...</tr><td> in <tr><td>...</td><tr>):
"<tr><td>Repute: " . $row["repute"]. "</td></tr>";
Also you have to put your html inside body tag
<!DOCTYPE html>
<html>
<head> </head>
<body>
<!-- Add here the CODE -->
</body>
<html>