I havent noticed ardav has already replied with more detailed example some minutes before me so do not pay too much attention to my reply :-)
Biiim commented: spot on +5
don't give up commented: thank you +0
I havent noticed ardav has already replied with more detailed example some minutes before me so do not pay too much attention to my reply :-)
If I understand correctly: you want to construct an SQL statement depending on a field to be sorted on and the sort direction (ASC, DESC)?
If the above is true then the simplest option is to have the field to be sorted on and the sort direction in a querystring (using a form with method="get" - I hope you know how to do this).
Then just check whether both values have been passed and construct a query:
// if field to sort and sort order have been set
if(isset($_GET['sortfield']) and isset($_GET['sortdir']) {
// assign querystring values to variables
// all the security stuff is omitted here for simplicity
// but do not to forget to check for correct values yourself!!!
$sortfield = $_GET['sortfield'];
$sortdir = $_GET['sortdir']
} else {
// prepare default values
$sortfield = 'Category';
$sortdir = 'ASC';
}
$query = "SELECT Category, ID, Arthur FROM booklist ORDER BY $sortfield $sortdir"
// do connecting to the db, reading from the table, displaying results etc
// ...
the <select> part it is echoing $one_date
This is due to my mistake. In line 32 double quotes should be used (to allow $one_date to be parsed):
echo ">$one_date</option>";
' selected="selected"'; part, could you explain this to me?
This is just a part of html syntax for select element. If an <option>
has a selected="selected"
attribute that option is selected. In the code above there is a foreach
loop that creates <option>
parts from an array (the $date_array
in your case) for the select element. Within each iteration it checks whether the curent value of an array equals to the value read from the database. If it finds one the attribute selected="selected"
is added to that option. Once it works OK have look at the HTML source in the browser.
I could not find any information on whether there are any restrictions for an option value attribute (<option value="any_restrictions_here?">
) .I hope dots are permitted. I think browsers encode values to be safe for sending to a server.
A general answer:
A simple example just to get the idea:
// a query to get the fields
$qry = "SELECT * FROM table WHERE record_id=$ome_id";
// run the query
$result = mysql_query($qry) or die('Some error occured.');
// an array with fields of the querried row
$row = mysql_fetch_array( $result );
// start the form
echo '<form method="post" action="some_page.php">';
// an example of input text element with the value from database field
echo '<input type="text" name="input_name" value="' . $row['field1'] . '" />';
// an example of select element with values from a $dates_array and a selected
// option from database field
$dates_array = array('1.4.2012','2.4.2012','3.4.2012','4.4.2012','5.4.2012',);
// begin the select element
echo '<select name="date_select">';
// loop through the dates_array and add options
foreach($dates_array as $one_date) {
// start the option tag
echo '<option value="' . $one_date . '"';
// if current element of the date_array equals to the date, read from the
// database, add selected attribute
if($one_date == $row['date_field']) {
echo ' selected="selected"';
}
// end the option, add the text value for the drop down, end the option …
in_array function actualy works if you pass it an array as a needle (PHP 4.2 and above) :
$test_arr = array(
0 => array('StudentID' => 123456789),
1 => array('StudentID' => 001122334),
2 => array('StudentID' => 010203040),
3 => array('StudentID' => 987654321));
if(in_array(array('StudentID' => 123456789), $test_arr)) {
echo 'Found';
} else {
echo 'Not found';
}
But this seems a bit clumsy to me. Why do you have such a structure of array and why is looping through array not an option?
You will have to use the correct type of joins (LEFT JOIN, RIGHT JOIN) to retrieve records with empty values. Which type of JOIN depends on the structure of tables and where the empty values are. See this tutorial:
Insert this code between lines 8 and 9 and post what is displayed:
echo('<pre>' . print_r($row, 1) . '</pre>');
This will display and array of values for each row. <pre> tags are just for nicer formatting. If each row is an array of expected values then your table should print correctly.
Biim is right. Reference was made correctly in your first post but was changed to wrong in your post 4 days ago.
The code seems to be OK. It can be a problem in that the query is not what you expect. Maybe you have already done this but if not put the following statement on line 27 and post here what it outputs:
die($sql);
I have not tried this but I think text fields should be put within text delimiters (usualy double quotes). Try changing your code this way:
$csv_output .= '"$row['misRefId']"' . ", ";
...
This way commas will be within double quotes as part of the text and wont be treated as a field delimiter. Be careful if you have double quotes in text. In that case you have to escape them.
Just to comment on the post by fobos above. If you use tc_tool.forms it is OK since this is mySql's notation of database_name.table_name or table_name.col_name. So tc_tools is probably a database name and forms is table name. Maybe tubesnube can confirm or correct me.
You can not use % wildcards if you use equals (=) operator. Wildcards (% or _) can be used only with LIKE statement. I suggested you use equal operator only if you are certain that doc_id is an integer not a string (or a complete string to match not just part of). In that case the query would be:
$searchById = "SELECT * FROM tc_tool.forms WHERE doc_id = $doc_id"; // $doc_id is and integer
or
$searchById = "SELECT * FROM tc_tool.forms WHERE doc_id = '$doc_id'"; // $doc_id is a complete string
That was just a suggestion. If you want to use wildcards then stick to your version:
$searchById = "SELECT * FROM tc_tool.forms WHERE doc_id LIKE '%$doc_id%'";
Since I have to go I am posting a quick checklist for debugging:
$_GET['check'] array should contain array of the Codes you checked with checkboxes
$code_list should be a string of the same codes, separated by commas (it is created from $_GET['check'] array using implode() function)
SELECT query should use $code_list to select all rows that have selected codes (that is why you use IN statement). It should look something like SELECT * FROM books where Code IN (1100,1102).
To debug first inspect the $_GET['check'] array. You do this with print_r($_GET['check']) command. It should display something like Array ( [0] => 1100 [1] => 1102 )
When it is OK you can check the $code_list string that comes from the array. YOu use die($code_list) command for that. $code_list should be something like '1100,1101,1102'.
You can also inspect the query using die($query). You can copy displayed query nto phpmyadmin (look for SQL tab) and see if it return correct rows.
Hope that helps.
After the line that says:
$code_list = implode(',', $_GET['check']);
put the following code:
die(code_list);
and post here.
OK, we are back to the beginning. Please uncomment the following line:
// print_r($_GET['check']);
and post what you get.
One more thing: I am leaving in 35 minutes and will not be availabel for 3 - 4 hours.
Your notepad++ should warn you about this error.
You are missing double quote at the end of the following statement:
$query = "SELECT * FROM books where Code IN (1100,1102);
It should be:
$query = "SELECT * FROM books where Code IN (1100,1102)";
Then why is it now different error. Can you post the last version of order.php.
This error is completely different now:
Parse error: syntax error, unexpected '>' in C:\xampp\htdocs\xampp\onlinebookstore\order.php on line 19
What IDE / editor do you use? It should show you the error in syntax. Have you misstyped something?
Also do you use phpmyadmin or other client to accesss the database? Try to test the following query and post what it returns:
SELECT * FROM books where Code IN (1100,1102)
Please uncomment the following line again and post the output:
// print_r($_GET['check']);
This array should contain values from checkboxes or an error message from the query.
Make sure the line print_r($_GET['check']);
in order.php is commented like this:
// print_r($_GET['check']);
Go back to the page home_order.php, select some checkboxes and submit.
Comment out the lines you uncommented for debugging (they are there just for debugging):
die($query);
and
print_r($_GET['check']);
The error is probably in home_order.php just before the end of while loop on line that says:
echo '<td align=center><input type="checkbox" name="check[]" value="';
echo $row['code'] . '" ></td>';
It should be:
echo $row['Code'] . '" ></td>';
It is better to use all small caps for field names otherwise the errors like that pop out (it was actually my error since I did not know the table structure).
So the error seems to come from previous script. Can you post both scripts (the one with the table and the order.php) and tell me what is the name of the first script.
$code_list is a string of codes and should get constructed from the $_GET['check'] array by implode function. So we have to check what the array is. Uncomment the following line in order.php:
// print_r($_GET['check']);
and post the output (firstselect a fewcheckboxes).
The following line is returning false instead of a resource (ponter to rows):
$result= mysql_query($query);
This means that there is an error in the query in order.php. You have to display the query and post it here. Uncoment the line that says:
// die($query);
refresh the page and post the output (your query);
Here you have your main file and order.php file. Read the comments since most of explanations are there. Main thing is that checkbox name attribute was changed to an array and value was added to each checkbox so you know which codes were selected. I assumed that code is an integer. If it is a string then you must add single quotes otherwise you will get db error.
This is your table with checkboxes:
<?php
// I have wrapped all HTML attributes in double quotes so you do not run into problems
// added html, head and body tags
echo '<html>';
// this line goes to head section
echo '<head><link rel="stylesheet" type="text/css" href="design.css" /></head>';
include("connect.php");
echo '<body>';
echo '<form method="GET" action="order.php">';
echo '<center><img src="top.png"></center>';
$result= mysql_query("SELECT * FROM books");
echo '<div><table border="0" cellspacing="15" align="center" id="home_orde"r>
<tr>
<th>Code</th>
<th>Title</th>
<th>Price</th>
<th>Stock</th>
</tr>';
while($row = mysql_fetch_array($result)) {
echo "<tr><td align=center>" . $row['code'] . "</td>";
echo "<td align=center>" . $row['Title'] . "</td>";
echo "<td align=center>" . $row['Price'] . "</td>";
echo "<td align=center>" . $row['Stock'] . "</td>";
// I have changed the name of checkbox to check[] array and added a value
// that equals the code, so you know which checkbox was selected
// I have also wrapped HTML attributes in double quotes
echo '<td align=center><input type="checkbox" name="check[]" value="';
echo $row['code'] . '" ></td>';
}
echo"</table></div>";
echo"<table border=0 cellspacing='15' align=center >";
echo"<td align=center>"."<input type=SUBMIT>"."</td>";
echo '</body></html>';
?>
This is order.php:
<?php
// if there were any checkboxes selected, they will be returned …
Just to be sure: You have a table where each row represent a code and each row has a checkbox. When user selects some checkboxes you would like to diplays information for selected rows based on code. Did I get it right?
It would also help if you post the whole script that displays the table with checkboxes. And use formating in the editor (i.e. select the code and click on the Code button).
Do you get any error messages? If yes post them here.
Also display the query and check it in phpmyadmin (or post it here). Change your code to something like:
$query = "SELECT * FROM books where Code='$code'";
// this will display the query so you can check it
die($query);
$result= mysql_query($query);
You are probably missing an assignment to a variable $doc_id (put it on line 22) just before you construct $searchById, like:
$doc_id = $_POST['searchID']
And if $doc_id is a number (integer) you could use = instead of LIKE in your query.
And another question: is it OK that all the id_no values are the same?
In your insert query there is a comma (",") missing after the second set of values which probably breaks your query (see below).
INSERT INTO system.grades
(id_no ,course ,semester ,year ,subject ,descriptive_title ,final_grades ,remarks)
VALUES
('003', 'cs', 'second', 'second', 'cs', 'prog', '2', 'pass'),
('003', 'cs', 'second', 'second', 'java', 'prog', '2.1', 'pass')
('003', 'cs', 'second', 'second', 'vb', 'prog', '2.3', 'pass'),
('003', 'cs', 'second', 'second', 'C++', 'prog', '2.4', 'pass');
Can you please post the array $new so I can have a look at it. Place this code before if (count($new)
> 0) line and post the output:
die(print_r($new, 1))
Your insert query has to be checked if it is OK. Put this code before theif ($query)
statement:
die($query);
This will display your final query and stop the script. Please post the displayed query here (and then remove the above die statement).
As I said I would do it like this (it is cleaner and safer and less chances for mistakes):
// assign $value array to variables, you can also do some cleaning here
if(isset($value['subject']) &&
isset($value['subject']) &&
isset($value['subject']) &&
isset($value['subject'])) {
$subject = $value['subject'];
$descriptive_title = $value['descriptive_title'];
$final_grades = $value['final_grades'];
$remarks = $value['remarks'];
$is_error = false;
} else {
$is_error = true;
}
if($is_error) {
die('ERROR: values missing!');
}
$new[] = "('$course', '$semester', '$year', '$id_no', '$subject', '$descriptive_title', '$final_grades', ' $remarks')";
What is the error?
I prefer to construct statements this way since it is easier to debug:
> $new[] = "('$course', '$semester', '$year', '$id_no', '$value[\"subject\"]', '$value[\"descriptive_title\"]', '$value[\"final_grades\"]', ' $value[\"remarks\"]')";
And also you better check for the values in the $value array and assign them to variables (and possiblly clean them):
if(isset($value["descriptive_title"])) {
$descriptive_title = $value["descriptive_title"];
}
Do the classic trick: insert die(query)
after the $query = mysql_query("INSERT INTO grades ...
statement and inspect whether the query is OK. Test it in phpmyadmin (or post it here).
This is because you have a return statement within a foreach loop so the loop gets executed only once. Try this way:
function t6($table)
{
$rows = '';
foreach ($table as $key => $value) {
$rows .= "<tr><td>$key</td><td>$value</td></tr>\n";
}
return $rows;
}
To keep a lang setting in a session seems OK for a session duration, to store it as a preference, put it into a database or a file. But back to your problem: do you have anywhere in your script(s) the session_start() command? It is required on every page for sessions to work.
Cool. Maybe you can mark the thread as solved.
Have a look at the html source (i.e in Firefox( right click on the page and select View Page Source. In the source you can check whether the checkboxes have proper value attributes (each checkbox should have different id for value attribute). Also check if there are any errors in html (usually colored red).
Is your other_2 table empty or are there already any records?
Post your table structure. Which fiekd is the primary key? Do you have an autoincrement field in the table? You should probably check wheter the id already exists in other_2 table before inserting it. to avoid duplicate records.
if(isset($_POST['submit'])) {
if(isset($_POST['checkbox']) and !empty($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $id) {
// check if the record with this id exists
$sql = "SELECT COUNT(*) FROM other_2 WHERE id=$id";
$result=mysql_query($sql);
// insert only if record does not exist
if(mysql_num_rows($result) == 0) {
$sql = "INSERT INTO other_2 SELECT FROM other WHERE id=$id";
}
}
}
}
Sorry I thought you have only the topic. In the case above the solution will be similar. First check if the form was submited and if yes, get the array of IDs. Then just insert into others_2 table by selecting from others. The code would be something like
if(isset($_POST['submit'])) {
if(isset($_POST['checkbox']) and !empty($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $id) {
$sql = "INSERT INTO other_2 SELECT FROM other WHERE id=$id";
}
}
}
But be careful. Tables orther and other_2 have to have exactly the same structure otherwise you might not get what you expect. You can also make the query more specific by specifying the fields. And also it would be a good idea to check for existing records in other_2 table not to insert duplicate rows.
Basicaly what you do you add a ceckbox to each row in the table, wrap the table in <form></form>
tags, add hidden fields which hold the topics and add a submit button. Then you first check if the form has been submitted. If yes you process it (do the insert) and then as usually draw the table. See comments in the code (the code was not tested, but you will get the idea).
<?php
// do the connection stuff
$con=mysql_connect("localhost","root","");
if(!$con) {
die('can not connect'.mysql_error());
}
mysql_select_db("test", $con );
// check if the form was already submitted, and process it, if it was
if(isset($_POST['submit'])) {
// check if any of the checkboxes have been selected
// (selected checkboxes will be returned in a $_POST['cbsave'] array,
// if none was selected, $_POST['cbsave'] will not be set)
if(isset($_POST['cbsave']) and !empty($_POST['cbsave'])) {
foreach($_POST['cbsave'] as $id) {
// check if an appropriate hidden field with the topic exists and
// is not empty
$topic_key = "topic_$id";
if(isset($_POST[$topic_key]) and !empty($_POST[$topic_key])) {
$new_topic = $_POST[$topic_key];
// insert into others_2 table
$sql = "INSERT INTO others_2 VALUES ($id, '$new_topic')";
}
}
}
}
// select from others to fill the table
$others="others";
$sql="SELECT * FROM $others";
$result=mysql_query($sql);
$num = mysql_num_rows($result);
// commented this one out since it appears lower in the script!
// echo"<thead>
// <tr> <th>#</th> <th> id </th> <th>topic</th></thead>";
// echo"<tbody>";
// put whole thing in a form that has action set to itself (or other page if you wish)
echo '<form action="#" method="post">';
// …
Sorry, correct code is
...
else if ($selected_radio == 'multiply') {
...
This forum has been upgraded just recently and I can not find the edit button that is why so many posts from me :-)
There is another typo in the calculate.php file on line 18: you are missing letter 'l' in a word multiply. The correct code is
...
else if ($selected_radio == 'mutiply') {
...
The easiest way to spot these kinds of errors is to look at the source code in the browser (in Firefox left click on the page and select View page source). Html errors are marked red.