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'];
?>
Related
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);
}
?>
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>
The Problem
Hello, I am creating a search function that will allow users to search for a specific E-Number and see whether it is derived from animals or not, basically seeing if it's vegan. I have successflly connected to the database using PHP on my website.
The Code
At the top of the page:
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=***** port=*****
dbname=**** user=**** password=*****")
or die('Could not connect: ' . pg_last_error());
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
// Performing SQL query
$query = 'SELECT vegan FROM enumbers WHERE code = searchq';
}
?>
The search bar:
<div id="tablebox">
<!-- Search bar -->
<p>Is It Vegan?</p>
<form name="form1" method="post" action="searchEnumbers.php">
<input name="search" type="text" size="30" maxlength="5" />
<input name="submit" type="submit" value="Search" />
</form>
</div>
How will I now display the 'vegan' result that has been searched? I am unsure how to print the results.
Update
The column names in the enumbers table are: 'code', 'name', 'type', and 'vegan'.
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=db.dcs.aber.ac.uk port=5432
dbname=cs399030_16_17 user=sec17 password=Liverpool2112")
or die('Could not connect: ' . pg_last_error());
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
// Performing SQL query
$pg_query = 'SELECT vegan FROM enumbers WHERE code = '.$searchq;
$result = pg_query($query);
foreach($result as $r){ //If you have multiple records or $result
echo "<p> Your ".$r->params." or ".$r['params']." here </p>"; //for instance
}
}
?>
You should have something like:
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=**** port=****
dbname=**** user=**** password=****")
or die('Could not connect: ' . pg_last_error());
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
// Performing SQL query
$query = 'SELECT vegan FROM enumbers WHERE code = '.$searchq;
// make the query with: pg_query
// $result = pg_query($query);
foreach($result as $r){ //If you have multiple records or $result
echo "<p> Your ".$r->params." or ".$r['params']." here </p>"; //for instance
}
//you could use: var_dump(pg_fetch_all($result));
}
?>
<!-- If you want to show always the form. If not, put inside the else -->
<div id="tablebox">
<!-- Search bar -->
<p>Is It Vegan?</p>
<form name="form1" method="post" action="searchEnumbers.php">
<input name="search" type="text" size="30" maxlength="5" />
<input name="submit" type="submit" value="Search" />
</form>
</div>
Note this is not the best way to do it (you could use AJAX, and differents pages in order to now refresh the page), or others ways. But this could work as the way you want.
Check official documentation from PHP: http://php.net/manual/kr/function.pg-connect.php
Hope it helps!
I do have programming experience, but new to php. I do have an issue with an example I was doing from this tutorial. I looked over it millions of times, googled, ect ect. I don't have an idea why my code isnt working.
The purpose is to basically just test inserting and deleting in sql from php, using a button for Add Record and Delete Record. The Add record button works perfectly, but delete doesnt do a thing other than reload the page. Heres the code...
<?php // sqltest.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['type']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$type = get_post('type');
$year = get_post('year');
$isbn = get_post('isbn');
if (isset($_POST['delete']) && $isbn != "")
{
echo "worked!!!!!!!!!!!!!!";
$query = "DELETE FROM classics WHERE isbn='$isbn'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows($result) > 0) echo 'user deleted';
//if (!mysql_query($query, $db_server))
//echo "DELETE failed: $query" . mysql_error();
}
else
{
echo "nooooooooooooooooooo";
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$type', '$year', '$isbn')";
if (!mysql_query($query, $db_server))
{
echo "INSERT failed: $query" . mysql_error();
}
}
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Type <input type="text" name="type" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type='submit' value='ADD RECORD' />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Type $row[2]
Year $row[3]
ISBN $row[4]
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name='isbn' value="$row[4]" />
<input type='submit' value='DELETE RECORD' />
</form>
</pre>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
I have looked over this many times, still no idea why this won't work. Is it the for loop that is making this button not work? Note, you will see echo "worked!!!"; and in the else echo "noooooooo"; that was for me to test whether the button was being tested, yet nothing prints. So maybe i missed something in the button code itself? Also, no errors are printed, and my editor (and myself) have missed the syntax error (if thats the case).
The code for the delete button is at the end, before I closed the DB.
Thanks for your help in advance.
Your problem is your first if block.
You're checking for the presence of the posted variables author title type year isbn. Whereas in your delete code the only variables sent are delete and isbn. Therefore the first if block is completely missed (including the delete code).
You need to modify your first if to be if(isset($_POST)) { // a form has been posted. Then it should work.
Another way to do it:
if(isset($_POST['delete']) && isset($_POST['isbn']) && !empty($_POST['isbn'])){
//delete code here
}
if(isset($_POST['author']) && isset($_POST['title']) && isset....){
// insert code here
}
EDIT: rewritten code:
<?php // sqltest.php
// I don't know what's in here, so I've left it
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST))
{
if (isset($_POST['delete']) && !empty($_POST['isbn']))
{
echo "Deleting";
$query = "DELETE FROM classics WHERE isbn='".mysql_real_escape_string($_POST['isbn'])."'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows($result) > 0) echo 'user deleted';
}
else
{
echo "Inserting";
$query = "INSERT INTO classics VALUES ('".mysql_real_escape_string($_POST['author'])."', '".mysql_real_escape_string($_POST['title'])."', '".mysql_real_escape_string($_POST['type'])."', '".mysql_real_escape_string($_POST['year'])."', '".mysql_real_escape_string($_POST['isbn'])."')";
if (!mysql_query($query))
{
echo "INSERT failed: $query" . mysql_error();
}
}
}
// you don't need echo's here... just html
?>
<form action="sqltest.php" method="post">
<pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Type <input type="text" name="type" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type='submit' value='ADD RECORD' />
</pre>
</form>
<?php
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
// a better way to do this:
while($row = mysql_fetch_array($result)){
?>
<pre>
Author <?php echo $row[0]; ?>
Title <?php echo $row[1]; ?>
Type <?php echo $row[2]; ?>
Year <?php echo $row[3]; ?>
ISBN <?php echo $row[4]; ?>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name='isbn' value="<?php echo $row[4]; ?>" />
<input type='submit' value='DELETE RECORD' />
</form>
</pre>
<?php
}
mysql_close($db_server);
?>
Verify the method you used in your form. Make sure it's POST like this:
Form action="yourpage.php" method="POST"
and in your code above, replace the following:
$author = get_post('author');
$title = get_post('title');
$type = get_post('type');
$year = get_post('year');
$isbn = get_post('isbn');
with
$author = $_POST['author'];
$title = $_POST['title'];
$type = $_POST['type'];
$year = $_POST['year'];
$isbn = $_POST['isbn'];
Finally, there is no need to check again if the $isbn is not null as you did it in your isset() method. So remove $isbn!="" in the if below:
if (isset($_POST['delete']) && $isbn != "")
{
}
becomes:
if (isset($_POST['delete']))
{
}
Since you are testing, checking if the user clicked the delete button is of less importance. So you can also remove it for a while and add it later because you are sure that, that code is accessible after clicking the delete button.
You have no form field named delete, so it is impossible for your delete code path to ever be taken.
I'm guessing you're tryign to use the value of the submit button to decide what to do? In that case, you're also missing a name attribute on the submit button - without that, it cannot submit any value with the form. You probably want:
<input type="submit" name="submit" value="DELETE RECORD" />
and then have
if (isset($_POST['submit']) && ($_POST['submit'] == 'DELETE RECORD')) {
...
}
I'm working on a basic web form (using PHP and smarty templates) that allows users to add and delete data from a mysql database table. The data and form display fine, but nothing happens when a user tries to add or delete records from the table(not even the "cannot delete/add record' error message displays). Here is what the code looks like:
<?php //smartytest.php
$path =$_SERVER['DOCUMENT_ROOT'];
require "$path/Smarty/Smarty.class.php";
$smarty = new Smarty();
$smarty->template_dir = "$path/temp/smarty/templates";
$smarty->compile_dir= "$path/temp/smarty/templates_c";
$smarty->cache_dir="$path/temp/smarty/cache";
$smarty->config_dir="$path/temp/smarty/configs";
require_once ("$path/phptest/login.php");
$db_server=mysql_connect($db_hostname, $db_username, $db_password);
if(!$db_server) die('unable to connect to MySQL: '. mysql_error());
mysql_select_db($db_database) or die("unable to select database: " . mysql_error());
if(isset($_POST['author'])&&
isset($_POST['title'])&&
isset($_POST['category'])&&
isset($_POST['year'])&&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$category=get_post('category');
$year = get_post('year');
$isbn =get_post('isbn');
if (isset($_POST['delete']) && $isbn !='')
{
$query= "DELETE FROM classics WHERE isbn='$isbn'";
if (!mysql_query($query))
{
echo "DELETE failed: $query<br>". mysql_error() . "<p>";
}
}
else
{
$query = "INSERT INTO classics VALUES" . "('$author','$title', '$category', '$year', '$isbn')";
if (!mysql_query($query))
{
echo "INSERT failed: $query<br>" . mysql_error() . "<p>";
}
}
}
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: ". mysql_error());
$rows = mysql_num_rows($result);
for ($j=0; $j < $rows; ++$j)
{
$results[] = mysql_fetch_array($result);
}
mysql_close($db_server);
$smarty->assign('results', $results);
$smarty->display("smartytest.tpl");
function get_post($var)
{
return mysql_escape_string($_POST[$var]);
}
?>
Also, here is the Smarty template file:
<html><head>
<title>Smarty Test</title>
</head><body>
<form action="/phptest/smartytest.php" method="post"><pre>
Author <input type="text" name="author">
Title<input type="text" name="title">
Category<input type="text" name="category">
Year<input type="text" name="year">
ISBN<input type="text" name="isbn">
<input type="submit" value="ADD RECORD">
</pre></form>
{section name=row loop=$results}
<form action="/phptest/smartytest.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="isbn" value="{$results[row].isbn}">
<pre>
Author {$results[row].author}
Title {$results[row].title}
Category {$results[row].category}
Year {$results[row].year}
ISBN {$results[row].isbn}
<input type="submit" value="DELETE RECORD"></form>
</pre>
{/section}
</body></html>
My best guess is that there is something wrong with the nested if statements (which may be why not even the error message is displaying), but I've double checked the code and it looks good (at least to me). Does anyone notice anything wrong with this? I can post a screen of what the page looks like if that will help.
You are checking for the existence of author, title, category, year, isbn with isset(..) before checking to see what type of action was taken. There variables (like $_POST['author'] are not set. Reason is that you have multiple forms on the page. Only the inputs that are within the form that is submitted are available in $_POST.
In this case, you could simply do:
if (isset($_POST['delete'])
&& isset($_POST['isbn'])
&& strlen($_POST['isbn'])) {
// Remove record code here
}
else {
// Add record code here
}