The names in the $_POST array have to be the same as the name attributes of form fileds i.e.:
<input name="email" type="text" size="30" />
<?php $email = $_POST['email'];?>
It is much easier if the name attribtes and the variables are the same.
The names in the $_POST array have to be the same as the name attributes of form fileds i.e.:
<input name="email" type="text" size="30" />
<?php $email = $_POST['email'];?>
It is much easier if the name attribtes and the variables are the same.
The following is my suggestion (maybe not perfect but works):
// first check if the form was submitted
if(isset($_POST['submit'])) {
// initialize the array that will hold potential error messages
$errors = array();
// initialize variables (for filling-in fields in case of errors)
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
// if the form was submitted do the validation, assign variables and prepare
// potential error messages
// Filter Email
// you can also use the function from the saadi06 post above
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'E-mail is not valid';
}
// Filter name
if(!filter_var($name, FILTER_DEFAULT)) {
$errors[] = 'Name is not valid';
}
// Filter Phone (I doubt this is an appropriate filter for phone numbers)
// you better make up a function for checking phone numbers in your country
if(!filter_var($phone, FILTER_DEFAULT)) {
$errors[] = 'Phone is not valid';
}
// comment text
$comment = $_POST['comment'];
// if there were no errors (the errors array is empty) send the mail,
// display the successful message and stop the script
if(empty($errors)) {
$from = 'From: Form Submission';
$to = 'email@gmail/yahoo/etc.com';
$subject = 'Form Has Been Submitted - FRONT PAGE';
$body = " Form is Submitted by $name\n E-Mail: $email\n Phone: $phone\n Comments:\n $comment";
// mail($to, $subject, $body, $from);
die('<p>Message Sent Successfully!</p>');
}
}
// start the form, method is post, action is # (same page)
echo '<form method="post" action="#">';
// add the input element for name
echo 'Name: <input type="text" name="name" value="' . $name . '" /><br …
Multiple ANDs are legitimate and should work OK. However usually tables are joined on some matching fields so your query should also contain ON keyword. Do you get any errors running the query in phpmyadmin?
Maybe have look at this: http://www.killerphp.com/tutorials/object-oriented-php/. Haven't checked it myself but looks like a simple introduction.
And be aware of the difference between ||
and or
(and also &&
and and
) since they are essentially the same but do get evaluated in different order. See also the following thread: http://www.daniweb.com/web-development/php/threads/424547/-vs-and#post1814451
Are the two tables somehow related? If yes you can JOIN them and search for both terms. Without knowing the structure of the tables it is hard to tell more.
I get the text displayed as H1 (Firefox 12 on Fedora 16). Maybe you should have a look at the HTML code that your browser displays and see if there are any errors elsewhere (right click on page and select View page source in Firefox).
No problem, my friend. And please do not call me a guru since I am far far from that :-). You will soon get practice too.
If you find the answers helpful you can always vote (up arrow on the right side). If you think the post is really bad you can also downvote it (down arrow on the right side).
If this wrapps up this topic you can mark is as solved. If another problems arise just start a new topic.
This is the principle:
for($row=1;$row<=20; $row++){
echo "<tr>\n";
for($col=1;$col<=20; $col++) {
$x=rand($min,$max);
$random_array[$row][$col] = $x;
if($x % 2 == 0) {
$char = '*';
} else {
$char = '%';
}
echo"<td>$char</td>\n";
// add value to the $temp_array
$temp_array[] = $x;
}
echo "</tr>";
}
how do I make every even/odd number have for example: all evens are blue... and odds are red?
Do you mean every even/odd number or even/odd row in a table?
In both cases you use css style and apply it to table cells or rows. Here is the example for even/odd numbers:
// define the css styles
$style_even = {color: blue;};
$style_odd = {color: red;};
for($row=1;$row<=20; $row++){
echo "<tr>\n";
for($col=1;$col<=20; $col++) {
$x=rand($min,$max);
$random_array[$row][$col] = $x;
// define style depending on whether the number is even or odd
if($x % 2 == 0) {
$style = $style_even;
} else {
$style = $style_odd;
}
// add style to the cell
echo "<td style='$style'>$x</td>\n";
// add value to the $temp_array
$temp_array[] = $x;
}
echo "</tr>";
}
I'll be as good as you in maybe about a 2-3 years!
I'm not such an expert, it is just a practice and experience. If you do programming on regular basis you will get that in less than one year :-)
But I came up with a question, is there other ways in sorting a loop or maybe a better way and a way I shouldn't do it?
When it comes to sorting, there are basically two approaches:
Save the data you want to sort in an array (like I did above) and sort the array with one of many array sort functions. There are plenty functions to use that sort by keys, do natural sort, case insensitive sort, multidimensional sort, reverse sort etc. See http://php.net/manual/en/array.sorting.php
If you draw your data from a database then you can sort in your query using ORDER BY statement such as $query = "SELECT name, joindate FROM members ORDER BY name"
.
The following code should roughly do it:
// add the first div
echo '<div id="shelf" class="Magenta_div">';
// initialize the counter for the current table row
$current_row = 1;
while($row = mysqli_fetch_row($res)) {
// echo the image data from the db table row
echo "...";
// check if the current row count is divisible by 4
// if yes end the div and add another div
if($current_row % 4 == 0) {
echo '</div>';
echo '<div id="shelf" class="Magenta_div">';
}
// increase the current row
$current_row++;
}
// add the last div
echo '</div>';
The only thing is that in the last div you can have 0 images but you can check the number of rows returned and if it is divisible by 4 do not echo the last <div> </div>
pair of tags.
Well, if everything is OK including echo $id;
(line 6 in your first post displays correct ID) then something must be wrong with connection / query preparing. Have you tried what Steen proposed? if you use PDO I am not much faniliar with it. I use MDB2 from PEAR framework for stuff like this. In case I have to check the prepared querie I use
if (PEAR::isError($q)) {
die($q->getMessage());
}
or just print_r($mdb2);
if $mdb2 is the MDB2 object.
OK, I've done a bit of juggling and came up with the code below. Please note since you create a two-dimensional array you have to copy it to a one-dimensional temporary array so you can use the sort php function which works on one-dimensional arrays. See the comments in the code. I have renamed the variables you used but you can change them. Hope this is what you intended to get help with. If not then give more explanation.
<?php
$x=0;
$min=900;
$max=2000;
// initialize array of random values
$random_array = array();
// initialize temporary array for sorting
$temp_array = array();
// start html table for random values
echo "<table border=\"1\">";
// create $random_array with random numbers, display html table rows and
// store each value in onedimensional $temp_array for sorting
for($row=1;$row<=20; $row++){
echo "<tr>\n";
for($col=1;$col<=20; $col++) {
$x=rand($min,$max);
$random_array[$row][$col] = $x;
echo"<td>$x</td>\n";
// add value to the $temp_array
$temp_array[] = $x;
}
echo "</tr>";
}
// end the html table
echo "</table>";
// sort the $temp_array (sort works on onedimensional arrays)
sort($temp_array);
// start a table for sorted values
echo "<table border=\"1\">";
// initialize counter that will be the $temp_array's key
$key = 0;
// display html table rows of sorted values
for($row=1;$row<=20; $row++){
echo "<tr>\n";
for($col=1;$col<=20; $col++) {
echo"<td>{$temp_array[$key]}</td>\n";
// increase the key
$key++;
}
echo "</tr>";
}
// end the html table of sorted values
echo "</table>";
?>
In the above code the variables $table and $y are undefined. What is the purpose of those?
Also you should not put the </table>
tag within the foreach loop (see line 23). I am still looking at your code so more follows.
Also where do you get the $_GET['id'] from? Maybe you should test for it whether it contains a valid value like this:
if(isset($_GET['id']) and is_numeric($_GET['id'])) {
$id = (int)$_GET['id'];
} else {
die('Error, no ID passed over.');
}
Put the following on the line 8:
die($query);
and post what you get. It might be that the $subject_id is empty or not set.
Post the code you have so far.
Store login information in session and always check it. After logout, unset it.
What is the output of the following command
yum info phpMyAdmin
Which linux distro do you have? In Fedora (16) phpmyadmin is in the updates repository.
Sorry for my silence, I was away for some time.
I forgot to initialize the $current_record variable before the while loop. As Biim said put the missing line before the while loop begins.
Add a variable that counts record and check in the loop whether is odd or even. If it is odd then you start the row and the cell, if it is even end the cell and the row of the table.
function getBookSeller ()
{
$con = mysql_connect(server , userName , password ) or die('DataBase cannot connect. Reason: ' . mysql_errno());
mysql_select_db(db_name) or die('Table cannot connect. ' . mysql_errno());
$sql = "SELECT *
FROM book_sellers";
$result = mysql_query($sql, $con) or die('Query Error. ' . mysql_errno());
$totalrows = mysql_affected_rows();
$totalrows = ceil( $totalrows/2);
//echo $totalrows;
echo "<table width='600' border='1' cellspacing='2' cellpadding='3' bordercolor='#FFFFFF'>";
echo "<tr align='center'>";
echo "<td colspan='2' bordercolor='#000000' bgcolor='#9999CC'><b>Get
your copy today</b></td>";
echo "</tr>";
while($row = mysql_fetch_array($result))
{
// initialize output string
$output = "";
// if the current record is odd (1,3,5...) then start the row and the cell
if($current_record % 2 == 1) {
$output .= "<tr bordercolor='#CCCCCC'><td>";
}
$output .= "<b>".$row["book_shop"]."</b><br><br>";
$output .= "<b>Att: </b>".$row["name"]."<br>";
$output .= "<b>Add: </b>".$row["address"]."<br>";
$output .= "<b>Phone: </b>".$row["ph"]."<br>";
$output .= "<b>Fax: </b>".$row["fax"]."<br>";
$output .= "<b>Mobile: </b>".$row["mobile"]."<br>";
$output .= "<b>Email: </b>".$row["email"]."<br>";
$output .= "<b>Website: </b>".$row["website"]."<br>";
// if the current record is even (2,4,6...) then end the cell and the row
if($current_record % 2 == 0) {
$output .= "</td></tr>";
}
echo $output;
$current_record++;
}
// if the last row was odd then you have to end the row when out of the loop
if($current_record % 2 == 0) {
echo "</td></tr>";
}
echo "</table>";
}
To get the number of records in …
You are welcome and come back if you need more help. If you decide it is OK mark the thread as solved.
Give your select element a name that is an array (like bookshelf[]). Upon submision your post array will contain an array with selected values.
<form action='library.php' method='post'>
<select name='bookshelf[]' multiple='true'>
<option value="alice_s_wonderland">Alice's wonderland</option>
<option value="secret_seven">Secret Seven</option>
<option value="jonathan_livingston_sagull">Jonathan Livingston Seagull</option>
</select>
<input type="submit" name="submit" value="Submit books" />
</form>
And the library.php
<?php
// check if the form is submitted, the bookself array exists and is not empty
if(isset($_POST['submit']) && isset($_POST['bookshelf']) && !empty($_POST['bookshelf'])) {
// $_POST['bookshelf'] is an array of selected options, process it the way you like
// i.e. you can loop through it with foreach
// I will implode it into a comma separated string and display it
echo implode(', ', $_POST['bookshelf']);
} else {
echo 'No titles were selected. Go back and select at least one title.';
}
?>
One quick solution would be to produce csv file using fputcsv() function (see http://php.net/manual/en/function.fputcsv.php).
Another option is to read the data from the db table, create a html table and send appropriate headers to the browser that sees the table as an excel file:
<?php
// connect to the db and query the data from the table usual way
// ...
// begin the html table
$labels = '<table>';
// loop through the db result and add rows
while($row = mysqli_fetch_assoc($result)) {
$labels .= "<tr><td>{{$row['field1']}</td>";
$labels .= "<td>{{$row['field2']}</td>";
$labels .= "<td>{{$row['field3']}</td>"</tr>;
}
// end the html table
$labels .= '</table>';
// send the headers (make sure no content has been sent before)
// I found those on the web and must confess that haven't studied each one of
// them but they work fine for me
header("Pragma: no-cache");
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: application/x-msdownload");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=bia_values_1_8.xls ");
header("Content-Transfer-Encoding: binary ");
// echo the table with label data
// the browser should open/download it as an excel file
echo $labels;
?>
I use TCPDF for stufflike this. The following is adaption of example from tcpdf.org. Download the library, link to it and check it out. It is not perfect, you can fine tune it.
<?php
// some test data; you will read it from the database
$TEST_LABEL_DATA = array(
array(
'title' => 'Mr',
'fullName' => 'Bean',
'address' => '10 Bean st.',
'zipCode' => '10000',
'city' => 'London'),
array(
'title' => 'Ms',
'fullName' => 'Piggy',
'address' => '20 Muppet st.',
'zipCode' => '10001',
'city' => 'New York'),
array(
'title' => 'Herr',
'fullName' => 'Vladimir Putin',
'address' => '1 Weapon st.',
'zipCode' => '1000',
'city' => 'Moscow'),
array(
'title' => 'Mr',
'fullName' => 'Bean',
'address' => '10 Bean st.',
'zipCode' => '10000',
'city' => 'London'),
array(
'title' => 'Ms',
'fullName' => 'Piggy',
'address' => '20 Muppet st.',
'zipCode' => '10001',
'city' => 'New York'),
array(
'title' => 'Herr',
'fullName' => 'Vladimir Putin',
'address' => '1 Weapon st.',
'zipCode' => '1000',
'city' => 'Moscow'),
);
// make sure the path is correct
require_once('tcpdf.php');
// set page
$page_orientation = 'P';
$page_units = 'mm';
$page_format = 'A4';
// set top and left margin
$top_margin = 8;
$left_margin = 0;
// initialize object
$pdf = new TCPDF($page_orientation, $page_units, $page_format, true, 'UTF-8');
// set margins
$pdf->SetMargins(0, 0, -1, true);
//set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set font
$pdf->SetFont('times', '', 10);
// add a page
$pdf->AddPage();
// set cell padding
$pdf->setCellPadding(1);
// set cell margins
$pdf->setCellMargins(0, 0, 0, 0);
// set label dimensions (see the Avery label specification) …
Ocnsider that the user types in a URL abc.php or send it by email to someone else. I these cases $_POST would not contain any values and the script would display an error message. That is why you check with isset() and handle error yourself. The more complete code would be:
if(isset($_POST['agree'])) {
if($_POST['agree'] == 'yes') {
// code for YES here
} elseif($_POST['agree'] == 'no') {
// code for NO here
} else
// $_POST is set but does not contain value Yer or No
// error message "Please select Yes or No"
// (or redirect back to the form)
} else {
// $_POST is not set
// error message "Please select Yes or No"
// (or redirect back to the form)
}
You are missing value attributes for each radio button. The chosen value (only one) will get carried over to the abc.php page through $_POST global array. Note that you are also missing a submit button to submit the form. On abc.php start with checking if $_POST['agree'] is set which means the form has been submitted, and then process it.
<form action='abc.php' method='post'>
<label>YES</label>
<input type='radio' name='agree' value='yes' />
<label>NO</label>
<input type='radio' name='agree' value='no' />
<input type='submit' name='submit' value='Submit' />
</form>
Then on abc.php
if(isset($_POST['agree'])) {
if($_POST['agree'] == 'yes') {
// code for YES here
} elseif($_POST['agree'] == 'no') {
// code for NO here
}
}
Here are some hints:
Is this hapening in IE7 or IE8? Then maybe this link can help:
The above error has nothing to do with the office. It says that the file is not on the server. So the first thing you have to check is whether the link is correct.
If you want to open Office 2007 files and have Office 2003 then you can download Microsoft Office Compatibility Pack for Word, Excel, and PowerPoint at http://office.microsoft.com/en-us/support/microsoft-office-compatibility-pack-for-word-excel-and-powerpoint-HA010168676.aspx
If you do not have Office 2003 then use LibreOffice or free MS viewers (I think they are available on web).
No problem, you owe me nothing :-). I have helped for shear pleasure and I always learn something from that, too.
Just a hint: to remember selections store selected calendars in the $_SESSION array. Seehttp://www.w3schools.com/php/php_sessions.asp. If you have troubles, come back.
Is the problem that the browser can not open the files with the above extensions? If that is the case you probably do not have the appropriate program to open the files (up to date MS Office version, viewer apps or LibreOffice) or browser component. What is actually the error you get?
OK, I am getting the picture. Let's make it step by step. Below is the code to display a form with three checkboxes and a submit button. If the form gets submited the script will read the events from selected tables and display those events. You can adapt this code to suit your requirements. Please note that I have changed the names of tables from table to calendar to make things clear and to avoid possible mistakes (I think it is not a good idea to use general terms or reserved words for variable names). See explanations in comments.
<?php
// if form was submitted and if array with calendar names exists and is not empty
if(isset($_POST['calendar']) && !empty($_POST['calendar']))
{
// connect to the database
$con = mysql_connect("","","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("", $con);
// process selected tables (calendars)
// - read events from each calendar
// - display events for that calendar
foreach($_POST['calendar'] as $calendar)
{
// query to read events from one calendar
$q_select = "SELECT * FROM $calendar ";
$result = mysql_query($q_select);
// display calendar name
echo "<h3>$calendar</h3>";
// list of events (i.e from three columns, separated with a <br />
// but you could display this in a html table)
while($row = mysql_fetch_row($result))
{
echo "<p>{$row[0]}<br />{$row[1]}<br />{$row[2]}</p>";
}
}
}
?>
<form method="post" action="#">
<input type="checkbox" name="calendar[]" value="calendar_A" checked="checked"/>Calendar A<br />
<input type="checkbox" name="calendar[]" value="calendar_B"/>Calendar B<br />
<input type="checkbox" name="calendar[]" value="calendar_C"/>Calendar C<br />
<input type="submit" name="submit" value="Submit">
</form>
…You do not read any variables for values from the form on previous page in the update_ac.php. You should assign the values from the $_POST array. This should go on top of the pdate_ac.php:
// check if the form was submitted
if(isset($_POST['Submit'])) {
// get the ID (cast it to integer if it is supposed to be integer)
$id = (int) $_POST['id'];
// get the title and escape it to avoid SQL injection
$title = mysql_real_escape_string($_POST['title']);
// get the content and escape it to avoid SQL injection
$content = mysql_real_escape_string($_POST['content']);
// get the description and escape it to avoid SQL injection
$discription = mysql_real_escape_string($_POST['discription']);
// now run the update query using the variables
mysql_query("UPDATE content SET title='$title', discription='$discription', content='$content' WHERE id='$id'");
mysql_close($con);
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='show.php'>View result</a>";
}
Where should the variable $one_table be drawn from? Does it somehow come from the form?
This is only my assumption since I still do not exactly understand what you want to do: in my previous post I gave you three posibilities to get the table names. For the example in that post I chose the last possibility - the user enters table names in the form, separated by space. So you end up with a string of table names and spaces between them. You use explode
function to convert this string into an array. The array of table names is then processed in a foreach
loop where $one_table
represents the current table name when you loop through the array of table names (see http://php.net/manual/en/control-structures.foreach.php). The array can contain one or more table names.
In the insert function, I am hoping that $table_name will become a table such that I can enter it into this statement "SELECT FROM table_name". Does this happen on the previous step?
Really hard to answer since I do not understand how you want to use the table names.
In the VALUES '$categories', should it read something like this? - VALUES ('{$_POST['columnA']}', '{$_POST['columnB']}', '{$_POST['columnC']}')";
I do not know what the role of categories is here. Maybe you describe the whole concept, what you want to achieve, what is the expected input, the table structures etc. Only after realy understanding what you want to do I can give you useful …
If you want to let users create their own tables you must use input form fields (one for each table or one for many tables separated by some character such as space or colon). Then you have to store all table names in an array which you will use in foreach loop:
If you let users choose their table names can be dangerous since they can unknowingly use mysql keywords. You can avoid that adding a prefix to each table. You might also make sure that different users do not use same names for table names.
The loop for inserting would be something like
<?php
// first check if the form was submitted
// and if it was process the queries
if(isset($_POST['Submit'])) {
// check if any table names were entered
if(isset($_POST['table']) and $_POST['table'] != '') {
// security first: escape the string to avoid SQL injections
$tables_string = mysql_real_scape_string($_POST['table']);
// prefix for tables
$prefix = 'usrtbl_';
// create tables array (table names are separated by spaces in this example)
$tables_array = explode(' ', $tables_string);
// proces tables
// the data for the fields is in the $categories variable …
How would you like to query the checked tables? Would you like to JOIN them or query each separately? What is the srtucture of tables? Are they the same? Sory for putting questions instad of answering :-)
First, do not think of yourself so negatively, mate. No-one is perfect and we all have our weaknesses as far as programming (and everything else) goes.
Your question is a bit unclear. What is the code that works and what is the code that does not work? Your queries above are incorrect as they are. What is the point of the foreach loop when you do not use $value anywhere?
INSERT INTO table (table) VALUES $categories
What is the purpose of this query? Do you have a column named 'table'? What is the table name?
$query = "SELECT () FROM table"
Something is missing in the above insert statement. And a semicolon is missing too.
Sorry, I've been away on holiday for a couple of days.
The problem is in line 14: echo"$image_id_g"
where you send some output to the browser. You can not use header() function once you send output to the browser since the headers are sent automatically before the output. Comment out line 14 and it should work. Also make sure that in the include file header.php
there is no output sent (not even a space).
If you realy must send output before header() function then use output buffering.
The redirection won't work if there was html output sent before it. You should put the if block to the beginning of the script (i.e. first check if the form was submitted) and then draw the form. There should be not even a space before the header.
<?php
if(isset($_SESSION['username'])) /*** user is loged in ***/
{
if($_SERVER['REQUEST_METHOD'] == 'POST') //user hit submit button
{
$user_id_s = $_SESSION['user_id'];
$image_id_g = $_POST['random'];
if(!$tester = mysql_query("SELECT * FROM image WHERE image_id = '$image_id_g' AND user_id = '$user_id_s'"))
{
$del_image = mysql_query("DELETE FROM image WHERE image_id = '$image_id_g'");
$del_comment = mysql_query("Delete From comment Where image_id = '$image_id_g'");
header('location:zoom.php');
} else {
// display the error message or handle the situation some other way
echo '<div>Error deleting th image.</div>';
}
}
}
?>
<form class="form" action = 'deleteimage.php' method = 'post'>
<input type='submit' class='button' value='Yes'>
<input type="hidden" name ="random" class="random" value="<?php echo($_GET['imgid']);?>" />
<br/><br/>
<br/>
<br/>
</form>
You get the error only after you click the yes button. Since the form gets submitted to itself and you have no querystring in your action attribute the $_GET array is empty. After deleting you should probably redirect user o the previous page. If this is so use header('location:zoom.php') or something like that.
if(isset($_SESSION['username'])) /*** user is loged in ***/
{
if($_SERVER['REQUEST_METHOD'] == 'POST') //user hit submit button
{
$user_id_s = $_SESSION['user_id'];
$image_id_g = $_POST['random'];
if(!$tester = mysql_query("SELECT * FROM image WHERE image_id = '$image_id_g' AND user_id = '$user_id_s'"))
{
$del_image = mysql_query("DELETE FROM image WHERE image_id = '$image_id_g'");
$del_comment = mysql_query("Delete From comment Where image_id = '$image_id_g'");
// redirect the user
header('location:zoom.php');
}
...
If you look at the html code of deleteimage.php in the browser does the hidden input have the required value (the image ID)?
If you echo the whole line then your version from the first post is OK. But maybe you should check if $row['image_id'] returns a valid value:
if(is_numeric($row['image_id']) and $row['image_id'] > 0) {
echo "<a href='deleteimage.php?imgid={$row['image_id']}'>Delete</a>";
} else {
echo 'An error has occurred.';
}
provided that the image ID is a numeric value.
I think you should echo the $row['image_id'] value like:
<a href='deleteimage.php?imgid=<?php echo $row['image_id'];?>'>Delete</a>
Apparently you already have three thumbnails generated for each video and you can just link to them. See http://www.reelseo.com/youtube-thumbnail-image/
Maybe you post it so the thread is complete. And if this is it please mark it as solved. Cheers.