How to fetch data from mysql when press button? - php

I am trying to fetch data randomly from mysql when click button,here is my code.
<?php
$con=mysqli_connect("localhost","root","","school");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT description From task ORDER BY RAND() LIMIT 2");
echo "<p><strong>Question:</strong></p>";
while($row = mysqli_fetch_array($result))
{
echo "<p>". $row['description'] ."</p>";
}
mysqli_close($con);
?>
<input type="button" value="Get Assignment" onclick="myfunc()">
</body>
</html>
I expect the output when i'm clicking Get Assignment button it will display random question, until i will display empty box.

You should wrap your php code to isset function which will check if data is send then run else don't.
isset function check if variable is set & not null
alternatively you can call Ajax to append data on click. here
<?php
$con=mysqli_connect("localhost","root","","school");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){
$result = mysqli_query($con,"SELECT description From task ORDER BY RAND() LIMIT 2");
echo "<p><strong>Question:</strong></p>";
while($row = mysqli_fetch_array($result))
{
echo "<p>". $row['description'] ."</p>";
}
mysqli_close($con);
}
?>
<input type="button" name="submit" value="Get Assignment" onclick="myfunc()">
</body>
</html>
edit fixed my code
you need to wrap your input button to a form which will submit the form to the page itself
<form method="post" action="">
<input type="submit" name="submit" value="Get Assignment">
</form>

Related

Value not saving after form is submitted

I've created a mysql table with two columns. One is ID and other is Heading. I have a textarea on which I run UPDATE code and whenever someone submits a form its being updated in the datebase column under heading. And that works fine but I want to show the last inputted submit inside my textarea.
My code is showing the last inputted value but when I reset the page it all turns out blank and its not showing anymore. I looked out in datebase and the heading is still there so I don't know why its dissapearing from the front end.
My page:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
So for example if I type Aleksa, after submit it will get url like edit.php?heading=Aleksa&submit=Submit. And then when I delete url just to edit.php, the value is missing.
You can test the page here: https://www.easybewussterschaffen.com/admin/edit.php
This is happening, because it's always trying to insert the heading when you refresh the page. You should check to see if the request is GET or the request is POST, and only insert it if they're submitting the form.
Update your form method, specify it to POST, and specifically check the method or check for the existance of $_POST['submit'] as shown below:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
// Use one of the 2 if statements:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Trying to insert a new heading
if (isset($_POST['submit'])) { // Alternative
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="POST">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
Alternatively, if you still wish to make a GET request, you should check to make sure that the heading is set:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
if (isset($_GET['submit'])) {
$heading = mysqli_real_escape_string($link, $_GET['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="GET">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
I did it like this, is this good tho? Its working
<?php
$sql = "SELECT * FROM content";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '';
while($row = mysqli_fetch_array($result)){
echo $row['heading'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>

php: Unable to take value from the user by using submit button

This is my db : link link
<?php
$con=mysqli_connect("localhost","root","","organisation");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM org_insert");
echo "<!doctype html>
<html lang=\"en\">
<head>
<!-- Bootstrap CSS -->
<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">
<title>Hello, world!</title>
</head>
<body>
<table border='1'>
<tr>
<th>below_whom</th>
<th>name</th>
</tr>";
$row = mysqli_fetch_array($result);
#echo '<pre>'; print_r($row); echo '</pre>';
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['below_whom'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<div class="form-group">
<label for="usr">below_whom:</label>
<input type="text" name ="below_whom" id="below_whom" class="form-control">
</div>
<div class="form-group">
<label for="usr">name:</label>
<input type="text" name ="name" id="name" class="form-control">
</div>
<form method="post">
<input type="button" name="submit" id="submit" class="btn btn-primary" value="submit"/>
</form>
<?php
$con=mysqli_connect("localhost","root","","organisation");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit']))
{
if($below_whom !=''||$name !=''){
$below_whom=$_POST['below_whom'];
$name=$_POST['name'];
$query=mysqli_query("INSERT INTO org_insert VALUES ('$below_whom','$name');");
$query_run = mysqli_query($con,$query);
echo "<p>query inserted.</p>";
}else{
echo "<p>Insertion Failed.</p>";
}
}
mysqli_close($con);
echo"</body>
</html>";
?>
The text under p tag isn't getting executed, ie, the program is not going inside the if statement itself. I have rechecked the syntax, what is the problem? Is the syntax incorrect? I am pretty sure the connection with sql is correct. I have also refereed to some articles, still I am stuck here.
use post variables before if loop as shown below
if(isset($_POST['submit']))
{
$below_whom=$_POST['below_whom'];
$name=$_POST['name'];
if($below_whom !=''||$name !=''){
$query=mysqli_query("INSERT INTO org_insert VALUES ('$below_whom','$name');");
$query_run = mysqli_query($con,$query);
echo "<p>query inserted.</p>";
}else{
echo "<p>Insertion Failed.</p>";
}
}
and in HTML Code add type as submit and start form tag before div as
<form method="post" action=""> and closes after input tag
<input type="submit" name="submit" id="submit" class="btn btn-primary" value="submit"/>
One of the issues that I am able to see is that Your query should be:
$query=mysqli_query("INSERT INTO `org_insert`(`below_whom`,`name`) VALUES ('$below_whom','$name')");
Hope this helps.
Change the mysqli_fetch_array to mysqli_fetch_assoc or add a parameter too
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);

how to do search in the same page?

1) this my search form
search.html :
<form action="process.php" method="POST">
<input type="text" name="query" />
<input type="hidden" name="searching">
<input type="submit" value="Search" />
</form>
2) All of my search process is handled and will be shown on process.php.
process.php :
<?php
$connection = mysql_connect("*****","*****","*****");
if (!connection) {
die ("Please reload page. Database connection failed: " . mysql_error());
}
// Select a databse to use
$db_select = mysql_select_db("*****",$connection);
if (!$db_select) {
die("Please reload page. Database selection failed: " . mysql_error());
}
if (isset($_POST["searching"])) {
/*call search process*/
dosearch();
}
function doSearch(){
$keyword = $_POST("query");
$search = "SELECT * FROM tbl_name WHERE name LIKE '%$keyword%'";
$result = mysql_query($search) or die('query did not work');
While($result_arr = mysql_fetch_array( $result ))
{
echo $result_arr['name'];
echo " ";
echo "<br>";
echo "<br>";
}
}
?>
3)How to show the search result at page "search.html" and how to combine it into one same page?
You will have to create search.php instead of search.html.
you may try using php sessions. they are very helpful.
you can save whatever variable you want to transfer from "process.php" to "search.php" in the $_SESSION array and then use them in search.php. for example :
in process.php
<?php session_start();
$_SESSION['a']=$result_arr['name'];
?>
then in search.php
<?php session_start();
echo $_SESSION['a'];
?>

post array from checkboxes is always returning empty

i am trying to delete the email entries from check boxes in a form , but it is unable to fetch any value from 'todelete[]' array
here is the code:
<?php
$dbc= mysqli_connect('localhost','root','','customer_base')or die('Error connecting to MySQL server.');
$query = "select * from email_list";
$result= mysqli_query($dbc, $query)or die('Error querying database.');
while($row= mysqli_fetch_array($result)){
echo '<input type="checkbox" value="' .$row['id']. '"name="todelete[]" />';
echo $row['first_name'].' '.$row['last_name'].' '.$row['email'].' '.'<br />';
}
if((isset($_POST['submit']))&&(isset($_POST['todelete']))){
$output_form= false;
foreach($_POST['todelete'] as $delete_id){
$query = "delete from email_list where id = $delete_id";
mysqli_query($dbc,$query)or die('Error querying database.');
}
echo '<p>Customer entry removed</p>'.'<br />';
}elseif((isset($_POST['submit']))&&(empty($_POST['todelete']))){
echo "<p>you haven't selected any customer entry to delete!</p>";
$output_form= true;
}else {$output_form= true; }
mysqli_close($dbc);
if($output_form){
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" name="submit" value="remove" />
</form>
<?php
}
?>
now,if no checkbox is checked, it gives the message , to select the checkboxes, but even if the checkboxes are selected , it still returns the message to select the checkboxes.
So, it is never enters the loop for delete query , aka$_POST['todelete'] is always empty, but it should not. u tried to check whether the $_POST array is empty , it didn;t comeup with any thing ,
i tried to go through a lot of answers ,but it seems my query was unresolved... Need help !!
What am i doing wrong with the code ??
It seems your checkbox was outside the form tag.
just replace your code with my code below:
//check for $_POST values
if((isset($_POST['submit']))&&(isset($_POST['todelete']))){
$output_form= false;
foreach($_POST['todelete'] as $delete_id){
$query = "delete from email_list where id = $delete_id";
mysqli_query($dbc,$query)or die('Error querying database.');
}
echo '<p>Customer entry removed</p>'.'<br />';
}elseif((isset($_POST['submit']))&&(empty($_POST['todelete']))){
echo "<p>you haven't selected any customer entry to delete!</p>";
$output_form= true;
}else {
$output_form= true;
}
//check if to show form
if($output_form){ ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$dbc= mysqli_connect('localhost','root','','customer_base')or die('Error connecting to MySQL server.');
$query = "select * from email_list";
$result= mysqli_query($dbc, $query)or die('Error querying database.');
while($row= mysqli_fetch_array($result)){
echo '<input type="checkbox" value="' .$row['id']. '"name="todelete[]" />';
echo $row['first_name'].' '.$row['last_name'].' '.$row['email'].' '.'<br />';
}
mysqli_close($dbc);
?>
<input type="submit" name="submit" value="remove" />
</form>
<?php } ?>
as i can see you're using mysqli, i recommend you move on to PDO.

HTML Radiobutton form not POSTing

I have written a small HTML form and added it to the page. My goal is for it to POST the value of the Checked button to a PHP page which I have also written. The PHP page is not getting the value for some reason. I am also not getting any PHP errors. The codes are below.
form.php
<form action="http://www.zbrowntechnology.com/InsaneBrain/quiz.php" method="POST">
<font color="white" size="3">
<?php
$con = mysql_connect("HOST", "USER", "PASS");
if(!$con) {
die('Unable to connect to MySQL: '.mysql_error());
}
mysql_select_db("zach_insaneB", $con);
$result = mysql_query("SELECT Name FROM quiz");
while($row = mysql_fetch_assoc($result)) {
$qname = $row['Name'];
echo "<input type='radio' name='button1' id='$qname'>";
echo "<label for='$qname'><font color='white'/>$qname</font></label>";
}
?>
</font>
</div>
</div>
<div id="Oobj12">
<div id="Gcode234" class="dfltc">
<input type="image" src="http://www.zbrowntechnology.com/InsaneBrain/begin.png" alt="Begin" />
</form></div>
</div>
getdata.php
<?php
$data = $_POST['button1'];
echo $data;
?>
Actually, I see the problem...you don't actually have a value in the radio button. You need something like:
echo "<input type='radio' name='button1' id='$qname' value='$some_value'>";

Categories