PHP - Select Form To Display Data From Mysql Not Working When Using Ajax
I had this working, but when I try and get fancy and use AJAX the data doesn't display. I think this is a PHP problem though.
My code for the select form including AJAX code Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-GB"> <head> <title>AJAX Example</title> <link rel="stylesheet" type="text/css" href="Form.css" media="screen" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("tr:odd").addClass("odd"); }); </script> <script type="text/javascript"> function showPlayers(str) { var xmlhttp; if (str=="") { document.getElementById("DataDisplay").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); else {// code for IE6, IE5 } xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("DataDisplay").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","Query.php?category_id="+str,true); xmlhttp.send(); } </script> </head> <body> <h1">AJAX Example</h1> <?php #connect to MySQL $conn = @mysql_connect( "localhost","username","pw") or die( "You did not successfully connect to the DB!" ); #select the specified database $rs = @mysql_SELECT_DB ("MyDB", $conn ) or die ( "Error connecting to the database test!"); ?> <form name="sports" id="sports"> <legend>Select a Sport</legend> <select name="category_id" onChange="showPlayers(this.value)"> <option value="">Select a Sport:</option> <?php $sql = "SELECT category_id, sport FROM sports ". "ORDER BY sport"; $rs = mysql_query($sql); while($row = mysql_fetch_array($rs)) { echo "<option value=\"".$row['category_id']."\">".$row['sport']."</option>\n "; } ?> </select> </form> <br /> <div id="DataDisplay"></div> </body> </html> Query.php <?php #get the id $id=$_GET["category_id"]; #connect to MySQL $conn = @mysql_connect( "localhost","username","pw") or die( "Error connecting to MySQL" ); #select the specified database $rs = @mysql_SELECT_DB ("MyDB", $conn ) or die ( "Could not select that particular Database"); #$id="category_id"; #create the query $sql ="SELECT * FROM sports INNER JOIN players ON sports.category_id = players.category_id WHERE players.category_id = '".$id."'"; echo $sql; #execute the query $rs = mysql_query($sql,$conn); #start the table code echo "<table><tr><th>Category ID</th><th>Sport</th><th>First Name</th><th>Last Name</th></tr>"; #write the data while( $row = mysql_fetch_array( $rs) ) { echo ("<tr><td>"); echo ($row["category_id"] ); echo ("</td>"); echo ("<td>"); echo ($row["sport"]); echo ("</td>"); echo ("<td>"); echo ($row["first_name"]); echo ("</td>"); echo ("<td>"); echo ($row["last_name"]); echo ("</td></tr>"); } echo "</tr></table>"; mysql_close($conn); ?> I think the problem is either with this part in the AJAX Code: [Select] xmlhttp.open("GET","Query.php?category_id="+str,true); or most likely in my Query.php code when I wasn't using AJAX and using POST it worked fine, but adding the AJAX stuff and GET it doesn't work. When I echo out the SQL the result is Code: [Select] SELECT * FROM sports INNER JOIN players ON sports.category_id = players.category_id WHERE players.category_id = '' so the category_id is not being selected properly and that is the primary key/foreign key in the MySQL table which connects the JOIN. Similar TutorialsThis is a continuation of a previous post. I am trying to get the names of countries that are in a database table. It's not working! All I get is a Submit button, but no data. This is what I understand from the code that Psycho suggested: I am unfamiliar with the function and the use of the FOREACH constuct. looking at the PHP manual there are two syntaxes. It appears that Psyhco has used the second form where the current element's key is assigned to $key variable for each itteration. foreach (array_expression as $key => $value The 2 variables he used are $id and $label I assume that the line: $optionsHTML = ''; is the array built from the expression: $optionsHTML .= "{$label}\n"; Because I was not familiar with the PDO method, but have used mysqli, I had to rewrite the data retrival part which I believe is OK. I guess that the line : $countryOptions = buildSelectOptions($countries); is used in conjunction with the function to build the array. The HTML part that Psycho wrote puts the variable into the Form format for a selection list. Why is the $optionsHTML also inclosed in the option tags? Have I got the HTML part correct or is it the data extraction part that is incorrect? Here is the code: <? include("AddStats_admin_connect.php"); //connect to database doDB(); //Function to build select options based on passed array function buildSelectOptions($options) { $optionsHTML = ''; foreach($options as $id => $label) { $optionsHTML .= "<option value='{$id}'>{$label}</option>\n"; } return $optionsHTML; } //Run query to get the ID and Name from the table //Then populate into an array $clist_sql = "SELECT CID, Country FROM Countries"; $clist_res= mysqli_query($mysqli, $clist_sql) or die(mysqli_error($mysqli)); if (mysqli_num_rows($clist_res) < 1) { //this Country not exist $display_block = "<p><em>You have selected an invalid Country.<br/> Please try again.</em></p>"; } $countries = array(); while($Ctry_info = mysqli_fetch_array($clist_res)) { $countries[$Ctry_info['CID'] = $Ctry_info['Country']]; } $countryOptions = buildSelectOptions($countries); ?> <!DOCTYPE html> <html lang="en"> <head> <title>Stats</title> <link rel="stylesheet" href="stylesheets/style.css" /> <!--[if IE]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <? echo $countryOptions; ?> </br></br></br></br></br></br></br></br> <!Later in the HTML for the page <form action="Ctrystats.php" method="post"> <option name="country" value=<? echo $countryOptions;?>Country</option></br></br> <input type="submit" value="Submit Choice"> </form></p> </body> </html>I think I am nearly there so I would appreciate some help to finish this coding. Note: If you make your questions easy to read, then you have better chances of a quality answer. Use [ code ] ] tags. Hey guys, New to the forum and a newer user of PHP / MySQL. I am having trouble with some code I've written up. I don't seem to get any errors when running it, but it's not updating my database the way that it should. hopefully a simple fix. I am thinking that it must be on the MySQL side of things. Couple of things to start. My html form is comprised completely of drop down list inputs. I'm the only user so I thought this would be the easiest approach. Because of that I've made my PHP as follows: Code: [Select] <?php $season = $_POST['season']; $month = $_POST['month']; $day = $_POST['day']; $year = $_POST['year']; $time = $_POST['time']; $event = $_POST['event']; $game = $_POST['game']; $buyin = $_POST['buyin']; $connect = mysql_connect('localhost','root','') or die('can not connect'); if ($connect) { echo "connected to database"; } $db = mysql_select_db('dpl') or die('can not find database'); if ($db) { echo "DPL Selected"; } $query = sprintf("INSERT INTO events (season , month , day , year , time , event , game , buyin) VALUES ('%s' , '%s' , '%s' , '%s' , '%s' , '%s' , '%s' , '%s')", $season , $month , $day , $year , $time , $event , $game , $buyin ); if ($query) { echo "Your event has been added"; } ?> My connection is working, my database is selected and I'm even now getting confirmation that my query is working, but when i go to check my database there are no entries in it? any thoughts? I've tried the drop down variables as both VARCHAR and TEXT inputs in MySQL, but I can't seem to get it to work. Any help is greatly appreciated. This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=347691.0 Hi all, I am a php student and i am doing a project in php. I am doing the project of online attendance register. I am stuck with the part of reports. We need to select three different values from an HTML form and pick the selected rows and wants to display those rows in a table. I have done a code but it is not working. Please help me out of this issue. HTML Form: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> </head> <body><form action="reportpro.php" method="get" name="services"> <table width="447" border="0" align="center" > <tr style="text-align: center"> <td width="441"><table width="481" border="1"> <tr> <td width="216"><div align="center"> SECTION </div></td> <td width="102"><div align="center"> MONTH </div></td> <td width="141"><div align="center"> YEAR </div></td> </tr> <tr> <td><select name="section" id="select"> <option>SERVICES-A</option> <option>SERVICES-B</option> <option>SERVICES-C</option> </select></td> <td><select name="month" id="select"> <option>01</option> <option>02</option> <option>03</option> <option>04</option> <option>05</option> <option>06</option> <option>07</option> <option>08</option> <option>09</option> <option>10</option> <option>11</option> <option>12</option> </select></td> <td><select name="year" id="select"> <option>2014</option> <option>2015</option> <option>2016</option> <option>2017</option> <option>2018</option> <option>2019</option> <option>2020</option> </select></td> </tr> <tr> <td colspan="4"> <center><input name="submit" type="submit" id="submit" formaction="reportpro.php" formmethod="get" value="Search"></center></td> </tr> </table> <p> </p> <p> </p> <p> </p></td> </tr> </table> </form> </body> </html> PHP Code: <!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=utf-8" /> <title>Untitled Document</title> </head> <body> <form action="" method="get"> <table border="1" align="center" > <tr> <td>BOOK NO</td> <td>Name</td> <td>Desigination</td> <td>Section</td> <td>Day</td> <td>Month</td> <td>Year</td> <td>Attendance</td> </tr> <?php $con=mysql_connect("localhost","root",""); mysql_select_db("niy",$con); $m=$_REQUEST['month']; $y=$_REQUEST['year']; $sec=$_REQUEST['section']; $sql="select month='$m', year='$y', sectn='$sec' from attendance "; echo $sql; $res=mysql_query($sql,$con); while($row=mysql_fetch_array($res)) { ?> <tr> <td><?php echo $row[1];?></td> <td><?php echo $row[2];?></td> <td><?php echo $row[3];?></td> <td><?php echo $row[4];?></td> <td><?php echo $row[5];?></td> <td><?php echo $m;?></td> <td><?php echo $y;?></td> <td><?php echo $row[8];?></td> </tr> <?php } ?> </table> </body> </html> //my controller <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class homeController extends Controller { public function index() { $employee = DB::table('employee')->orderBy('id','desc')->get(); $department = DB::table('department')->orderBy('id','desc')->get(); return view('index', ['employee' => $employee , 'department' => $department]); } } //my routes Route::get('index','homeController@index'); //my view using blade temmplating engine @foreach($employee as $emp) <div class="employee"> <b>{{ $emp->name }} </b> <a href="employee/{{ $emp->id }}"> <p class="intro">{{ substr($emp->intro ,0, 50) }}...</p> </a> </div> @endforeach @foreach($department as $dep) <div class="department"> <b>{{ $dep->name }} </b> <a href="department/{{ $dep->id }}"> <p class="desc">{{ substr($dep->description ,0, 100) }}...</p> </a> </div> @endforeach I want to fetch using ajax, how can i do it, teach/help me Hello everyone, I begin in everything web related but I have been programming for years. I tried to code something simple : small Mysql DB (works fine) and to begin a search bar to browse data. I adapted a code that I understood provided here : https://www.cloudways.com/blog/live-search-php-mysql-ajax/. Base principle is simple : as you type in your query, it will pass the text to script.js that will forward this request to ajax.php file. In the ajax.php, a javascript function named “fill()” will pass the fetched results. This function will also display the result(s) into “display” div in the “search.php” file. The problem is that when I type anything it displays, below the search bar, at the moment I type a character: Quote
'; //Fetching result from database. while ($Result = MySQLi_fetch_array($ExecQuery)) { ?> ")'>
instead of the actual answer from my database (no error in the browser console). I tested the SQL query + the user I provide and everything seems fine. Any clue what could be the root cause ? I strongly suspect a mistake in the code as I already corrected one (script.js instead of scripts.js) but I really cannot figure out where. Thanks in advance,
problematic code (ajax.php):
<?php //Including Database configuration file. include "db.php"; //Getting value of "search" variable from "script.js". if (isset($_POST['search'])) { //Search box value assigning to $Name variable. $Name = $_POST['search']; //Search query. $Query = "SELECT Name FROM search WHERE Name LIKE '%$Name%' LIMIT 5"; //Query execution $ExecQuery = MySQLi_query($con, $Query); //Creating unordered list to display result. echo ' <ul> '; //Fetching result from database. while ($Result = MySQLi_fetch_array($ExecQuery)) { ?> <!-- Creating unordered list items. Calling javascript function named as "fill" found in "script.js" file. By passing fetched result as parameter. --> <li onclick='fill("<?php echo $Result['Name']; ?>")'> <a> <!-- Assigning searched result in "Search box" in "search.php" file. --> <?php echo $Result['Name']; ?> </li></a> <!-- Below php code is just for closing parenthesis. Don't be confused. --> <?php }} ?> </ul>
I have a form on our website that a user can fill out for custom product. I want the form data to be 1) stored into a mysql database AND after storing said data, 2) email the same data to our sales department. 1) The form data DOES get stored into mysql database (except for the first two fields, for some weird reason) 2) I added a "mail" section to the php file that stores the data into the database, but it is not working correctly. I have stripped the email portion down to sending just one of the fields in the "message" to make it easier for troubleshooting I have included here, both the form section of the html file, and the formdata.php file that processes the data for your analysis. I am relatively new to php so there are going to be some issues with security, but I can work on those after I get the store & email process to work correctly. Please review my code and see if anyone can be of assistance. I looked through the forums and couldn't find another issue that was the same as mine. If I just overlooked, please tell me the thread post #. Thanks THE FORM WHICH COLLECTS THE DATA ******************************* <form method=POST action=formdata.php> <table width="640" border=0 align="center"> <tr> <td align=right><b>First Name</b></td> <td><input type=text name=FName size=25></td> <td><div align="right"><b>Telephone</b></div></td> <td><input type=text name=Tel size=25></td> </tr> <tr> <td align=right><b>Last Name</b></td> <td><input type=text name=LName size=25></td> <td><div align="right"><b>Fax</b></div></td> <td><input type=text name=Fax size=25></td> </tr> <tr> <td align=right><b>Title</b></td> <td><input type=text name=Title size=25></td> <td><div align="right"><b>Email</b></div></td> <td><input type=text name=Email size=50></td> </tr> <tr> <td align=right><b>Company</b></td> <td><input type=text name=Comp size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Address</b></td> <td><input type=text name=Addr size=25></td> <td><div align="right"><b>Estimated Annual Volume</b></div></td> <td><input type=text name=EAV size=25></td> </tr> <tr> <td align=right><b>City</b></td> <td><input type=text name=City size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>State/Province</b></td> <td><input type=text name=SProv size=25></td> <td><div align="right"><b>Application</b></div></td> <td><input type=text name=Appl size=25></td> </tr> <tr> <td align=right><b>Country</b></td> <td><input type=text name=Ctry size=25></td> <td><div align="right"><b>Type of System</b></div></td> <td><input type=text name=Syst size=25></td> </tr> <tr> <td align=right><b>Zip/Postal Code</b></td> <td><input type=text name=ZPC size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td><div align="right"><strong><font color="#FFFF00" face="Arial, Helvetica, sans-serif">COIL DESIGN</font></strong></div></td> <td><font color="#FFFF00" face="Arial, Helvetica, sans-serif"><strong>PARAMETERS</strong></font></td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Primary Resistance (ohms)</b></td> <td><input type=text name=Pres size=25></td> <td><div align="right"><b>Primary Inductance (mH)</b></div></td> <td><input type=text name=Pind size=25></td> </tr> <tr> <td align=right><b>Secondary Resistance (ohms)</b></td> <td><input type=text name=Sres size=25></td> <td><div align="right"><b>Secondary Inductance (H)</b></div></td> <td><input type=text name=Sind size=25></td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Peak Operating Current (Amps)</b></td> <td><input type=text name=POC size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Output Energy (mJ)</b></td> <td><input type=text name=Egy size=25></td> <td><div align="right"><b>Output Voltage (kV)</b></div></td> <td><input type=text name=Volt size=25></td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b># HV Towers per Coil</b></td> <td><input type=text name=TPC size=25></td> <td><div align="right"><b># of Coils per Package</b></div></td> <td><input type=text name=CPP size=25></td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <th colspan=4><b>Please enter any additional information he </b></th> </tr> <tr> <th colspan=4><textarea name=Mess cols=50 rows=10 id="Message"></textarea></th> </tr> </table> </dl> <div align="center"> <p> <input type=hidden name=BodyTag value="<body bgcolor="#484589" text="#FFFFFF" link="#FFFF00" alink="#FFFFFF" vlink="#FF7F00">"> <input type=hidden name=FA value=SendMail> </p> <p><font color="#FFFF00" face="Arial, Helvetica, sans-serif"><strong>PLEASE MAKE SURE ALL INFORMATION<br> IS CORRECT BEFORE SUBMITTING</strong></font></p> <p> <input type=submit value="Submit Form"> </p> </div> </form> THE FILE THAT PROCESSES THE FORM DATA (formdata.php) *********************************************** <?php $con = mysql_connect("localhost","XXX","XXX"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("customform", $con); $sql="INSERT INTO formdata (Fname, Lname, Title, Comp, Addr, City, SProv, Ctry, ZPC, Tel, Fax, Email, EAV, Appl, Syst, Pres, Pind, Sres, Sind, POC, Egy, Volt, TPC, CPP, Mess) VALUES ('$_POST[Fname]','$_POST[Lname]','$_POST[Title]','$_POST[Comp]','$_POST[Addr]','$_POST[City]','$_POST[SProv]','$_POST[Ctry]','$_POST[ZPC]','$_POST[Tel]','$_POST[Fax]','$_POST[Email]','$_POST[EAV]','$_POST[Appl]','$_POST[Syst]','$_POST[Pres]','$_POST[Pind]','$_POST[Sres]','$_POST[Sind]','$_POST[POC]','$_POST[Egy]','$_POST[Volt]','$_POST[TPC]','$_POST[CPP]','$_POST[Mess]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "Your Information Was Successfully Posted"; mysql_close($con); $to = "recipient email address here"; $subject = "Custom Form"; $email = $_POST['Email'] ; $message = $_POST['Comp'] ; $headers = "From: $Email"; $sent = mail($to, $subject, $message, $headers) ; if($sent) {print "Your mail was sent successfully"; } else {print "We encountered an error sending your mail"; } ?> Hi... I have query in highlighting null data using this code: Code: [Select] <?php include 'config.php'; $currentEmpID = $_SESSION['empID']; if(!isset($_POST['Regsubmit_'])){ $DATE1 = $_GET['Regfirstinput']; $DATE2 = $_GET['Regsecondinput']; $sql = "SELECT DISTINCT IF(ISNULL(a.LOG_IN), 'rdc', '') AS LOGIN_CLASS, IF(ISNULL(a.LOG_OUT), 'rdc', '') AS LOGOUT_CLASS, a.EMP_ID, CONCAT(LASTNAME, ', ' , FIRSTNAME) AS FULLNAME, a.LOG_IN, a.LOG_OUT FROM $ATTENDANCE.attendance_build AS a JOIN $ADODB_DB.employment em ON (a.EMP_ID = em.EMP_NO AND em.STATUS IN ('Reg Operatives', 'Reg Staff')) WHERE LOG_IN BETWEEN '$DATE1' AND '$DATE2' OR ISNULL(LOG_IN) OR ISNULL(LOG_OUT)"; $DTR = $conn3->GetAll($sql); $smarty->assign('attendance', $DTR); } $smarty->display('header_att.tpl'); $smarty->display('RegAttendance.tpl'); $smarty->display('footer.tpl'); ?> and here is the tpl code: Code: [Select] {section name=att loop=$attendance} <tr> <td colspan="2">{$attendance[att].EMP_ID}</td> <td colspan="2">{$attendance[att].FULLNAME}</td> <td colspan="2" class="{$attendance[att].LOGIN_CLASS}">{$attendance[att].LOG_IN|date_format:"%d-%m-%Y %I:%M %p"}</td> <td colspan="2" class="{$attendance[att].LOGOUT_CLASS}">{$attendance[att].LOG_OUT|date_format:"%d-%m-%Y %I:%M %p"}</td> </tr> {sectionelse} <tr><td colspan="1">No DATA</td></tr> {/section} this code highlight the null value of login or logout or both. this is the css: Code: [Select] .rdc {background-color:#ff0000;} Now, I need to revised my query statement, because i have separate code for adding attendance if the employee has no attendance or no login or no logout. I just want to happen is if the employee is already add his attendance in NRS table or should I said if the LOG_IN in attendance table is equal to TIME_IN in NRS table the data will have a color yellow. For Example: I have this data in attendance table: EMP_ID = 012012 LOG_IN = NULL LOG_OUT = 2011-12-12 13:35:00 I will his attendance in NRS table to have his attendance: EMP_NO = 012012 TIME_IN = 2011-12-12 05:35:00 TIME_OUT = 2011-12-12 13:35:00 In my above query the LOG_IN has a background color of RED. I want to happen is if I add his attendance in NRS the EMP_NO, LOG_IN, LOGOUT will have a color to notice that it is already have in NRS. Because theirs a scenario that the employee has no login or no logout or both. Feel free to ask me if my explanation is not clear to you. Thank you in advance I'm experimenting out premade codes and trying to make them some how work the way I want to. This is "my" image uploader. For the uploader is suppose to find the image AND the code stored in mysql, but it doesn't seem to find it. any problem? <?php $link = mysql_connect("localhost", "mcd", "whatanicepassword"); mysql_select_db("mcd", $link); if (!isset($_POST["code"])) { die ("Error: Not all fields complete"); } $limit_size=5120; $target = "skin/"; $target = $target . basename( $_FILES['uploaded']['name']); $ok=1; $filelol = $_FILES['uploaded']['name']; $file_size=$_FILES['uploaded']['size']; $filecheck = "skin/".$filelol; //This is our size condition if ($file_size >= $limit_size) { echo "Your file is too large.<br>"; $ok=0; } if (file_exists($filecheck)) { } else {echo $filelol." does not exist in the database. Please upload at the main site.<br>"; $ok=0;} // username and password sent from Form $uploaded=mysql_real_escape_string($_POST['uploaded']); $code=mysql_real_escape_string($_POST['code']); $checkquery = mysql_query("SELECT * FROM user_list WHERE uploaded = '$uploaded' AND code = '$code'") or die("Error : " . mysql_error()); $num_rows=mysql_num_rows($checkquery); if ($num_rows < 1 ) { echo 'File not found in MySQL<br><br><br>'; $ok=0; } else {echo 'YES!';} //This is our limit file type condition if (($_FILES["uploaded"]["type"] != "image/png")) { echo "You may only upload PNG files.<br>"; $ok=0; } if ($ok==0) { Echo "Sorry your file was not uploaded<br>"; } //If everything is ok we try to upload it else { if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file ".$filelol." has been uploaded"; } else { echo "Sorry, there was a problem uploading your file."; } } ?> The Business Logic is: If product is already purchased, upgrade the product I have a customer input form to get information, along with some fields which should be auto populated based on what the customer chooses. Screen Shot:
https://i.stack.imgur.com/Fkyim.png When we come to the shipping cost I am getting it from Magento, using a PHP function. form :
https://paste.ofcode.org/335FVUhpBGbazQtrcPLVQUs sp_cost.php
https://paste.ofcode.org/hvG2sP9TW9CEPgMMuKXNuw $results = getShippingEstimate('14419','1',"IN","642001"); How can i get country and zipcode from the user entry and return the shipping cost?
Edited April 26, 2019 by aveeva I am working on a project where I want a select form to display information from a MySQL table. The select values will be different sports (basketball,baseball,hockey,football) and the display will be various players from those sports. I have set up so far two tables in MySQL. One is called 'sports' and contains two columns. Once called 'category_id' and that is the primary key and auto increments. The other column is 'sports' and contains the various sports I mentioned. For my select menu I created the following code. <?php #connect to MySQL $conn = @mysql_connect( "localhost","uname","pw") or die( "You did not successfully connect to the DB!" ); #select the specified database $rs = @mysql_SELECT_DB ("test", $conn ) or die ( "Error connecting to the database test!"); ?> <html> <head>Display MySQL</head> <body> <form name="form2" id="form2"action="" > <select name="categoryID"> <?php $sql = "SELECT category_id, sport FROM sports ". "ORDER BY sport"; $rs = mysql_query($sql); while($row = mysql_fetch_array($rs)) { echo "<option value=\"".$row['category_id']."\">".$row['sport']."</option>\n "; } ?> </select> </form> </body> </html> this works great. I also created another table called 'players' which contains the fields 'player_id' which is the primary key and auto increments, category_id' which is the foreign key for the sports table, sport, first_name, last_name. The code I am using the query and display the desired result is as follows <html> <head> <title>Get MySQL Data</title> </head> <body> <?php #connect to MySQL $conn = @mysql_connect( "localhost","uname","pw") or die( "Err:Db" ); #select the specified database $rs = @mysql_SELECT_DB ("test", $conn ) or die ( "Err:Db"); #create the query $sql ="SELECT * FROM sports INNER JOIN players ON sports.category_id = players.category_id WHERE players.sport = 'Basketball'"; #execute the query $rs = mysql_query($sql,$conn); #write the data while( $row = mysql_fetch_array( $rs) ) { echo ("<table border='1'><tr><td>"); echo ("Caetegory ID: " . $row["category_id"] ); echo ("</td>"); echo ("<td>"); echo ( "Sport: " .$row["sport"]); echo ("</td>"); echo ("<td>"); echo ( "first_name: " .$row["first_name"]); echo ("</td>"); echo ("<td>"); echo ( "last_name: " .$row["last_name"]); echo ("</td>"); echo ("</tr></table>"); } ?> </body> </html> this also works fine. All I need to do is tie the two together so that when a particular sport is selected, the query will display below in a table. I know I need to change my WHERE clause to a variable. This is what I need help with. thanks Hi, I have come up with the following code, I need it to get the details of several scattered products and echo the results, the trick is I don't want it to echo the results one after the other... I want to have the products scattered between unique text on the page but don't want to run the query several times for performance reasons. E.g.- PAGE to look like this: $Product_1 unique text/images $Product_2 $Product_3 unique text/images $Product_4 Current Code: Code: [Select] <? $result = mysql_query("SELECT * FROM products where Product_ID IN (475, 465, 234, 567, 845)"); while($row = mysql_fetch_array($result)) { $x = "1"; while ($x<=3) { echo $x; $Product = "Product_"; $Product = $Product.$x; echo $Product; $Product = $row['Product_ID']; echo $Product; $x++; echo $x; } } At the moment it returns the following results: Quote 1 Product_1 465 2 2 Product_2 465 3 3 Product_3 465 4 1 Product_1 475 2 2 Product_2 475 3 3 Product_3 475 4 A few problems... In Blue... it duplicates for product 465 In Red... It repeats again for 475 Also.... it starts with 465, but I want it to go in order as how it appears - $result = mysql_query("SELECT * FROM products where Product_ID IN (475, 465, 234, 567, 845)"); so should start with 475 I want to get the following result: Quote 1 Product_1 475 2 2 Product_2 465 3 3 Product_3 234 4 4 Product_4 567 4 (and so on.....) If anyone could provide me assistance with my troubled 'while loop' statement that would be much appreciated! Not really sure what to ask because I don't know what the problem is. Maybe just need a fresh set of eyes to find out whats wrong. I am trying selecting content from a database table but its not working. I am not getting any errors just a blank screen where the content should be displayed. html Code: [Select] <table> <tbody> <tr> <th>Topic</th> <th>Name</th> <th>Date</th> </tr> <?php include 'server/forum.php'; ?> </tbody> </table> php Code: [Select] <?php require_once('load_data.php'); $con = mysql_connect($db_host, $db_user, $db_pwd); if (!$con) { die('Could not connect to database: ' . mysql_error()); } $dbcon = mysql_select_db($database); if (!$dbcon) { die('Could not select database: ' . mysql_error()); } $sql = "SELECT * FROM $table ORDER BY id"; $result = mysql_query($sql) or die("Error ". mysql_error(). " with query ". $sql); if (!$result) { die("Query to show fields from table failed:".mysql_error()); } $row = mysql_fetch_array($result) while($row) { echo '<tr>'; echo '<td class="forumtd"><b>'; echo '<a href="topic.php?id='.$row['id'].'">'.stripslashes(htmlspecialchars($row['topic'])).'</a>'; echo "</b></td>"; echo '<td class="forumtd"><em>'; echo stripslashes(htmlspecialchars($row['name'])); echo "</em></td>"; echo '<td class="forumtd">'; echo date("l M dS, Y", $row['date']); echo "</td>"; echo "</tr>"; } mysql_close($con); ?> Hi, This is my first post in this forum and am a PHP beginner. I have written a script in php and need to use echo to see the values of variables etc. However I dont get the output on the screen while using echo . I am using Xampp server with Apache. The startup.html file code is
<!DOCTYPE HTML>
</head>
and the test.php code is <?php
$lat = $_REQUEST['latitude'];
echo 'latitude- '.$lat . ', longitude- ' . $lon; Please help regards
Sanjish Not sure why this isnt working. Code: [Select] <?php session_start(); ?> <!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> <script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script> <script type="text/javascript">bkLib.onDomLoaded(nicEditors.allTextAreas);</script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <LINK REL=StyleSheet HREF="inc/dyn_style.css" TYPE="text/css" MEDIA=screen /> <?php ?> <?php include('logic.inc'); mysqlConnect(); ?> <script type="text/javascript" src="bbeditor/ed.js"></script> <link rel="stylesheet" type="text/css" href="dyn_style.css" /> <title> Social </title> <script type="text/javascript"> function changeTitle(title) { document.title = title; } </script> </head> <body> <?php $inc = 'new_story.php'; $view = 'Newest '; $by = 'added'; $where = " "; $where2 = " "; $order = "ASC"; $gen = "All"; $rat = 'All'; $blerg = ""; $sort = 'newest'; //---------------------------------------------------------------------- if(isset($_GET['sub'])) { $sort = $_GET['sort']; switch($sort) { case "Most Popular"; $by = 'views'; $view = 'Most Popular '; $order = 'DESC'; break; case "Most Reviewed"; $view= 'Most Reviewed '; $by = 'reviews'; $order = 'DESC'; break; case "Newest"; $by = 'added'; $view = 'Newest'; $order = 'ASC'; break; } $genre = mysql_real_escape_string($_GET['cat']); $rating = mysql_real_escape_string($_GET['rat']); if($gen == 'All') { $where = " "; $blerg = ""; } else { $where = "WHERE cat='$gen'"; } if ($rat == "All") { $where2 = ' '; $blerg = 'AND'; } else { $where2 = $blerg ." rating = '$rat' "; } } //---------------------------------------------------------------------- ?> <?php serch(); ?> <form action="story.php" method="get"> <label id='inline'> Order By: </label> <select name='sort'> <option selected='yes' label='Currently Selected' > <?php echo $view; ?> </option> <option> Newest </option> <option> Most Popular</option> <option> Most Reviewed </option> </select> <input type='hidden' value='spec_view' name='p' /> <label id='inline'> Genre/Catagory: </label> <select name='gen'> <option selected='yes' label = 'Selected Genre - <?php echo $gen; ?>'> <?php echo $gen; ?> </option> <option> All </option> <option> Fantasy </option> <option> Adventure </option> <option> Science Fiction</option> <option> Drama</option> <option> Fable </option> <option> Horror</option> <option> Humor</option> <option> Realistic Fiction </option> <option> Tall Tale</option> <option> Mystery </option> <option> Mythology </option> <option> Poetry </option> <option> Shorty Story </option> <option> Romance </option> </select> <label id='inline'> Rating: </label> <select name='rat'> <option selected='yes' label = "Selected Genre - <?php echo $rat; ?>"> <?php echo $gen; ?> </option> <option> All </option> <option> C </option> <option> C13 </option> <option> YA </option> <option> A </option> </select> <input type='submit' value='Go!' name = 'go' /> </form> <?php $query = " SELECT * FROM story_info ORDER BY $by $order $where $where2 "; echo $query; $select = mysql_query($query) or die(mysql_error()); while($rows = mysql_fetch_assoc($select)) { $viewsdb = $rows['views']; $titledb = $rows['title']; $userdb = $rows['user']; $catdb = $rows['cat']; $ratdb = $rows['rating']; $id_db = $rows['story_id']; $sumdb = shorten($rows['sum']); echo "<h3><a href='?p=page&id=$id_db'> $titledb </a> </h3>"; echo "<div id='fun_info'>"; echo "$sumdb <br />"; echo "By <a href='?p=profile&user=$userdb'> $userdb </a> <br /> "; echo "$viewsdb Views | Rated: $ratdb | Catagory: <a href='?p=cat_view&gen=$catdb'> $catdb </a> </div>"; } ?> </div> </body> </html> Hello. I'm a newbie so sorry if this isn't the best forum to post my problem.
I am using a MySQL and PHP to create a web app. I have authentication, and I can register users. I also have a form that users provide information and it is successfully inserting data into a table in my database.
I will use fictional fields for my database table called meal_info:
username
dateStartedDiet
numberMealsPerDay
costPerMeal
Problem: Select user-specific data from the MySQL database, using Session username to select only the current user's data, then display it and do some calculations.
Here is thecode at the top, and I am fairly sure it's working:
session_start(); //execute commone code
require("common.php"); //includes code to connect to database, etc.
if(empty($_SESSION['user'])) Hi there, I'm having a problem with updating a record with an UPDATE mysql query and then following that query with a SELECT query to get those values just updated. This is what I'm trying to do...I'd like a member to be able to complete a recommended task and upon doing so, go to a page in their back office where they can check off that task as "Completed". This completed task would be recorded in their member record in our database so that when they return to this list, it will remain as "Completed". I'm providing the member with a submit button that will call the same page and then update depending on which task is clicked as complete. Here is my code: Code: [Select] $memberid = $_SESSION['member']; // Check if form has been submitted if(isset($_POST['task_done']) && $_POST['task_submit'] == 'submitted') { $taskvalue = $_POST['task_value']; $query = "UPDATE membertable SET $taskvalue = 'done' WHERE id = $memberid"; $result = mysqli_query($dbc, $query); } $query ="SELECT task1, task2, task3 FROM membertable WHERE id = $memberid"; $result = mysqli_query($dbc, $query); $row = mysqli_fetch_array($result, MYSQLI_ASSOC); $_SESSION['task1'] = $row['task1']; $_SESSION['task2'] = $row['task2']; $_SESSION['task3'] = $row['task3']; ?> <h4>Task List</h4> <table> <form action="" method="post"> <tr> <td>Task 1</td> <td><?php if($_SESSION['task1'] == 'done') {echo '<div>Completed</div>';} else{ echo '<input type="submit" name="task_done" value="Mark As Completed" />';} ?></td> </tr> <input type="hidden" name="task_value" value="task1" /> <input type="hidden" name="task_submit" value="submitted" /> </form> <form action="" method="post"> <tr> <td>Task 1</td> <td><?php if($_SESSION['task1'] == 'done') {echo '<div>Completed</div>';} else{ echo '<input type="submit" name="task_done" value="Mark As Completed" />';} ?></td> </tr> <input type="hidden" name="task_value" value="task2" /> <input type="hidden" name="task_submit" value="submitted" /> </form> <form action="" method="post"> <tr> <td>Task 1</td> <td><?php if($_SESSION['task1'] == 'done') {echo '<div>Completed</div>';} else{ echo '<input type="submit" name="task_done" value="Mark As Completed" />';} ?></td> </tr> <input type="hidden" name="task_value" value="task3" /> <input type="hidden" name="task_submit" value="submitted" /> </form> </table> The problem that I am having is that the database is not updated with the value "done" but after submission, the screen displays "Completed" instead of "Mark As Completed". So the value is being picked up as "done", but that is why I have the SELECT after the UPDATES, so that there is always a current value for whether a task is done or not. Then I refresh and the screen returns the button to Mark As Complete. Also, when I try marking all three tasks as, sometimes all three are updated, sometimes only one or two and again, I leave the page or refresh and the "Marked As Completed" buttons come back. Bizarre. If anyone can tell me where my logic is going wrong, I would appreciate it. I'm not sure what I'm doing wrong here... This is my index <html <head> <title>Admin applications</title> </head> <body text="#000000"> <center> <?php include("connect.php"); echo "<table cellpadding='3' cellspacing='2' summary='' border='3'>"; echo "<tr><td>Real name:<br><br>"; echo $row['real_name']; echo "</td><td>Age:<br><br>"; echo $row['age']; echo "</td><td>In-Game Name:<br><br>"; echo $row['game_name']; echo "</td><td>Steam ID:<br><br>"; echo $row['steamid']; echo "</td><td>Agreement:<br><br>"; echo $row['agreement']; echo "</td><td>Will use vent:<br><br>"; echo $row['vent']; echo "</td><td>Activity:<br><br>"; echo $row['activity']; echo "</td><td>Why this person wants to be an admin:<br><br>"; echo $row['why']; echo "</td></tr></table>"; ?> </center> </body> </html> and this is my database connect <?php $database="admin"; mysql_connect ("localhost", "root", "waygan914"); @mysql_select_db($database) or die( "Unable to select database"); mysql_query("SELECT * FROM applications"); ?> The database table "applications" has 8 fields, and 2 records, but when I view the page i get the table but no data: I am managing a shop website which is using php and mysql for data. The website has a section that will display the related products with the one that you are watching. Now my problem is that if there are more than 5 items it will continue to display all the items in one row with the consequent that the page will not display well. I need to find a way to begin a new row after the 5th item so it will display 5 items in each row. this is my current code that is responsible for showing the related items. There is also a picture attached with the problem. while ($row = mysql_fetch_array($retd)) { $code = $row["code"]; $name = $row["name"]; echo("<td width=150 align=center>"); echo ("<a href=../products/info.php?scode=$code><img src=pictures/$code.gif border=0 alt=Item $name</a>"); echo ("<br><a href=../products/info.php?scode=$code><span class=fs13>$name</span></a>"); echo("</td>"); } Does anyone know how can I do this? Morning all, and Evening everyone else. Im using the following Query to display information from a table Code: [Select] <? include "config.php"; $query1="Select *,DATE_FORMAT(date_posted,'%W,%d %b %Y') as thedate FROM article WHERE DATE_SUB(CURDATE(),INTERVAL 30 DAY) ORDER BY date_posted DESC LIMIT 1 "; $blogarticles = mysql_query($query1) or die(mysql_error()); $num = mysql_num_rows($blogarticles); ?> What I am wanting to find out, is as the blog post itself could be pages long at times, is the anyway that further down the page where I actually call the data up onto the page itself I can limit how much of it is displayed? Ive succesfully added a limit to how many records are shown with the "DES LIMIT 1", is there something I can add to my query, or further down in my displaying table (which I will code just below here) to limit the lines/characters on display until the full article is opened? Display table: Code: [Select] <table width="75%" border="0" cellspacing="1" align="left"> <tr> <td> </td> </tr> <tr> <td> </td> </tr> <? if($num > 0){ while($row_articles = mysql_fetch_assoc($blogarticles)){ ?> <tr class="title"> <td><?=$row_articles['title'];?> </td> </tr> <tr> <td> </td> </tr> <tr class="tbody"> <td><?=$row_articles['comments'];?></td> </tr> <tr> <td> </td> </tr> <tr class="links"> <td>Date posted: <?=$row_articles['date_posted'];?> | <a href="comments.php?aid=<?=$row_articles['artid'];?>&cid=<?=$row_articles['categoryID'];?>">Comments(<? //echo $row_articles['artid']; //$thenum=row_articles['artid']; $getcomments = "SELECT * FROM article WHERE artchild='".$row_articles['artid']."'"; if(!$theResult=mysql_query($getcomments)){ echo mysql_error(); }else{ $num_comments=mysql_num_rows($theResult); echo $num_comments; } ?>) </a></td> </tr> <tr class="links"> <td> </td> </tr> <tr class="links"> <td> </td> </tr> <? } }else{ ?> <tr><td><p>There are no articles available at present</p></td></tr> <? } ?> <tr> </tr> </table> Just to clarify 'comments' is the table field that holds the blog data, it also holds comments on the blog, but the child ID is what differentiates them from one another. Thanks in advance for your help ladies & gents Tom |