I am new to PhP and MySQL and now having trouble displaying certain records. I have records pf list of students and their year level stored in a database. I was able to display all of them in a webpage. Now I have one textbox and a button and what I wanted to do is when I enter for example "1" on the textbox and click the button, what will appear on my page will be the records of all the first year students only.
Somehow I need to change it so that when the year is posted back then it changes the sql to limit the information displayed.
Any suggestions or links to some examples will be much appreciated. Here is my code.
<form name="form1" method="post" action="">
<div align="center">
<?php
include("dbcon.php");
$query="select * from student order by year, studname";
$result=#mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result)>0)
{
?>
<label>
<input type="text" name="txtyear" id="txtyear">
<input type="submit" name="btnyear" id="btnyear" value="Submit">
</label>
<table width="75%" border="1">
<tr>
<td align="center" width="20%"><strong>Student Number</strong></td>
<td align="center" width="27%"><strong>Name</strong></td>
<td align="center" width="23%"><strong>Course</strong></td>
<td align="center" width="30%"><strong>Year Level</strong></td>
</tr>
<?php
while($row=mysql_fetch_array($result))
{echo "<tr>";
echo "<td>".$row['studno']."</td>";
echo "<td>".$row['studname']."</td>";
echo "<td>".$row['course']."</td>";
echo "<td>".$row['year']."</td>";
echo "</tr>";
}
?>
</table>
<?php
}
else
echo "no records found";
?>
</div>
</form>
You need a WHERE clause. A very basic example might look like this:
$year = mysql_real_escape_string($_POST['year']);
$query = SELECT * FROM student WHERE year = $year ORDER BY studname";
NB: Look into the PHP MySQLi extension. These functions are almost identical to their mysql equivalent, but come with numerous improvements.
Also, you would likely want to improve the validation of the $_POST['year'] field. Ensuring that it is an integer with is_int() wouldn't be a bad idea. You could also typecast it with (int) like (int) $year = mysql_real_escape_string($_POST['year']); and then perform the query if the year isn't 0. Perhaps you know all this already... or perhaps I'm getting ahead of myself. Either way, I'll stop. :)
You can find more info about Mysql select query syntax on
http://dev.mysql.com/doc/refman/5.1/en/select.html.
Also don't use # for errors suppression in php-code. Because of it will slow your script. Try to process such situation manually. In this case (#mysql_query($query)) it seems it doesn't make sense anyway.
Related
I'm a novice at PHP, so I'm having trouble with this task:
In a nutshell, I want to run a query and have the results returned in an array, and then allow the users to choose one selection from the array, and have a numerical value get passed on to another php page to be used in additional computations.
Here's my basic code so far:
<?php
include 'mysql_connect.php';
$Choices = mysqli_query ($server_connect, "SELECT * FROM Database
WHERE FLOOR (Item_number) = '$StockCategory' AND name='$name'")
or die(mysqli_error ($server_connect));?>
<table cellspacing="1" cellpadding="2" width="20%" border="1">
<?php while ($selectionlist = mysqli_fetch_array($Choices)){
$orderchoicenumber++;
$selectnumber = $matchups['Item_number']; ?>
<tr>
<td> <?php echo $selectionlist['size']; ?> </td>
<td> <?php echo $selectionlist['color'];?> </td>
<td> <?php echo $selectnumber;?></td>
<td> <?php echo $orderchoicenumber;?>
<?php }?>
</td></tr>
Enter your selection:
<form name ="selectionprocess" action="precheckout.php" method="POST">
<input type="text" maxlength="2" name="enterselection" >
<input type="hidden" name="selectnumber" value="<?php echo $selectnumber;?>">
</form>
<input type="submit" name="formSubmit" value="Submit" >
and here's the code on the destination page [precheckout.php]:
<?php
$name = isset($_POST["name"]) ? $_POST["name"] : $_SESSION['name'];
$mode = $_POST["select"];
$SelectNumber = $_POST["selectnumber"];
$Item_number = $SelectNumber;
?>
<p>Hello <?php echo $name; ?>!</p> <br>
OK, the item number of what you want is--- <?php echo $Item_number;?>
Of course, this means the number of results from the myfetcharray will vary.
The first aspect works pretty well. In this example, here's the output I receive (in table format):
Enter your selection: _____
4x6 navy 90515.01 1
4x8 mauve 90515.07 2
6x8 auburn 90515.03 3
2x4 black 90515.02 4
5x7 aqua 90515.08 5
The selection number is in the far right column. (The decimal number is the identifying Item Number in my SQL database. I'd like to not display this number in the final program, and even though I suppose I could make users enter in that number instead of a selection number in order to proceed, it's not a very user-friendly approach.)
The problem arises when I try to enter in a selection number (in this case, 1-5). The program successfully carries over a numerical value to the precheckout page [value="<?php echo $selectnumber;?>">], but it's always the final value spit out by the myfetcharray (i.e. in the lowest row). In this example, the output on the next page would be:
Hello, John!
OK, let's see how you did, because this item number is--- 90515.08
...no matter which matchup number was selected.
Ideally, I would like a more user-friendly way of selecting a row, rather than typing in a selection number. I've tried the radio button approach, but the best I could do was to successfully pass along a value of "on" to the next page instead of a numerical value. I'm willing to use other languages, though I don't know if they would play nice with PHP (i.e., Javascript).
Any thoughts on this would be appreciated. Thanks!
First off: a more user-friendly approach could be a dropdown menu: Try this:
<select>
<?php while ($selectionlist = mysqli_fetch_array($Choices)){
$orderchoicenumber++;
$selectnumber = $matchups['Item_number']; ?>
<option value="<?php echo $selectnumber; ?>">
<?php echo $selectionlist['size'] . " " . $selectionlist['color'] . " " . $selectionlist['color'] . " " . $selectnumber . " " . $orderchoicenumber; ?>
</option>
<?php }?>
</select>
All your PHP code is executed on the server when the page loads and any user interaction with the page is 'client side' (on the user's machine) so you're right: it needs another language to update your selectnumber hidden input. jQuery (a javascript library) is your best bet here.
You must already have some javascript on your page to post your form to precheckout.php - can you add that to your question, then I'll be able to guide you on the bits you need to change?
I have 2 tables, one with data and other is blank in same database.
a)- Tables "cusrec" is main and contains data in it.
b)- Tables "order" is empty and I want to insert the data in it.
I tried to fetch data from table "cusrec" and insert it into "order", when I echo, it shows the data of table "cusrec" but it is not inserting into table "order". Both tables are in same database.
Code is:
<?php
mysql_connect("localhost","root","");
mysql_select_db('dobhighat');
if(isset($_GET['search'])){
$srch = $_GET['srch'];
$que=mysql_query("select * from cusrec where custid='$srch' OR mobile='$srch'");
$ftch=mysql_fetch_array($que);
$scustid=$ftch['custid'];
$sname=$ftch['name'];
$smobile=$ftch['mobile'];
$totcloth=$ftch['clothpackage'];
if(isset($_POST['confirm']))
{
$ordernum=$_REQUEST['ordernum'];
$orderdate=date('d/m/y');
$ordercloth=$_REQUEST['ordercloth'];
$clothrem=$totcloth-$ordercloth;
$abc=mysql_query("insert into order(custid,name,mobile,totcloth,orderno,orderdate,ordercloth,clothrem)values('$scustid','$sname','$smobile','$totcloth','$ordernum','$orderdate','$ordercloth','$clothrem')");
}
}
?>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<?php $orddate=date('d/m/y'); ?>
<form name="form 1" action="" method="get">
<div align="right"><input type="text" name="srch" placeholder="Search by Id or Mobile" size="25">
<input type="submit" name="search" value="Search"></div>
</form>
<form name="form2" action="" method="post">
<table>
<tr>
<td width="103">Order Date</td>
<td width="94">Customer Id</td>
<td width="53">Name</td>
<td width="71">Mobile</td>
<td width="144">Order No.</td>
<td width="144">No.of Clothes</td>
</tr>
<tr>
<td><?php echo $orddate; ?></td>
<td><?php echo #$ftch['custid']; ?></td>
<td><?php echo #$ftch['name']; ?></td>
<td><?php echo #$ftch['lname']; ?></td>
<td><?php echo #$ftch['mobile']; ?></td>
<td><input type="text" name="ordernum" required></td>
<td><input type="text" name="ordercloth" required></td>
</tr>
<tr><td colspan="8"><center><input type="submit" name="confirm" value="Confirm"></center></td></tr>
</table>
</form>
</body>
</html>
Help is needed
Forget all I said about the forms and the structure of the document (although it could be useful eventually as I don't know how reliable is that GET and POST).
I am a dodo and just realized that your table name is order. ORDER is a reserved keyword in SQL and it's the reason why your SQL statement is incorrect! Just put the name between ` and it will work:
$abc=mysql_query("insert into `order`(custid,name,mobile,totcloth,orderno,orderdate,ordercloth,clothrem)values('$scustid','$sname','$smobile','$totcloth','$ordernum','$orderdate','$ordercloth','$clothrem')");
Or you may want (if possible) to rename the table in order to avoid confusion and future problems.
This doesn't mean that the code is perfect. You should still look at the recommendations by the other users and the list below, and improve it. Specially the security concerns.
Once you fix that, the insert will work; but there are still many things that you need to fix:
You should not use mysql functions and move to mysqli or PDO.
You should sanitize all the values that go to the database or to the page:
Your code is subject to SQL injection (see comments in question).
Your code is subject to XSS (see comments in question).
The doctype in your page is incorrect (if you want html5, it should be <!doctype html> and not <!doctype>.
Names and IDs must not have white spaces in them (read this for name and id notation: http://www.w3.org/TR/html401/types.html#type-name)
As stated in other answers, the SQL statement could be improved. The solution that you have may work fine (I don't find any apparent error) but it is not ideal and may present performance problems and other type of problems (e.g.: if two different users have the same phone number).
And there are probably more things that I didn't notice as I just looked quickly through the code.
Have you thought of doing an insert from select? Something like...
INSERT INTO ORDER
( custid, name, mobile, otherFields, etc... )
SELECT same, ordered, fields, as, theInsert
from custrec where custid='$srch' OR mobile='$srch'
The only issue I see with your select where clause is that you could be getting multiple customers via the OR mobile='%srch' and cause duplicate orders.
You can do it directly from SQL
INSERT INTO order
( custid,
name,
mobile,
totcloth,
orderno,
orderdate,
ordercloth,
clothrem)
SELECT
custid,
name,
mobile,
totcloth,
orderno,
orderdate,
ordercloth,
clothrem
FROM cusrec
WHERE custid='$srch' OR mobile='$srch'"
;
You just need to match the column with from table to to table
I think to insert and fetch the same data we can do it by using the below-mentioned code for PHP MYSQLI.
$id=trim($_POST['id']);
$email=trim($_POST['email'];
$env_name=trim($_POST['env_name'];
$sql="INSERT INTO integration (id,email,env_name) VALUES ($id,$email'$envName')";
if(mysqli_query($conn,$sql)){
$selectSql="SELECT id,email,env_name from integration WHERE id=$id and email='$email'";
$result=mysqli_query($conn,$selectSql){
if($result){
$row=mysqli_fetch_array($result, MYSQLI_ASSOC);
return $row;
}
}
}
I haven't designed a website for about 3 years now, so I am quite rusty to say the least. I have to fall back on Dreamweaver CS5 to help me out.
Right...
I want a page for news, and the user/customer will select from a dropdown menu the date (JAN, FEB, MAR, APR etc...) Now, I have a table in my mySQL database called 'news' where each row is referenced by these dates. I have already set up a Dynamic List for the date (a dropdown list.)
What I want is for the customer to select the date from the dropdown, and for the results to show in a Recordset underneath. I am assuming that the SQL query needs to be wrote something along the lines of:
SELECT date, subject, message
FROM news
WHERE date = $ XXXXXDROPDOWNLIST XXX $
As you can see, I made the last line up because I can't quite grasp how it should function. I am thinking that the dropdown list needs to be in a form which will POST and the table of results needs to be in a form which will GET.
Could somebody more technical than me please enlighten my dillema?
Thanks, Rob.
Code
mysql_select_db($database_rcc, $rcc);
$query_dropdowndate = "SELECT DATE_FORMAT(date, '%M %Y') AS FORMATTEDDATE FROM news GROUP BY FORMATTEDDATE ORDER BY Date DESC ";
$dropdowndate = mysql_query($query_dropdowndate, $rcc) or die(mysql_error());
$row_dropdowndate = mysql_fetch_assoc($dropdowndate);
$totalRows_dropdowndate = mysql_num_rows($dropdowndate);
mysql_select_db($database_rcc, $rcc);
$query_newsitems = "SELECT `Date`, Subject, Message FROM news WHERE date = $_POST['dropdowndate']";
$newsitems = mysql_query($query_newsitems, $rcc) or die(mysql_error());
$row_newsitems = mysql_fetch_assoc($newsitems);
$totalRows_newsitems = mysql_num_rows($newsitems);
?>
<form id="choosedate" name="choosedate" method="post" action="#">
<label for="dropdowndate"></label>
<select name="dropdowndate" id="dropdowndate">
<?php
do {
?>
<option value="<?php echo $row_dropdowndate['FORMATTEDDATE']?>"<?php if (!(strcmp($row_dropdowndate['FORMATTEDDATE'], $row_dropdowndate['FORMATTEDDATE']))) {echo "selected=\"selected\"";} ?>><?php echo $row_dropdowndate['FORMATTEDDATE']?></option>
<?php
} while ($row_dropdowndate = mysql_fetch_assoc($dropdowndate));
$rows = mysql_num_rows($dropdowndate);
if($rows > 0) {
mysql_data_seek($dropdowndate, 0);
$row_dropdowndate = mysql_fetch_assoc($dropdowndate);
}
?>
</select>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
<p> </p>
<form id="form1" name="form1" method="get" action="">
<table border="0" cellpadding="5" cellspacing="2">
<tr>
<td>Date</td>
<td>Subject</td>
<td>Message</td>
</tr>
<?php do { ?>
<tr>
<td><?php echo $row_newsitems['Date']; ?></td>
<td><?php echo $row_newsitems['Subject']; ?></td>
<td><?php echo $row_newsitems['Message']; ?></td>
</tr>
<?php } while ($row_newsitems = mysql_fetch_assoc($newsitems)); ?>
Some of this may look weird so let me explain... The dynamic list (dropdown) is called 'dropdowndate' and the form is called 'choosedate' There is a button called 'submit' to submit the form. FORMATTEDDATE is the name given to the recordset which gives the dropdown menu a dynamic list.
I want the value from that dynamic list when user's POST, to insert into the query as i mentioned ... SELECT Date, Subject, Message FROM news WHERE date = $_POST['dropdowndate']"; (THIS BIT IS PROBABLY WRONG)
Rob
SELECT date, subject, message FROM news WHERE date = $_POST['fieldvalue']
The $_POST variable contains all the data sent when the form is posted. The field value should correspond to the name you give the select field.
This would be open to injection, so please ensure you use reasonable security measures.
If you wish to get the data without refreshing, you will need to use AJAX the following explains it beautifully http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/ if you need more info on that just ask.
An example of an HTML dropdown
<form method="POST">
<select name="animal">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
</select>
</form>
An example how to catch the information with php
<?php
echo $_POST['animal'];
?>
Do you want the records to be loaded when the user select something from the drop down, or you want it to be loaded with the page?
In the first case you need to use Ajax, to bring the records in the background.
In the other case, you can do a statement like the one you posted when the page is loading.
$select = $_POST['dropdowndate'];
$sql = "SELECT * FROM table WHERE attribute = '$select'" or die (mysql_error());
Trying to work on a clients site and I am having a bit of difficulty. When I have no entries in the database, it catches at if(!row) and displays the message. This part works fine. My issue is when I have entries in the db, they do not display. I know the while loop works because I have several pages running a similar loop. In fact, this loop was copied from another page that displays this entry's information on a public page.
I know this site is mainly for questions, but I think I just need a fresh pair of eyes to look at my code(I've been coding for over 12 hours and I'm a bit tired). A lot of the code below is from a previous web designer and if it were up to me, I would just rewrite the entire site because the code is "out of date", but the client just wants me to improve on it. Any help would be greatly apprecieated.
$row = mysql_fetch_array($result);
if (!$row) {
echo '<tr><td bgcolor="ffffff" colspan="3"><font face="arial,helvetica" size="2" color="000000">There are no entries at this time, check back later.</font></td></tr>';
} else {
while ($row = mysql_fetch_array($result)) {
echo '<tr>
<td bgcolor="ffffff"><font face="arial,helvetica" size="2" color="000000">$date - $row["theme"]</font></td>
<td bgcolor="ffffff" align="center">
<form action="dsp_modifyposition.php">
<input type="hidden" name="specialID" value="$row["specialID"]">
<input type="hidden" name="theme" value="$row["theme"]">
<input type="submit" value=" Modify ">
</form>
</td>
<td bgcolor="ffffff" align="center">
<form action="act_deleteposition.php" onsubmit="return confirm(\'Are you sure you want to delete this event: $date \')">
<input type="hidden" name="specialID" value="$row["specialID"]">
<input type="hidden" name="theme" value="$row["theme"]">
<input type="submit" value=" Delete ">
</form>
</td>
</tr>';
}
}
When you call mysql_fetch_array for the first time, the mysql result pointer is moved to the next row. Because nothing is done with this row, this first row does not get displayed. What you want is mysql_num_rows to check how many rows are in the resultset. As a side-note, I would suggest using mysql_fetch_assoc if you're not using the numeric indices.
if (!mysql_num_rows($result)) {
echo '...';
} else {
while ($row = mysql_fetch_assoc($result)) {
echo '...';
}
}
Change your first lines to this:
$cnt = mysql_num_rows($result)
if (!$cnt) {
echo '<tr><td bgcolor="ffffff" colspan="3"><font face="arial,helvetica" size="2" color="000000">There are no entries at this time, check back later.</font></td></tr>';
} else {
....
Your if() statement seems flawed. The statement:
$row = mysql_fetch_array($result);
will fetch a row and move the pointer in $result to the next row, so your while will start at the second row. If your query returns only one row, you're effectively calling mysql_fetch_array() twice and skipping over the data returned.
You should find some other way of checking if you have results (possibly with mysql_num_rows()).
Trying to delete multiple rows using check-boxes. At first i'm generating table of contents with checkbox column. Then posting data to php side. The problem is, php side returning back to the current page. It means that all done successfully and page returned user back. But no success. There is no error in php logs, and MySQL problem. I tried print_r ($_POST['checkbox']); die(); after $delete=$_POST['delete'];. It gave me result something like that Array ( [0] => on [1] => on ) what's wrong with my code?
My HTML markup looks like that
<?php
$result = $db->query("SELECT id, name, showinmenu FROM menu") ;
$num=$result->num_rows;
if ($num>0) {
?>
<form method="post" action="processor/dbdel.php">
<div style="overflow-y: auto; overflow-x: hidden; height:500px">
<table id="list" class="features-table">
<thead>
<tr>
<th>#</th>
<th style="min-width:80px;" class="name">Ad (menyuda işlənən)</th>
<th>Sil</th>
</tr>
</thead>
<tbody>
<?
while ($row = $result->fetch_object()) {
echo '<tr>
<td>'.$row->id.'</td>
<td>'.$row->name.'</td>
<td><input type="checkbox" name="checkbox[]" method="post" value"'.$row->id.'" id="checkbox[]" "/></td>
</tr>';
}
// when the loop is complete, close off the list.
echo "</tbody> <tr id='noresults'>
<td style='text-align:center' colspan='9'>Nəticə yoxdur</td>
</tr></table>
</div>
<p style='text-align:center;'>
<input id='delete' type='submit' name='delete' value='Seçilənləri sil'/> </p>
</form>";
}
?>
And here is my PHP code
<?php
require '../../core/includes/common.php';
$delete=$_POST['delete'];
if($delete) // from button name="delete"
{
if (is_array($_POST['checkbox']))
foreach($_POST['checkbox'] as $del_id) {
$del_id = (int)$del_id;
$result=$db->query ("DELETE FROM menu WHERE id = '$del_id'") or die($db->error);
$result2=$db->query ("DELETE FROM pages WHERE id = '$del_id'") or die($db->error);
}
if($result2)
{
header("location:".$wsurl."admin/?page=db");
}
else
{
echo "Error: ".$db->error;
}
}
?>
Your code is an absolute disaster.
1) Using echo with repeated string concatenation to output html. Look up HEREDOCs, double-quoted strings, or simply breaking out of PHP-mode (?>) to output html.
2) Checking for POST by looking for form fields. If you want to make sure you're in a POST situation, then do if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... } instead. This is 100% reliable, and does not depend on the presence (or absence) of particular form fields. If the data was submitted via post, this statement will evaluate to true, ALWAYS.
3) You are blindly embedding user-provided data into SQL query strings. Read up about SQL injection attacks, then consider what happens if someone hacks your form and submits a checkbox value of ' or 1' - say goodbye to the contents of your checkbox table.
4) You appear to have a stray " in your checkbox output line:
[...snip...] method="post" value"'.$row->id.'" id="checkbox[]" "/></td>
^--here
which is almost certainly "breaking" your form and causing subsequent tag attributes to be misinterpreted.
5) on the plus side, I'll have to give you this much - you are at least checking for query errors on your two delete queries, which is always nice to see. However, that's a minor plus in a huge field of negatives.