PHP - Query From Post Method Works For Text Box But Not Selection List
Hi, I'm new to PHP/MySQL and need some help getting my query to work for my selection list:
The selection list is built with: <form action='processformmissing.php' method='POST'> <fieldset> <legend>Choose Department</legend> <select name='depart'> <option value=''></option> <?php while ($row = mysqli_fetch_array($result)) { extract($row); echo "<option value='$department'>$department</option>\n"; } ?> </select> <p><input type='submit' value='Select Department' /></p> </fieldset> </form> The data is then sent to: $depart = $_POST['depart']; $deptlike = "%".$depart."%"; echo "<p>$depart</p>"; echo "<p>$deptlike</p>"; $query = "SELECT * FROM lifecerts INNER JOIN employees ON lifecerts.cid = employees.cid WHERE department LIKE '$deptlike' ORDER BY employees.name"; Hitting the submit button from my selection list form seems to be working fine because when I echo my data ($depart and $deptlike) it is giving me the correct value, but the query doesn't give me any results. However, if my post data comes from a text box instead of a selection list, my query works fine. Any thoughts on what I'm doing wrong??? Many thanks! Similar Tutorials//here is the code. For some reason it searches the first time, but the second search loads everything. testing at: mnmotorsports.com // searcha.php <?php require("head.php");?> <table width="800" border="1"><tr><td width="550"></td><td> <form method="post" action="searcha.php?go" id="searchform"> <input type="text" name="name"> <input type="submit" name="submit" value="Search"> </form> </td></tr> <tr><td height ="300"> <?php echo "searching"; // connect to host require("connect.php"); // retrieve data $name = $_POST['name']; echo " any card name matching: <b>'".$name."'</b>"; $query = "SELECT * FROM ".$tname." WHERE name LIKE '%".$name."%'"; $result = mysql_query($query) or die(mysql_error()); $SearchCntr=0; while($row = mysql_fetch_array($result)){ $SearchCntr++; echo "<table border='1' width='500'>"; echo "<tr><td>".$row['edition']." | <a href='#'>".$row['name']."</a> | ".$row['manacost']." | ".$row['price']."</td></tr>"; echo "</table>"; } echo $SearchCntr." SEARCH RESULTS</body></html>"; ?> </td><td></td> </tr> </table> <?php require("footer.php"); ?> Hi I am having this error while running my php script using ajax. Everything seems to be fine but I do not know why it is giving this error. Code: [Select] <br /> <b>Notice</b>: Undefined index: amount in <b>C:\wamp\www\...\add_bid.php</b> on line <b>3</b><br /> {"error":"yes","fieldErrors":null} Here is my code here is .php code which contains the form Code: [Select] <?php session_start(); $auctionid = $_POST['auction_id']; include "design/header.php"; include "DB/db.php"; ?> <div class="contents" id="bid_contents"> <?php $q = "SELECT * FROM bids WHERE productid='$auctionid' ORDER BY bidid DESC LIMIT 0,1"; $query = mysql_query($q) or mysql_error(); //echo $q; $row = mysql_fetch_assoc($query) or mysql_error(); $current_bid = $row['current_bid']; $thumbnail = mysql_query("SELECT * FROM products WHERE productid='$auctionid'"); $row_thumb = mysql_fetch_assoc($thumbnail); $thumb = $row_thumb['thumbnail']; $title = $row_thumb['product_title']; ?> <div id="thumb"> <img src='<?php echo $thumb ?>' border='none' /><br /> <?php echo $title."<br />"; echo "<b>Current Bid:</b> Eur ".$current_bid; ?> <form name="bid_form" id="bid_form"> <input type="text" name="amount" size="5" /> <input type="button" name="place_bid_btn" id="bid_btn" value="Place Bid" /> <div id="message"></div> </form> </div><!-- thumb --> </div> <?php include "design/footer.php" ?> here is .js file for ajax Code: [Select] $(function() { $('#bid_btn').click(function() { var url = 'add_bid.php'; var query = $('#bid_form').serialize(); alert(query); $.ajax({ type: 'POST', url: url, query: query, dataType: 'json', success: function(data) { if(data.error == 'no') { $('#message').css('display','none'); } else { $('#message').html(data.fieldErrors).css('display','block'); } } }); }); }); and here is where i get data from previous .php file and the problem seems to be in this page. I guess. Name of this page is add_bid.php Code: [Select] <?php session_start(); $bid = $_POST['amount']; $error = 'yes'; $msg = $bid; $JSON_array = array('error' => $error, 'fieldErrors' => $msg); $JSON_response = json_encode($JSON_array); header('Content-type: application/json'); echo $JSON_response; ?> I am adding jquery library and javascript file in my header.php file so it is fine. Please help Dear All, I am trying to check which button is clicked inside the same php file and from there i will do some coding, I tried to echo some text but not working. PHP: <?php include('dbcon.php'); include('session.php'); $result=mysqli_query($con, "select * from staff where OracleID='$session_id'")or die('Error In Session'); $row=mysqli_fetch_array($result); if (isset($_POST["inside"])){ echo 'inside'; } else{ echo 'outside'; } ?> HTML: <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="form-wrapper"> <center> <form action="home.php" method="POST"> <h3>Welcome: <?php echo $row['StaffName']; ?> </h3> <?php if ($row['ClockedIn'] == True and $row['ClockedOut'] == False) {echo "You already clockedIn today, please clockOut"; echo '<button hidden> type="submit" class="buttonstyle" >Clock Time IN!</button>'; echo '<button type="submit" name = "out" class="buttonstyle">Clock Time OUT!</button>';} ?> <?php if ($row['ClockedOut'] == False and $row['ClockedIn'] == False) {echo '<button type="submit" name = "inside" class="buttonstyle" >Clock Time IN!</button>'; echo '<button type="submit" name = "out" class="buttonstyle" >Clock Time OUT!</button>';} ?> <?php if ($row['ClockedIn'] == True and $row['ClockedOut'] == True) {echo "You already clockedIn and ClockedOut today!"; echo '<button hidden> type="submit" class="buttonstyle" >Clock Time IN!</button>'; echo '<button hidden> type="submit" class="buttonstyle">Clock Time OUT!</button>';} ?> </form> </center> </div> </body> </html> Please help on this please. try to give difference in points Code: [Select] <?php if ($_SERVER['REQUEST_METHOD'] == 'POST'){ $db = mysql_connect("localhost", "*******" , "*****")or die("Error connecting to database: " . mysql_error()); $db_used = mysql_select_db("pskkorg_drp1", $db)or die("Could not select database: " . mysql_error()); $user_name = mysql_real_escape_string($_POST['username'],$db); $query = mysql_query("SELECT * FROM student WHERE Username = '$user_name'",$db) or die(mysql_error()); if(mysql_num_rows($query) == 1){ echo "Login successful, welcome back " . $user_name . ""; }else{ echo "Login unsuccessful, please ensure you are using the correct details"; } }else{ echo "Error"; } ?> take a look at this code, is there anything wrong?... it always come out the error output when i test it. when i enter this url, http://www.pskk.org/LMS/LMSscripts/FirstTimeUser10.php?Username=149090 it come out Error. suppose it will appear Login Successful since the username 149090 exist in the database. Hey Everyone.
I am hoping this is the right place to ask this question.
I am using a new WordPress theme and it has native related post coding in it. The problem is the code uses Post Tags as the selection value instead of Post Category. I was wondering if anyone could help me with this strip of code. I want to change it so the theme gets Posts in the same Category, instead of Posts with the same Tags.
* Display related posts. * * @return void */ function stag_related_posts() { global $post; if( stag_rcp_user_has_no_access() ) return; if( ! stag_theme_mod( 'post_settings', 'show_related_posts' ) ) return; $tags = wp_get_post_tags( $post->ID ); if ( count( $tags ) ) { $tags_ids = array(); foreach($tags as $individual_tag) { $tag_ids[] = $individual_tag->term_id; } $query = new WP_Query( array( 'tag__in' => $tags_ids, 'post__not_in' => array( $post->ID ), 'posts_per_page' => absint( stag_theme_mod( 'post_settings', 'related_posts_count' ) ), 'caller_get_posts' => 1 ) ); // Add filter to attach 'post-grid' class add_filter( 'stag_showing_related_posts', '__return_true' ); if( $query->have_posts() ) : echo '<section class="related-posts" data-layout="2-2-2-2">'; while( $query->have_posts() ) : $query->the_post(); get_template_part( 'content', get_post_format() ); endwhile; echo '</section>'; endif; } wp_reset_query(); remove_all_filters( 'stag_showing_related_posts' ); }I've tried simply replaces the words Tags with Categories, but it doesn't seem to do much. Any help would be greatly, greatly, appreciated. I'm trying to update every record where one field in a row is less than the other. The code gets each row i'm looking for and sets up the query right, I hope I combined the entire query into one string each query seperated by a ; so it's like UPDATE `table` SET field2= '1' WHERE field1= '1';UPDATE `table` SET field2= '1' WHERE field1= '2';UPDATE `table` SET field2= '1' WHERE field1= '3';UPDATE `table` SET field2= '1' WHERE field1= '4';UPDATE `table` SET field2= '1' WHERE field1= '5'; this executes properly if i run the query in phpMyAdmin, however when I run the query in PHP, it does nothing... Any advice? Hi there, I wrote a pretty simple html form that inputs data into my database. I've included a truncated version of it, There are a lot more fields. Basically when i hit the submit it processes input.php but after its been successful the page is still at input.php in the browser Is there anyway to take the page back to the page i was using to input data Code: [Select] <form action="insert.php" method="post"> <p>Adornment Name: <br> <input type="text" name="name"> <br> <br> Quality: <br> <select name="quality"> <option value="Other">Other Not Listed</option> <option value="Superior">Superior</option> <option value="Greater">Greater</option> <option value="Lesser">Lesser</option> <option value="Raid">Raid</option> <option value="Faction">Faction</option> </select> </form> Code: [Select] include 'db_connect.php'; $sql="INSERT INTO $db_table (name, quality) VALUES ( '$_POST[name]', '$_POST[quality]')"; if (!mysql_query($sql,$db)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($db) ?> i created an array like this while{ $ir = 0; $stud[$row_mrk['id_sub']][$ir]=$row_mrk['id_sub']; $ir++; $stud[$row_mrk['id_sub']][$ir]=$row_mrk['seminar_topic']; $ir++; $stud[$row_mrk['id_sub']][$ir]=$row_mrk['seminar_mark']; $ir++; $stud[$row_mrk['id_sub']][$ir]=$row_mrk['attendance']; $ir++; $stud[$row_mrk['id_sub']][$ir]=$row_mrk['internal_mark']; $ir++; $stud[$row_mrk['id_sub']][$ir]=$row_mrk['external_mark']; $ir++; } echo "<input type='hidden' name='ar_std' id='ar_std' value='$stud' /> </table>" ; and it is able to print in the same page using foreach ($stud as $v1) { echo "$v1\n<br>"; foreach ($v1 as $v2) { echo "$v2\n<br>"; } } and in the next page $ar_stud[]=$_POST["ar_std"]; I'm getting an error PHP Warning: Invalid argument supplied for foreach() in save.php on line 25 PHP Stack trace: Hello I am working in moodle and its code base is in PHP. I am a novice to moodle as well as PHP and not quite familiar with PHP syntax. Right now I have built a Web page in moodle, and its view.php file I need to implement a fuctionality on click of a button. On click of submit button, I am trying to implement a functionality and I have written the code for that under if(isset($_POST['submit])) { ...my code...} Also while creating the form I have set the attributes as follows: echo "<form method='post' action='" . $_SERVER['PHP_SELF']."?inpopup=". $_GET['inpopup']."&id=" . $_GET['id'] . "'>"; But irrespective of whether or not I click the button, whenevr the page loads for the first time, it perform the code written in IF loop as well. So Am i going wrong in implementing a functionality on click of button in PHP or is it something related to moodle, if anyone knows? Any help or suggestions would be appreciated. As I am stuck with this logic since last three days. Regards hello, I was wondering if it is possible to get all the data sent by a html form via post/get method and use it somehow. it is difficult to explain what i mean, i don't mean to say how to get data normally i.e.. by using variables for example $data = $_POST['data']; that can only get only one field that is "data". The reason i am looking for this is because i have many forms that will have to use the mail() function, the problem is creating variables for each from then use the mail() function to send it will be time consuming. and the fields are different in different forms. I have noticed the similar technology used by mailmyform . com, they capture the data in any html form posted to their php page and mail it to the given email. Hi I am pulling my hair out over this, I have tried many many ways on getting this to work but none have. I have a multi list selection box, which the user can select more than one option from. Once submitted this gets sent to a mysql database table. Below is my shortened version of the multi list html code: <select multiple="multiple" size="10" name="special[]"> <option value="Abdominal Training"> Abdominal Training </option> <option value="Aerobics"> Aerobics </option> <option value="Agility"> Agility </option> </select> If have tried putting [] which creates an array in the mysql table field special, but when I echo it back it just echos 'array'. When I try it without the [], and echo it back, it only echos one selection. I am still new to php, but have managed to get my head around a lot, but have been stuck on this for weeks, please help. if a user were to select multiple items in a selection list I would like to concatenate those items into a list and assign that into a variable. I know I should loop through the list but i'm not sure how I would continue to add those values to a variable. Quote
I have this code here. i wanted to know how i can be able to make multiple selections from the returned data from the database and how to save them Quote
<select name="troom" multiple class="form-control" required> <option selected="true" disabled="disabled">--Select a room--</option> $records =mysqli_query($con, "select * from room where TRoom not in (select TRoom from roombook where cin <= '$checkout' and cout >= '$checkin');"); while ($data = mysqli_fetch_array($records)) { echo "<option value='" . $data['TRoom'] . "'>" . $data['TRoom'] . "</option>"; //displaying data in option menu } } ?> </select>
I'm trying to get this drop down menu to be sticky once the user clicks submit. Here's my entry code: Code: [Select] if (isset($_POST['guess'])) { if ($_POST['guess'] == $_SESSION['number']) { $response = "You Win!"; unset($_SESSION['number']); } else { $_SESSION['tries']++; if ($_SESSION['tries'] < 3) { $response = "Try #{$_SESSION['tries']}<br /><br />"; } else { $response = "You Lose"; unset($_SESSION['number']); } } } if (empty($_SESSION['number'])) { $_SESSION['tries'] = 0; $_SESSION['number'] = rand(1, 10); } And in my body: Code: [Select] <select name="guess" id="guess"> <?php for ($i = 1; $i < 11; $i++) { echo "<option value='{$i}'>{$i}</option>"; } ?> </select> Hi I have to two multi list select boxes side by side. The first has all the options that the user can select which they can select and transfer to the other multi list select box. I have used javascript to create the buttons which allow you to add and remove selections from the right multi list box. Once I hit submit all the selections go to a mysql database, which is fine. However my problem is that the selected options don't stay in the right hand mulit list box after submission. So I need to know how I can keep them in there, or maybe populate that right hand multi list box with the submitted selections. FYI: once the selections are submitted they are stored in a text field in mysql database, so I need them to come back, as options in the right hand multi list box. Hope this makes sense Below is a link to something similar, just need to sort out the php side http://www.dhtmlgoodies.com/scripts/multiple_select/multiple_select.html Many Thanks I've used a showQuery() method for years which accepted a SQL string and data array. Sometimes, I just have the PDO statement and I need to add temporary script just to keep track of the SQL string. Was looking at debugDumpParams() today which prompted me to create the new showStmtQuery() method. My approach of extracting the table from debugDumpParams's printed results is a little clunky. Any recommendations? Could/should other information from debugDumpParams's output be used? I typically don't use bound parameters but know I should more often. Suggestions how this could be changed to work with bound parameters? Thanks
function showQuery(string $sql, arrray $data, bool $keepLineBreaks=false):string { $keys = []; $values = []; foreach ($data as $key=>$value) { $keys[] = is_string($key)?'/:'.$key.'/':'/[?]/'; $values[] = is_numeric($value)?$value:"'$value'"; } $sql = preg_replace($keys, $values, $sql, 1, $count); return $keepLineBreaks?$sql:str_replace(array("\r", "\n"), ' ', $sql); } function showStmtQuery(\PDOStatement $stmt, array $data, bool $keepLineBreaks=false):string { ob_start(); $stmt->debugDumpParams(); $sql = ob_get_contents(); ob_end_clean(); //$sql = strtok(substr($sql, strpos($sql, '] ')+2), "\n"); $start=strpos($sql, '] ')+2; $sql = substr($sql, $start, strpos($sql, "\nParams:") - $start); return showQuery($sql); } $data=[5,50]; $sth = $pdo->prepare('SELECT * FROM my_table WHERE id > ? AND id < ?'); echo(showStmtQuery($sth, $data).PHP_EOL); //SELECT * FROM my_table WHERE id > 5 AND id < 50 $data=['lowId' => 5, 'highId' => 50]; $sth = $pdo->prepare('SELECT * FROM my_table WHERE id > :lowId AND id < :highId'); echo(showStmtQuery($sth, $data).PHP_EOL); //SELECT * FROM my_table WHERE id > 5 AND id < 50
Changed to use original showQuery function Hi I have created a Database class that uses the singleton method. I have a query method within this class so i would call this to return an array of results. What i need to know is what would be the best way to use this returned array Database Class: Code: [Select] <?php class Database { private static $dbInstance; private $hostname; private $username; private $password; private $database; private function __construct() { $this->hostname = 'localhost'; $this->username = 'user'; $this->password = 'pass'; $this->database = 'test'; mysql_connect($this->hostname, $this->username, $this->password); mysql_select_db($this->database); } public static function getDBInstance() { if (!self::$dbInstance) { self::$dbInstance = new Database(); } return self::$dbInstance; } public function query($q) { return mysql_query($q); } } ?> Person Class: Code: [Select] <?php require_once('Database.php'); class person { public function getName($id) { $con = Database::getDBInstance(); $query = $con->query("select name from data where id = ".$id); $result = mysql_fetch_assoc($query); echo $result['name']; } } ?> Index page: Code: [Select] <?php require_once('person.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> </head> <body> <?php $person = new person(); $person->getName(1); echo "<br />"; $person->getName(2); ?> </body> </html> I use AJAX method to get the value for `$month` from the year-month selection in my page. The year-month is pass correct correctly when it gets into my PHP code. But i am not sure how do i get the value and use it for my sql condition. I'm trying to plot a graph using Chart JS according to the year-month selection from the user. when the user select "2021-03" all the order that is made in the month of March will be plotted into the graph. There's no data shown in my page now and i do not know how can i query it. Can anyone enlighten me how can i do it? Because i do not know what mistake did i made here. Any kind of explanation will be appreciated. Thanks!
This is the code that i use for year-month selection <div class="col-2 my-auto"> <input type="month" id="month" class="form-control" value="<?php echo date('Y-m'); ?>"> </div> <div class="col-2 my-auto"> <button type="button" class="btn btn-info" onclick="loadchart();"> <i class="nc-icon nc-zoom-split"></i> </button> </div> This is the AJAX method <script type="text/javascript"> function loadchart() { $('#spin1').show(); var month= $('#month').val(); var data = { month: month, } $.ajax({ method:"GET", data:data, url:"includes/loadchart.php", success:function(data) { $('#loadchart').html(data); } }); } this is my loadchart.php <?php include '../session.php'; if(isset($_GET['month'])) { $months = $_GET['month']; ?> <?php $days = array(); $gross_sales = array(); $average_sales = array(); $type = CAL_GREGORIAN; $month = date('n'); $year = date('Y'); $day_count = cal_days_in_month($type, $month, $year); for ($i = 1; $i <= $day_count; $i++) { $sql = "SELECT *, SUM(purchase_price) as purchase_price FROM ordered_items WHERE DAY(order_datetime) = '$i' AND MONTH(order_datetime) = MONTH('".$months."') AND YEAR(order_datetime) = YEAR('".$months."') AND order_status = 5 "; $query = $conn->query($sql); $total = $query->num_rows; $row = $query->fetch_assoc(); if($row['purchase_price'] != 0) { $gross_sales[] = $row['purchase_price']; } else if ($row['purchase_price'] == 0 && $i <= date('d')) { $gross_sales[] = 0; } $average_sales[] = $row['purchase_price'] / $day_count; $day = $i.'/'.$month; array_push($days, $day); } $days = json_encode($days); $daily_gross_sales = json_encode($gross_sales); $average_gross_sales = json_encode($average_sales); ?> <script> const colors = { colorcode: { fill: '#51cbce', stroke: '#51cbce', }, }; var ctx2 = document.getElementById("attChart").getContext("2d"); const attChart = new Chart(ctx2, { type: 'line', data: { labels: <?php echo $days; ?>, datasets: [{ label: "Gross Sales: RM", fill: true, pointBackgroundColor: colors.colorcode.stroke, borderColor: colors.colorcode.stroke, pointHighlightStroke: colors.colorcode.stroke, borderCapStyle: 'dot', pointRadius: 5, pointHoverRadius: 5, pointStyle: 'dot', data: <?php echo $daily_gross_sales; ?>, showLine: true }, { label: "Average Sales: RM", fill: true, pointBackgroundColor: '#FF0000', borderColor: ' #FF0000 ', pointHighlightStroke: '#FF0000', borderCapStyle: 'dot', pointRadius: 5, pointHoverRadius: 5, pointStyle: 'dot', data: <?php echo $average_gross_sales; ?>, showLine: true } ] } <?php } ?> I do not know why my query from the loadchart.php is incorrect. Please help me with this advice me on this issue thanks! $sql = "SELECT *, SUM(purchase_price) as purchase_price FROM ordered_items WHERE DAY(order_datetime) = '$i' AND MONTH(order_datetime) = MONTH('".$months."') AND YEAR(order_datetime) = YEAR('".$months."') AND order_status = 5 ";
Good day and Merry Christmas to all, I just spent a good time of my christmas eve trying to figure out this problem. I hope one of you santas would be so kind as to help me with it. First off I have two tables; employee and employee_works both connected via employee_id key. Basically I have a parent window we'll call parent.php. inside the parent page is a search button that once clicked will open a child window we'll call child.php inside the child page is a list, lets say employees with name, employee_id, etc. My main concern is this: How do I populate parent.php based off the employee selection I made in the child window. Example: -Access parent.php -Click on search -Click on [ID: 004] [NAME: JOHN SMITH] [PHONE: 1233456] [DATE HIRED: JULY 16, 1992] <---format of a row in child.php -child.php automatically closes and parent.php now shows all data from employee_works with the employee_id = 004 Is this even possible? I know this is vary vague and would be willing to explain more if needed. My website is built mostly on javascript and php. |