Pls help.
I am working on a php project and this requires adding and altering data from the SQL database. There are two tables involved with this: emp which contains employee details and pay containing payroll records for each employee.
I would like to have a dropdown list containing all employee names (empname) from the database. Below the list is a form where the user shall input the payroll details. These details will then be saved into the SQL pay table corresponding to the employee name selected.
I've tried searching over the web but it doesn't seem to similar to my problem. How should I do this? Thanks!
Wihtout knowing any more details about your datbase, table structure and other stuff, this is closes that I could get.
<?php
/* Connect to SQL and retreive data */
$sqlConf = array('u'=>'username','p'=>'password','h'=>'localhost','d'=>'myDatabase');
$sqlCon = mysql_connect($sqlConf['h'], $sqlConf['u'], $sqlConf['p']);
if ($sqlCon) {
$emp = array();
mysql_select_db($sqlConf['d'], $con);
$result = mysql_query("SELECT * FROM emp");
while($row = mysql_fetch_array($result)) { $emp[] = $row; }
mysql_close($sqlCon);
}
/* Generate select box contents */
$html = '<select name="emp">';
$html .= '<option>Employee list</option>';
if (!empty($emp)) {
foreach ($emp as $k => $v) {
$html .= '<option value="'.$v['empid'].'">'.$v['empname'].'</option>';
}
}
$html .= '</select>';
/* Output */
echo $html;
?>
Sounds like you need to learn some basic php/SQL. The basic outlines of the problem are:
Query the dropdown list from SQL, and display in an option-select.
When they the form submit, send a corresponding query to update the database.
Is there some particular aspect of this problem that you can't get past?
This can be solved in any number of ways and the overall structure, design and layout of your application would dictate which route to go.
You could have classes that represent your database objects, classes that represent your forms, you could print your forms by mixing php and html like a crazy person and so on and so on.
Then it all depends on if you will be using ajax or not.
So give us a bit more information about how your application is designed and that will probably help.
If you have not started at all I would suggest you to look into some of the many frameworks. Zend Framework or Symphony for example. They have a good way of handling db abstractions and forms creation etc.
Related
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I want to add data from my DB to an array when a user clicks a link e.g
echo 'ADD'.
i get the id of the element and query the database to get the details of the item clicked and display it using a for loop like this(on cart-page.php):
$cart = $_GET['cartid'];
$cartData = array();
$SQL = "SELECT * FROM tbl_product where id ='$cart'";
$result = mysql_query($SQL);
while($row = mysql_fetch_assoc($result)){
array_push($cartData, $row);
}
$length = count($cartData);
for($i = 0; $i < $length; $i++) {
echo '</tr>';
echo ' <td class="product">'.$cartData[$i]['name'].'</td>';
echo'<td class="quantity"><input type="text" value='.$cartData[$i]['quantity'].' class="inputform"/></td>';
echo '</tr>';
}
My problem is array_push() isn't appending the data. Each time i navigate away from cart-page.php and click a link the previous content in cartData[] is overwritten leaving only one row in cartData[] at a time. How i can i get the data appended to cartData[] whenever i click a link like the one shown above? Thanks
Does it need to be APpended? Why not just add it to the array and order the array at a later time?
PHP array sorting
while($row = mysql_fetch_assoc($result)){
$cartData[] = $row;
}
In addition, you should ALWAYS escape your data.
$cart = $_GET['cartid'];
The above code is vunerable to SQL injection. At the least, escape it!
$cart = mysql_real_escape_string($_GET['cartid']);
EDIT
In order to remember all previous cart additions, you will need to create a session, and add each click to it:
session_start();
$cartid = mysql_real_escape_string($_GET['cartid']);
function addToCart($cartid)
{
$SQL = "SELECT * FROM tbl_product where id ='{$cartid}'";
$result = mysql_query($SQL);
while($row = mysql_fetch_assoc($result)){
$_SESSION['cartItems'][] = $row;
}
}
function getCartItems()
{
print_r($_SESSION['cartItems']);
}
This will hopefully work as you expect. Sessions will retain state across browser refreshes.
To use this code, when you want to add items to the original $cartData, you need to call the function addToCart($cartid). This will add the item data to the cartItems session array
To see whats in the cart as an array, just use print_r($_SESSION['cartItems']);
Short answer: Your issue is not that you aren't adding the item to the array, it's that you don't understand how arrays work. Arrays do not persist across pages, they are instantiated to a single runtime of a single script unless declared otherwise.
MAJOR security flaw #1 - Sending cartid in URL:
Edit: I misunderstood this. Your cartid variable refers to a product_id. This is very poor variable naming, any programmer would assume this referred to an ID of a shopping cart. Whilst this security flaw is not relevant in this instance, I'm leaving it here for anyone who misunderstands your code and decides to copy it.
Firstly, this URL is a problem:
echo 'ADD'
This means that if I can guess another user's cart ID, I can add items to their shopping cart by visiting cart-page.php?action=add&cartid=100 where 100 is another user's cart ID. You should process the $cart variable internally using a validated session, not send them across the internet via GET or POST requests which can be user manipulated.
MAJOR security flaw #2 - Vulnerability to SQL Injection attacks:
The statement
$SQL = "SELECT * FROM tbl_product where id ='$cart'";
is incredibly dangerous. Let's say I submit this in my URL (properly encoded of course):
cartid = 2'; DROP TABLE tbl_product; SELECT * FROM tbl_product WHERE cartid='
This will then perform the following query on your database:
SELECT * FROM tbl_product where id ='2'; DROP TABLE tbl_product; SELECT * FROM tbl_product WHERE cartid='';
If you want to avoid this, you have a few options. The best of those options is to switch to using prepared statements, the easiest of those options is to use mysql_real_escape_string on everything you put into your database, like this:
$SQL = "SELECT * FROM tbl_product where id ='" . mysql_real_escape_string($cart) . "';";
Once you've fixed the above, we can fix the rest of the code:
First, we want to put your results into the array. As $results is already an associative array, you can either use it directly or store it like this:
$cartData = $results;
Keeping products in the cart
Edit: I misunderstood what you were doing, you're using a variable called $cart to store a product ID, you need to sort out your variable names.
In order to have an array which will persist across multiple page loads, you will need to make it a session variable, first you have to start a PHP session:
session_start();
Use a session variable like this:
$_SESSION['shopping_cart'] = array();
Then, when you 'add' a product, do this:
$_SESSION['shopping_cart'][$cartData['id']] = array(
'name'=>$cartData['name'],
'quantity'=>1
);
When you change the quantity, this:
$_SESSION['shopping_cart'][$productId]['quantity'] = $newQuantity;
Now, when you display the cart, instead of displaying directly from products, insert to the array using the above first, then return the contents of $_SESSION['shopping_cart'].
foreach was made for array transversal, use it!
Finally, don't use an ugly for loop to iterate an array, just do:
<?php foreach($_SESSION['shopping_cart'] as $product): ?>
<tr>
<td><?php echo $product['name'] ?></td>
<td><input type='text' value='<?php echo $product['quantity'] ?>'></input></td>
</tr>
<?php endforeach; ?>
Hope this helps, I haven't done all the work for you, but I have given you a lot of pointers in the right direction and identified some serious issues which matter.
Recommendations for this Project:
A shopping site is a major undertaking, you should spend some time reading about concepts like PHP security, sessions, relational databases etc. It may seem like an unnecessary hassle, but writing clean and secure code now means that when you have to debug it and make changes, you will be able to do so much more easily.
I'd also suggest you look into some (free, open source) MVC frameworks like Zend and CakePHP. These wont do all the work for you, but they will make it easier for you to keep your code well maintained and readable.
how can i use a single jquery autocomplete for multiple form dropdown?
here is my view page(header):
$("#full_name").autocomplete({
source: "<?php echo site_url('autocomplete/get_names');?>"
});
$("#department").autocomplete({
source: "<?php echo site_url('autocomplete/get_dept');?>"
});
*** and other like these for subjects, zip and country.
controller page:
public function get_names(){
$this->load->model('autocomplete_model');
if (isset($_GET['term'])){
$q = strtolower($_GET['term']);
$this->autocomplete_model->get_fullnames($q);
}
}
*** and other functions...
model page:
function get_fullnames($q)
{
$match = $q;
$this->db->select('full_name');
$this->db->like('full_name', $match,'after');
$query = $this->db->get('employee_list');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['full_name']));
}
echo json_encode($row_set);
}
}
how can i implement a single search term that could be used for multiple criteria?
thank you guys in advance..
This is not going to scale; as your database tables grow, this implementation will become very sluggish. What you need to do is use an indexing engine to allow Full Text Searching.
MySQL does not allow Full Text Search on InnoDB tables (actually, it was just released in the latest version, but it's still in it's infancy). Look into using Elastic Search, Sphinx, or Solr.
Poke around StackOverflow to find the best engine for you - there are many helpful questions that have been asked in the past regarding this problem. Hopefully that sets you on the right course.
I had asked a similar question a few days ago but think I was trying to do to much at one time. I am hoping someone can help get me started on this.
I have two drop down lists, one will be populated with years (2012, 2011 etc) and I have some mySQL databases called "db_2012", "db_2011" etc. In these databases are tables representing months.
I would like the user to select a year and then use that selection to query the correct db and return a list of table names which will be used to populate the second drop down list. Then click a button "See Results" to query the selected table and show the results.
I am putting this on a wordpress website and am using a php template file that I created. This is still new to me and what I have so far doesnt work like I want it too, it is basically setup now that you select a year and select a month (not populated from db) and click a button. It makes the query and my table is displayed, but I need this solution to be more dynamic and work as described above. Thanks for the help.
echo '<form action="" method="post">';
echo'<select name="years" id="years">';
foreach($yearList as $year){
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select><br />';
echo '<select name="monthList" id="months">';
foreach($monthList as $month) {
echo'<option value="'.$month.'">'.$month.'</option>';
}
echo '</select>';
echo '<input type=\'submit\' value=\'See Results\'>';
echo '</form'>
$yearList and $monthList are just pre populated arrays. So now from here I want to click the See Results button and query my sql database using the parameters from the drop down selections.
$database = $_POST['yearList'];
$month = $_POST['monthList'];
$wpdbtest_otherdb = new wpdb('Username', 'Password', $database, 'localhost');
$qStr = "SELECT * FROM $month";
$myResults = $wpdbtest_otherdb->get_results($qStr, OBJECT);
It sounds like you want to send an AJAX call to a separate php page for security and processing, then have the PHP return XML that you parse back into the second selection box via the AJAX callback. It can be a little messy, but it allows you to check for weird form values that users might inject.
Edit: The PHP will receive your AJAX parameters as parts of the $_GET or the $_POST array. From there, you can do your checks and db call (or not), then add header("Content-Type:text/xml"); so the server sends it back with the correct header. After that you'll need to echo the XML-formatted data you want the JavaScript to receive. Just remember not to echo anything other than the XML if the request is supposed to go through.
I'm really struggling to get my code to work, and I can't figure out why.
I have a database in my PHPMyAdmin and it contains 2 tables:
tennisCourts
courtID
courtName
bookingFee
tenniscourts_Availability
courtID
court_dateBooked
I am writing a PHP program using PEAR repository, and I am struggling to create code that allows me to:
Display All courtNames and their corresponding bookingFee BASED ON users search date ONLY IF the courtName is not already booked by another user.
Here is my current code:-
$CHOSEN_BOOKING_DATE = $_GET['user_dateField']; //GET's input data from user form in my other html document.
$database->setFetchMode(MDB2_FETCHMODE_ASSOC);
$myQuery = "SELECT * FROM tennisCourts, tenniscourts_Availability WHERE court_dateBooked != $CHOSEN_BOOKING_DATE";
$queryResult =& $db->query($myQuery);
if (PEAR::isError($queryResult)) {
die($queryResult->getMessage());
}
echo '<table>';
while ($Col =& $queryResult->fetchRow()) {
echo '<td>'.$queryResult['courtName'].'</td>';
echo '<td>'.$queryResult['bookingFee'].'</td>';
echo '<td>'.$queryResult['court_dateBooked'].'</td>';
}
?>
The code above displays all the courtNames and BookingFee's for All court_dateBooked fields in my database. I cant get it to display the courtNames and bookingFee only if it isn't booked. If it is booked it should return "sorry no courts found on this date".
I am still new to PHP and SQL so forgive me if I have not made myself clear. I have been researching online and various sources say to use SQL UNION OR JOIN? Could someone please enlighten me on how they could be used in context to my scenario? I really appreciate any help. Thank you for checking out my question.
Try this:
$myQuery = "
SELECT c.courtName
, c.bookingFee
, a.court_dateBooked
FROM tennisCourts AS c
LEFT JOIN tenniscourts_Availability AS a ON c.id = a.courtID
WHERE a.court_dateBooked != '" . $CHOSEN_BOOKING_DATE ."'";
Make sure you sanitize and escape $CHOSEN_BOOKING_DATE properly before executing your query. Since it looks like you're using PDO you should be using prepared statements for this.
After spending 3 days on internet and struggling with so many different forums , i have found a match and similar case of my problem here.
Friends, I am zero in PHP, but still i have managed to do something to fulfill my requirement.
I am stuck with one thing now..So i need help on....
I am using one html+php form to submit database into mysql.
I created a display of that table through php script on a webpage.
Now i want a datepicker option on that displayed page by which i should able to select the date range and display the data of that date range from my mysql table.
And then take a export of data displayed of selected date range in excel.
This displayed page is login protected, so i want after login the next thing comes in should show a sate selection option which should be fromdate to to date , and then records should displayed from the database and i can take export of those displayed results in excel file.
The code i am using on this page is below which do not have any thing included for excel export and date picker script, I am pasting the code here and request you to please include the required code in it as required.
Thanks In advance
<?php
//database connections
$db_host = 'localhost';
$db_user = '***********';
$db_pwd = '*************';
$database = 'qserves1_uksurvey';
$table = 'forms';
$file = 'export';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table} ORDER BY date desc");
if (!$result) {
die("Query to show fields from table failed");
}
$num_rows = mysql_num_rows($result);
$fields_num = mysql_num_fields($result);
echo "$num_rows";
echo "<h1></h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
?>
</body></html>
This isn't a "write my code for me, please" site, so you're going to need to be a little more engaging and pro-acive. But we can certainly provide some guidance. Let's see...
Currently you have a page which displays all records from a given table, is that correct? And you need to do two things:
Before displaying any records, have the user select a date range. And keep the date range selection on the page so the user can re-select.
Provide a button which lets the user export the selected records to Excel.
For either of these, you're going to need to add an actual form to the page. Currently there isn't one. For the date picker, I recommend (naturally) using the jQuery UI datepicker. So the form for that would look something like this:
<form method="POST" action="myPHPFile.php">
<input type="text" id="fromDate" name="fromDate" />
<input type="text" id="toDate" name="toDate" />
<input type="submit" name="filterDate" value="Submit" />
</form>
<script>
$(function() {
$("#fromDate").datepicker();
$("#toDate").datepicker();
});
</script>
You may have to wrap the JavaScript in a $(document).ready(){} in order to make it work correctly, you'll want to test that. Anyway, this will give you a form to submit the dates to your script. Wrap the parts of your script which output data in a conditional which determines if the form values are present or not. If they're not, don't fetch any records. If they are, do some basic input checking (make sure the values are valid values, make sure fromDate is before toDate, etc.) and construct your SQL query to filter by date range. (Do take care to avoid SQL injection vulnerabilities here.)
For the Excel output, you may be able to find a ready-made solution for you that just needs a little tinkering. If I were to create one from scratch, I'd probably just output to a .csv file rather than a full Excel file. Most users don't know/care the difference. In that case, you'd just want to either create a second script which is nearly identical to the existing one or add a flag to the existing one which switches between HTML and CSV output, such as via a hidden form field.
For the output of the CSV, first make sure you set your response headers. You'll want to write a header to tell the browser that you're outputting a CSV file rather than text/html, and possibly suggest a file name for the browser to save. Then, the form inputs the SQL query will all be pretty much the same as before. The only difference is in the "HTML" that's being output. Rather than HTML tags, you'd wrap the records in commas, double-quotes (where appropriate), and carriage returns.
There's really nothing special to outputting a "file" vs. "HTML" because the HTTP protocol has no distinction between the two. It's always just text with headers.
Now, I'm sure you have more questions regarding this. And that's fine. In fact, we like to encourage asking (and, of course, answering) questions here. So please feel free to ask for clarification either in comments on this answer (or other answers), or by editing and refining your original question, or by asking an entirely new question if you have a specific topic on which you need help. Ideally, a good question on Stack Overflow consists of sample code which you are trying to write, an explanation of what the code is supposed to be doing, a description of the actual resulting output of the code, and any helpful information relevant to the code. As it stands right now, your question provides code somewhat unrelated to what you're asking, and you're just requesting that we add some features to it outright for you.