How to use MYSQL and two different Submit buttons? - php

I have created a song database (mysql) where a user can enter data into the textfield, select "by artist" or a "by title" radio button and click submit. This all works fine. :)
However, I would like to add another submit button that bypasses the above query and simply lists all of the songs that have been added to the database with a year's time.
I believe that the query I need is:
select * from dt_tb where `dt` >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
but I cannot figure out how to code the PHP to run the query for the songs within the past year.
Here are the two forms I have:
<p>
<form name="form" method="get" action="">
Search for: <input type="text" name="q" />
<input type="radio" name="field" value="title" <?=$checkTitle?> checked> Title
<input type="radio" name="field" value="artist" <?=$checkArtist?> > Artist
<input type="submit" name="Submit" value="Search" />
</form></p>
<form name="form" method="post" action="">
<br />
<input type="submit" name="Newsongs" value="New Releases" />
</form></p>
and here is the current, working php for the 1st query:
<?php
$delimiter = "\t";
$newline = "\n";
$var = #$_GET['q'] ;
$field = #$_GET['field'];
$var = htmlentities($var);
$trimmed = trim($var); //trim whitespace from the stored variable
$search_words = explode(' ', $var);
if ($var != "") {
// rows to return
$limit=100;
// check for an empty string and display a message.
if ($trimmed == "")
{
echo "<p>Please enter a search...</p>";
exit;
}
// check for a search parameter
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
//connect to your database
mysql_connect("DBLocation","DatabaseName","PASSWORD"); //(host, username, password)
//specify database
mysql_select_db("DatabaseName") or die("Unable to select database"); //select which database we're using
// Build SQL Query
$query = "SELECT * FROM Songs where $field like \"%$trimmed%\" order by $field ";
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
// If we have no results, offer a google search as an alternative
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>";
}
// next determine if s has been passed to script, if not use 0
if (empty($s)) {
$s=0;
}
// get results
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
// display what the person searched for
echo "<p>You searched for: "" . $var . ""</p>";
// begin to show results set
echo "<p style=\"color: #00ff00; font-size: 1.2em;\">Results</p>";
$count = 1 + $s ;
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
$title = $row["title"];
$artist = $row["artist"];
echo "$title";
echo " - ";
echo "$artist";
echo "<br />";
echo $newline;
$count++ ;
}
$currPage = (($s/$limit) + 1);
//break before paging
echo "<br />";
$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "<p>Showing results $b to $a of $numrows</p>";
}
?>

You can add a hidden field and then check it on submit:
<input type="hidden" name="act" id="act" value="">
Then on your second submit button, use JavaScript to change the value:
<input type="submit" name="Newsongs" value="New Releases" onclick="document.getElementById('act').value = 'list_all'" />
If the value is "list_all", process that, else do your current processing.
if ($_POST['act'] == 'list_all') {
// process second submit button code
} else {
// all your current code
}

You'll want to check if the NewSongs submit button was on the form submitted, and use that in an if statement to do the query or not.
<?php
if (!isset($_POST['NewSongs'])){
//do the search
} else {
//don't do the search
}
?>

You could use 2 submit button inside a form :
<p><form name="form" method="get" action="">
Search for: <input type="text" name="q" />
<input type="radio" name="field" value="title" <?=$checkTitle?> checked> Title
<input type="radio" name="field" value="artist" <?=$checkArtist?> > Artist
<input type="submit" name="submit" value="Search" />
<input type="submit" name="submit" value="New" />
</form>
</p>
<?php
if(isset($_GET['submit']) && $_GET['submit'] == 'Search'){
// do search
}
if(isset($_GET['submit']) && $_GET['submit'] == 'New'){
// do second search
}
?>

Related

Warning: Illegal string offset error

I'm trying to create a simple search engine in php, in which if the user enters a keyword they can search by event name or location. Then the results to be displayed in date order. Most of the has been taken from another site, but I am trying to convert it.
Can someone explain the error below to a newbie, in simple terms and how to correct it?
/home/ubuntu/workspace/test/test.php:49: array(5) { 'eventID' => string(1) "1" 'eventName' => string(8) "Exciting" 'eventLocation' => string(7) "Stadium" 'commencing' => string(10) "2017-04-01" 'expires' => string(10) "2017-04-30" } Warning: Illegal string offset 'eventName' in /home/ubuntu/workspace/test/test.php on line 50 Call Stack: 0.0003 238624 1. {main}() /home/ubuntu/workspace/test/test.php:0 1
<?php
session_start();
//include files
include 'header/header.php';
include 'nav/navigation.php';
include 'init.php';
$expires = strtotime($_POST["expires"]);
$expires = date('Y-m-d', $expires);
$events = "";
$find = $_POST['find'];
$field = $_POST['field'];
$searching = true;
if(isset($_POST["submit"])) {
if(!empty($_POST["events"])) {
$searching = false;
}
//This is only displayed if the user submitted the form
if($searching == true)
{
echo "<h2>Results</h2><p>";
//If the user did not enter a search term, they receive an error
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to the database
//$result = mysqli_query($connection,$query) or exit ("Error in query:
$query. ".mysqli_error($connection));
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$mysqli = new mysqli('localhost', 'root', '', 'c3470438');
$query = "SELECT * FROM events WHERE upper(eventLocation)
LIKE'%STADIUM%'";
$result = $mysqli->query($query);
//Temporarily echo $query for debugging purposes
//echo "$query";
//exit;
//And display the results
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "<br>";
foreach($row as $item) {
var_dump($row);
echo $item['eventName'];
exit();
}
exit;
//This counts the number or results. If there aren't any, it gives an
explanation
$anymatches=mysql_num_rows($data);
if ($anymatches == 0) {
echo "Sorry, but we can not find an entry to match your query<br>
<br>";
}
//And reminds the user what they searched for
echo "<b>Searched For:</b> " .$find;
}
}
?>
<fieldset>
<legend><h2>Events</h2></legend>
<form name="search" method="post" action="<?=$PHP_SELF?>">
<tr> <th> <td>
<fieldset>
<legend>Find all events</legend>
<input type="radio" name="events" <?php if (isset($events) &&
$events=="all") echo "checked";?>value="all"> Display all events
</fieldset>
<fieldset>
<legend>Find events by date</legend>
<input type="date" name="date" min="<?php echo date("Y-m-d");?>"
max="2025-01-01" value="<?php echo date("Y-m-d");?>">
</fieldset>
<fieldset>
<legend>Find events by keywords</legend>
<input type="hidden" placeholder='Search by keyword'name="searching"
value="yes" />
Search for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="eventName">Event Name</option>
<Option VALUE="eventLocation">Event Location</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="submit" />
</form>
</fieldset>
<button name="submit" value="submit" type="submit" class="button
expanded">Submit </button>
<button type="reset" value="Clear"class="button expanded">
Clear</button>
</fieldset>
</select> </td></tr>
<?php
//include files
include 'footer/footer.php';
?>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script>
</script>
</body>
Well $result->fetch_array(MYSQLI_ASSOC) returns a single row, but you are using it as if it returns all rows. So your foreach is iterating each field in the row, not each row and therefore you're trying to access an array key of a string.
Use a while like so:
while($row = $result->fetch_array(MYSQLI_ASSOC)){
echo $row['eventName'];
}
Also, you're using mysql_num_rows which is not part of mysqli. Instead use $result->num_rows.

PHP- how to get values from checked checkboxes and corresponding textboxes

I want to get three values separated by a comma when the form is submitted. The value from the checkbox, textbox 1 and textbox 2.
This is my code that retrieves values from mysql database and generates checkboxes and two corresponding textboxes.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$query = "SELECT * FROM subject";
$data = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($data)){
$s = $row['sub'];
echo $s;
?>
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="<?php echo $s; ?>" placeholder="Total Number" />
<input type="text" name="<?php echo $s; ?>" placeholder="Pass Number" />
<?php
}
?>
<input type="submit" name="submit" value="Add">
</form>
Suppose the user checks the first three boxes , and enters the values like in this picture -
when I click add, I get the values --
Physics
Math
Chemistry
by using the code below:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
echo $selected."</br>";
}
}
}
?>
but how do I get the values like this-
Physics,40,30
Math,40,30
Chemistry,30,25
I want this output in a variable so that I can store it in my database table.
I have spent several hours behind this in last few days. Please help me with this one.
you need to assign unique names to the <input type="text" ... /> so you can recieve its values in the PHP.
Second, you need to write PHP code, that's concatenating those values.
For example, your HTML code might be:
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="total[<?php echo $s; ?>]" placeholder="Total Number" />
<input type="text" name="pass[<?php echo $s; ?>]" placeholder="Pass Number" />
and your PHP code might be:
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
$total = $_POST['total'][$selected];
$pass = $_POST['pass'][$selected];
$var = $selected . ',' . $total . ',' . $pass;
echo $var . '<br />';
}
}
}

Search multiple words and single word at a time in a multiple row in Mysql php

I'm trying to use this search for searching more than one words or single word at a time from a database. Now the problem is that my script only running properly but please help me...
<form name="ds" method="post">
<input type="text" name="name" placeholder="Entername" />
<!--<input type="text" name="search" placeholder="Location" />-->
<select name="location[]" multiple="multiple">
<option value="delhi">Delhi</option>
<option value="Mumbai">Mumbai</option></select>
<input type="submit" name="submit" value="Search" />
</form>
<?
$conn=mysql_connect("localhost","root","");
mysql_select_db("dbrozgarexpress",$conn);
echo $search =$_POST['location'];
$description = "";
$name2=$_POST['name'];
if(isset($name2)&&$name2 != ""){
if($flag){
$cheack.= "AND ";
}
$cheack.="user_first_name ='$name2' ";
$flag =true;
}
if(isset($search)&&$search != ""){
if($flag){
$cheack.= "AND ";
}
foreach($search AS $s)
{
$cheack.="user_current_location_id ='$s' or ";
$flag =true;
}
}
$cheack = substr($cheack, 0, -4);
echo $query = "SELECT * FROM `tb_user` WHERE $cheack ";
?>
error SELECT * FROM `tb_user` WHERE user_first_name ='kum
I think I have a general idea of what you are after.
P.S. the query will only show after you submit the form - i.e. after you click search button
Try this:
<?php
// Handle Post
if (count($_POST))
{
// Load Params
$name = isset($_POST['name']) ? $_POST['name'] : '';
$locations = isset($_POST['location']) ? $_POST['location'] : array();
// Start Query
$sql = 'SELECT * FROM `tb_user` WHERE ';
// Build Query
$sql_parts = array();
if (!empty($name)) {
$sql_parts[] = "`user_first_name` = '$name'";
}
if (sizeof($locations)) {
foreach ($locations as $location) {
$sql_parts[] = "`user_current_location_id` = '$location'";
}
}
$sql = $sql . implode(' AND ', $sql_parts);
// Debug
echo $sql ."<br><br>";
}
?>
<form action="" name="ds" method="post">
<input type="text" name="name" placeholder="Entername" />
<select name="location[]" multiple="multiple">
<option value="delhi">Delhi</option>
<option value="Mumbai">Mumbai</option></select>
<input type="submit" name="submit" value="Search" />
</form>
Here's an example of this working:
No location selected, name only
name and one location
name and two location

PHP - Getting back Post from forEach select form

i have a website where the admin can choose to add a certain number of bbcode tags and the corresponding html tags.
First he chooses how many tags he wants to add from a drop down select form in a for Each loop.
Depending on how many tags he chose when he clicked the submit button, the corresponding number of input tags appear in a second form, also in a for Each loop. He fills in the bbcode and html input and clicks the submit button. Normally the tags should be added to my database but in this case when he clicks submit the form disappears and nothing is added..
Here is the code :
//FIRST FORM WHERE HE DECIDES HOW MANY TAGS TO ADD
<form id='nbbalises' action='config.ini.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>How many tags ?</legend>
<input type='hidden' name='submitted' id='submitted' value='1' />
<?php
echo '<select name="number">';
$range = range(1,50,1);
foreach ($range as $nb) {
echo "<option value='$nb'>$nb</option>";
}
echo "</select>";
?>
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form><br /> <br />
<?php
if (!(empty($_POST['number']))) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
//SECOND FORM WHERE I GENERATE THE INPUT DEPENDING ON THE NUMBER CHOSEN FROM FIRST FORM
<form id='balises' action='config.ini.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>Balises bbc : </legend>
<input type='hidden' name='submitted' id='submitted' value='1' />
<?php
foreach ($range2 as $nb2) {
echo "<label>bbcode tag $nb2 :</label>
<input type='text' size='40' name='bbc$nb2' id='bbc$nb2' maxlength='40' />
<label>html tag $nb2 :</label>
<input type='text' size='40' name='html$nb2' id='html$nb2' maxlength='40' />
<br />";
}
}
?>
<input type='submit' name='Submit2' value='Submit2' />
</fieldset>
</form>
<?php
//PROBLEM STARTS HERE, NOTHING WORKS UNDER HERE
if (isset($_POST['Submit2'])){
//CONNECT TO MY DATABASE
connectDB();
for ($i=0; $i<$number ; $i++){
if (!(empty($_POST["bbc$i"])) && (empty($_POST["html$i"])))
//FUNCTION ADDS TAGS TO DATABASE
addBbc($_POST["bbc$i"], $_POST["html$i"]);
}
mysql_close();
}
}
//MY FUNCTIONS TO ADD THE BBCODE AND HTML TO DATABASE
function connectDB(){
//connexion DB
$link = mysql_connect('127.0.0.1', 'USERNAME', 'PASSWORD');
if (!$link) {
die('Erreur de connexion: ' . mysql_error());
}
$db = mysql_select_db('1213he200967',$link) or die("N'a pu selectionner
1213he200967");
mysql_query("SET NAMES 'utf8'");
}
function addBbc($bbc, $html){
$b = mysql_real_escape_string($bbc);
$h = mysql_real_escape_string($html);
$query="INSERT INTO bbcode (BBC,HTML) VALUES ('$b','$h')";
$result = mysql_query($query) or die("error");
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
return false;
}
else return true;
}
Thank you very much, and sorry if my code is amateur-ish, i'm only starting in php.
EDIT
Found part of my problem
$number = $_POST['number'];
$range2 = range(1,$number,1);
This goes from 1 to the number chosen by the user in the first form.
for ($i=0; $i<$number ; $i++){
if (!(empty($_POST["bbc$i"])) && (empty($_POST["html$i"])))
//FUNCTION ADDS TAGS TO DATABASE
addBbc($_POST["bbc$i"], $_POST["html$i"]);
This goes from 0 to $number - 1
So i changed my code to this.
for ($i=0; $i<$number ; $i++){
$nb = $i + 1;
if (!(empty($_POST["bbc$nb"])) && (empty($_POST["html$nb"]))) {
addBbc($_POST["bbc$nb"], $_POST["html$nb"]);
}
else echo "$nb tags empty ";
This works a bit better but now it goes to the else just here above and displays "2 tags empty", so it still doesn't quite work.
Ok to solve it I finally decided to post the data from the second form to another page and i modified my code to this.
for ($i=0; $i<$number ; $i++){
$nb = $i + 1;
$varBbc = 'bbc'.$nb;
$varHtml = 'html'.$nb;
if ((isset($_POST[$varBbc])) && (isset($_POST[$varHtml]))) {
addBbc($varBbc, $varHtml);
}
else echo "$nb tags empty ";
}
Apparently using !empty instead of isset doesn't work in this case, maybe because of the html tags.
$nb should be in double quotes.
so echo "<option value='$nb'>$nb</option>"
change to echo "<option value='".$nb."'>$nb</option>";
and also
if (!(empty($_POST['number']))) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
change to:
if (isset($_POST['submit'])) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>

PHP variable returns a null value

I've created a textbox so when the admin types a name and clicks submit, it will shows a list of retrieved data from the database.
<form method="post" action="">
<?php
$teacherName = $_POST['teacherName'];
if ($_POST['submitted'] == 1) {
if($teacherName != ""){
$getName = mysql_query("SELECT name, user_id FROM members WHERE name = '$teacherName'");
$teacherdetails = mysql_fetch_array($getName);
$teachername = $teacherdetails['name'];
$teacher_id = $teacherdetails['user_id'];
if($teachername != ""){
print $teachername . "<br/>";
} else {
print "Give a valid name <br/>";
}
}
}
if ($teachername == ""){ ?>
Teacher name:<input type="text" size="20" name="teacherName"><input type="hidden" name="submitted" value="1"><br/>
<input type="submit" value="Submit" />
<?php $getModule = mysql_query("......");
while ($row2 = mysql_fetch_array($getModule)) { ?>
<input type="checkbox" name="modules[]" value="<?php print $row2["module_id"]?>"/> <?php print $row2["module_name"] . '<br/>'; } ?>
</div><br/> <?php } ?>
<input type="submit" value="Submit" />
</form>
Below I wrote this code (in the same script):
<?php
$modules = $_POST['modules'];
for($i = 0; $i < count($modules); $i++){
$module=mysql_query("INSERT INTO module (module_id,user_id) VALUES ('$modules[$i]','$teacher_id')");
}
?>
but for some reason when I call the variable "$teacher_id" (which is the value I retrieved before from the database. It works fine in the form) it returns nothing. It's null but I can't understand why.
Am I doing something wrong?
First off, put the PHP outside the form tags, at the top.
Secondly, the data you are receiving could be an array; with more than one result set;
do this just incase it it returned as that;
foreach($teacherdetails AS $teacher) {
//also set the values of the variables here
echo $teacher['name'];
echo $teacher['user_id'];
}
Regarding the last bit, is the $teacher_id successfully printing a result?
Also, where is the modules being input and posted from?

Categories