I have a php script that generates 3 files:
A .txt file
A .php file
The Script works fine but one thing destroys the idyll, the script does not write the vars in the 2nd generated script (I have also tried . $var . ). Any help would be appreciated.
The Code:
<?php
$filename = uniqid(rand(), true) . '.php';
$fh = fopen($filename, "w+");
if($fh)
{
fwrite($fh, "<html><body>
<div align='center'>
Neue Nachricht erstellen<br><br>
<form action='' . $filenamebes . '' Method='post'>
Titel:<br>
<input name='Name' size='40'><br><br>
Inhalt:<br>
<textarea name='inhalt' cols='40' rows='12'
wrap='physical'></textarea><p>
<input type='submit' value='Absenden'>
</form><br><br>
<?php
$beitrag = file('' . $filenametxt . '');
krsort($beitrag);
foreach($beitrag as $ausgabe)
{
$ausgabe = stripslashes($ausgabe);
$zerlegen = explode('|', $ausgabe);
echo '
<table align=\'center\'
border=\'1\' cellspacing=\'0\'
cellpadding=\'5\' bordercolorlight=\'black\'
bordercolordark=\'black\' width=\'50%\'>
<tr>
<td>
Titel: <a href=\'mailto:$zerlegen[0]\'>$zerlegen[1]</a>
am $zerlegen[2]
</td>
</tr>
<tr>
<td>
$zerlegen[3]
</td>
</tr>
</table><br>
';
}
?>
</div>
</body>
</html>
");
}
fclose($fh);
$filenametxt = uniqid(rand(), true) . '.txt';
$fhtxt = fopen($filenametxt, "w+");
if($fhtxt)
{
fwrite($fhtxt, "");
}
fclose($fhtxt);
$filenamebes = uniqid(rand(), true) . '.php';
$fhbes = fopen($filenamebes, "w+");
if($fhbes)
{
fwrite($fhbes, "<html>
<head>
<title>Speichere Nachricht</title>
</head>
<body>
<?php
$user = {$_POST['Name']};
$user = htmlentities($user);
$inhalt = {$_POST['inhalt']};
$inhalt = htmlentities($inhalt);
$inhalt = str_replace('\n', '<br>', $inhalt);
$email = {$_POST['EMail']};
$email = htmlentities($email);
if ($inhalt == '' or $user == '')
{
echo 'Sie müssen das Feld \'Namen\'
und \'Inhalt\' ausfüllen';
}
else
{
$datum= date('d.m.Y H:i:s');
$eintrag='$email|$user|$datum|$inhalt';
$datei = fopen('' . $filenametxt . '', 'a');
fwrite($datei, '\n'.$eintrag);
fclose($datei);
echo 'Ihre Nachricht wurde erfolgreich gespeichert';
}
?>
<br>
<a href='' . $filename . ''>Zurück</a>
</body>
</html>");
}
fclose($fhbes);
echo "PHP = $filename TXT = $filenametxt BES = $filenamebes <br><br><a href='".$filename."'>ÖffnenPHP</a> <br><br><a href='".$filenametxt."'>ÖffnenTXT</a> <br><br><a href='".$filenamebes."'>ÖffnenBES</a>"
?>
You are using Super string format to build your string.
Super string means double quotes "".
here
fwrite($fh, "<html><body>
and you use php variables in the super string format. So php identify the variable as a string or whatever it contains
Ex :
$a="ABCD";
echo "$a"; // this will print ABCD
but when you do it this way
$a="ABCD";
echo '$a';// this will print $a
Here is the solution
fwrite($fh, '<html><body>
<div align="center">
Neue Nachricht erstellen<br><br>
<form action=" . $filenamebes . " Method="post">
Titel:<br>
<input name="Name" size="40"><br><br>
Inhalt:<br>
<textarea name="inhalt" cols="40" rows="12"
wrap="physical"></textarea><p>
<input type="submit" value="Absenden">
</form><br><br>
<?php
$beitrag = file(" . $filenametxt . ");
krsort($beitrag);
foreach($beitrag as $ausgabe)
{
$ausgabe = stripslashes($ausgabe);
$zerlegen = explode("|", $ausgabe);
echo "
<table align=\"center\"
border=\"1\" cellspacing=\"0\"
cellpadding=\"5\" bordercolorlight=\"black\"
bordercolordark=\"black\" width=\"50%\">
<tr>
<td>
Titel: $zerlegen[1]
am $zerlegen[2]
</td>
</tr>
<tr>
<td>
$zerlegen[3]
</td>
</tr>
</table><br>
";
}
?>
</div>
</body>
</html>
');
PHP is treating those terms "$filenamebes" "$zerlegen" as actual variables.
Because those variables don't exist, it will not write anything to the file.
Instead you should escape those variables like so: \$filenamebes. This will allow you to physically write $filenamebes to the file, and not have PHP search for its value (null).
Proof of concept:
<?php
$a = 'test';
$s = "\$a";
echo $s ."\n"; //will print '$a'
echo "---\n";
$s = "$a";
echo $s ."\n"; //will print 'test'
Related
I've read through a number of similar questions, so I know this has been answered before, but now my question is why isn't what I'm doing working?
I'm new to web development, developing a web form that passes the submitted data to a CSV file. What I currently do, is after all form validation is done on the form page "form.php", it sends the user to another page "submittedApplication.php", and in the same statement goes all of my code to push the data into a CSV.
What I NEED, is to pass one particular variable from "form.php", over to "submittedApplication.php". It's a reference number that I have a random generator for, on form.php.
In my code I use a function to create the reference number, I store it in a variable called $result. In the bottom of the validation I use
header('Location: submittedApplication.php?result={$result}');
to try and pass it over, and then in the second page I use
echo $_GET['result'];
to try and grab the variable.
If you spot it in my code, I've also tried the hidden input method, to no avail as well.
Here is my form.php main page
<!DOCTYPE html>
<html>
<?php
//Define variables and set to empty values
//###CUSTOMER DATA###
//Name
$custName= "";
$custNameError = "";
//Reference Number
$result = gen_uid();
//Error holders
$errors = ""; //Generic Error list at top of form, can be appended to
$error = 0; //Error Tally, If 0 = good. If 1 = error.
//Generates a 10 character random string with a prefix and current date attached
function gen_uid($l=10){
$prefix = "BLANK DATA#";
$str = "";
date_default_timezone_set('America/New_York');
$date = date("Y.m.d");
for ($x=0;$x<$l;$x++)
$str .= substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1);
echo $prefix . $str . "<br/>" . "Generated On: " . $date; }
//for testing
echo $result;
if($_SERVER["REQUEST_METHOD"] == "GET"){
$custName = "";
$custAddress = "";
}
else if ($_SERVER["REQUEST_METHOD"] == "POST") { // Checking null values in message.
$custName = $_POST['customername'];
$custAddress = $_POST['CustomerMailingAddress'];
$passedResult = $_POST['result'];
//################################## Form Validation #####################################
//CUSTOMER NAME
if(!isset($custName) || $custName == "")
{
$custNameError = "Name required";
$errors .= "Customer contact information required, Contractor optional.<br/>";
$custName = "";
$error = 1;
}
else{
$custName = $_POST['customername'];
}
if($error == 0)
{
echo "<input type='hidden' name='result' value='{$result}'/>";
//this is where the creating of the csv takes place
$cvsData = $custName . "," . $custAddress . "," . $custPhone . "," . $custMobile . "," . $custFax . "," . $custEmail . "," . $conName . "," . $conAddress . "," .
$custPhone . "," . $conPhone . "," . $custMobile . "," . $conMobile . "," . $custEmail . "," . $conEmail . "," . $accNum ."\n";
$fp = fopen("formTest.csv","a"); // $fp is now the file pointer to file $filename
if($fp){
fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file
}
header('Location: submittedApplication.php?result={$result}');
}
}
?>
<body>
<h2 align="center"><u>Service Request Application Form</u></h2>
<hr>
<h4>NOTES:</h4>
<div id="wrapper">
<br/>
<h3 class="error"><?php echo $errors; ?></h3>
<form method="post" align="center" name="applicationform" id="applicationform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" enctype="multipart/form-data">
<!--###################################### CONTACT INFORMATION FIELDSET ######################################-->
<fieldset style="border: 1px black solid" align="center">
<legend style="font-weight:bold"><u>Contact Information</u></legend>
<table>
<tr>
<th></th>
<th><u>Customer</u></th>
<th title="Electrician"><u>Consultant/Contractor</u></th>
</tr>
<tr>
<td>
<tr>
<td align="right" id="namelabel">Contact Name:</td>
<td><input type="text" id="customername" name="customername" value="<?php echo $custName;?>" title="Name of contact on account"/></td>
<td><input type="text" id="contractorname" name="contractorname" title="Name of contractor or consultant" /></td>
</tr>
<tr>
<td></td>
<td><div class="error"><?php echo $custNameError;?></div></td>
<td></td>
</tr>
</td>
</tr>
</table>
</table>
</form>
</div>
</body>
</html>
And here is my second page submittedApplication.php
<!DOCTYPE html>
<html>
<body>
<h2 align="center"><u>Service Request Application Form</u></h2>
<hr>
<h4>NOTES:</h4>
<hr>
<div align="center"><h3>Application Submitted Successfully!</h3> </div>
<?php
echo $_GET['result'];
?>
</body>
</html>
Any and all tips are appreciated!
The way I would normally tackle passing values between pages is to use session variables.
You can do this in your form.php page
session_start();
$SESSION_["result"] = $result;
Then do the following in your other page
session_start();
if(isset($SESSION_["result"]) {
$result = $SESSION_["result"];
}
Just make sure you destroy or unset any session variables when you're done with them.
Exactly what the title says. My PHP written after an the an if statement to check if a text portion of a form has any value is not running. It works fine in one written earlier in my code, but not the second time.
Here is my whole code:
<?php include '../header.php'; include '../navigation.php'; ?>
<div id="pageContent">
<form name="format" method="POST" action="phpFunctions.php">
Please input date:
<input type="date" name="date" value="<?php echo date('Y-m-d'); ?>" />
<input type="submit" name"submit1" value="Format" />
</form>
<?php
if (isset($_POST['date'])) {
$new_date = $_POST['date'];
$date = new DateTime($new_date);
echo 'M-D-Y Format: ' . $date->format('m-d-Y') . '<br>';
echo 'D-M-Y Format: ' . $date->format('d-m-Y');
}
?>
<form name="stringStuff" method="POST" action="phpFunctions.php">
Enter string:
<input type="text" name"yourString">
<input type="submit" name"submit2" value="Parse" />
</form>
<?php
if (isset($_POST['yourString']) && !empty($_POST['yourString'])) {
echo 'ayyyyyy lmao';
$new_string = $_POST['theString'];
$trimmed_string = trim($new_string);
echo 'ayyyyyy lmao';
echo 'String Length: ' . strlen($new_string) . '<br>';
echo 'Trim Whitespace: ' . $trimmed_string . '<br>';
echo 'Lowercased: ' . strtolower($new_string) . '<br>';
if(strpos($new_string, 'DMACC') !== false) {
echo 'String contains DMACC';
}
else {
echo 'String does not contain DMACC';
}
}
?>
</div>
<?php include '../footer.php'; ?>
The portion of the code that isn't working is this portion after what I mentioned
if (isset($_POST['yourString']) && !empty($_POST['yourString'])) {
echo 'ayyyyyy lmao';
$new_string = $_POST['theString'];
$trimmed_string = trim($new_string);
echo 'ayyyyyy lmao';
echo 'String Length: ' . strlen($new_string) . '<br>';
echo 'Trim Whitespace: ' . $trimmed_string . '<br>';
echo 'Lowercased: ' . strtolower($new_string) . '<br>';
if(strpos($new_string, 'DMACC') !== false) {
echo 'String contains DMACC';
} else {
echo 'String does not contain DMACC';
}
}
you missed = , name="yourString"
<form name="stringStuff" method="POST" action="test_index.php">
Enter string:
<input type="text" name="yourString">
<input type="submit" name="submit2" value="Parse" />
</form>
It seems you are missing name="yourString"
<input type="text" name="yourString">
<input type="submit" name="submit2" value="Parse" />
I'm looking for help with my products list.
My Code:
<!DOCTYPE html>
<html>
<head>
<title> Produktliste </title>
</head>
<body>
<iframe name="dir" style="display:none;"></iframe>
<form action="shop.php" method="post">
<p> <h2> Produkt hinzufügen </h2> </p>
<p> Produktname: <input type="text" name="Produktname"/> </p>
<p> Produktbeschreibung: <textarea rows=2 cols=20 name="Produktbeschreibung"></textarea> </p>
<p> Preis: <input type="text" name="Preis"/> </p>
<input type="submit" name="speichern" value="Speichern"/>
</form>
<?php
$connect = new mysqli ('localhost', 'root', '');
$connect->select_db('shop');
if (#$_REQUEST["Produktname"] && #$_REQUEST["Produktbeschreibung"] && #$_REQUEST["Preis"]) {
$produktname = #$_REQUEST["Produktname"];
$beschreibung = #$_REQUEST["Produktbeschreibung"];
$preis = #$_REQUEST["Preis"];
$result = $connect->query("INSERT INTO `shop`.`produkte` (`Produktname`, `Beschreibung`, `Preis`) VALUES ('$produktname', '$beschreibung', '$preis');");
if(!$result) {
echo "SQL Fehler: " . $connect->error;
die;
} else { echo "Letzte ID: " . $connect->insert_id;
}
}
?>
<table border="2" width="30%" style="border:1px solid #000000; border-spacing:inherit; text-align:left;">
<br><br>
<tr>
<td> Produkt </td>
<td> Beschreibung </td>
<td> Preis </td>
<td> Funktionen </td>
<?php
$result = $connect->query("SELECT * FROM produkte");
while($obj = $result->fetch_object()) {
echo '<tr><td>' . $obj->Produktname . '</td><td>' . $obj->Beschreibung . '</td><td>' . $obj->Preis . ' EUR ' . '</td><td> Bearbeiten, Löschen </td></tr>';
}
?>
</tr>
</table>
<?php
if (isset($_REQUEST["delete"])) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlpart = explode('=', $url);
$ProduktID = end($urlpart);
$result = $connect->query("DELETE FROM `shop`.`produkte` WHERE `ProduktID` = $ProduktID;");
header('Location: ./shop.php');
}
if(isset($_REQUEST["id"])) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlpart = explode('=', $url);
$ProduktID = end($urlpart);
// Update SQL Data?
}
if (!$result) {
echo "SQL Fehler: " . $connect->error;
die;
}
?>
</body>
</html>
I'm now looking for a way to retrieve the MySQL Data with the equivalent ID into the existing HTML Form and update it back to the MySQL Database... I'm currently learning PHP at the University and I can't think any further by myself.
It needs to get done withing this PHP File, like everything else is.
Thanks for any help! :)
If I understand you correct, you want to echo inserted row from database. Change the line:
$result = $connect->query("SELECT * FROM produkte");
into:
$result = $connect->query("SELECT * FROM produkte WHERE ID_prod_column = '$insertID'");
Try something like this. Just change "ID_prod_column" to correct name and $insertID to correct variable.
I am using a wordpress plugin that fetches stock quote feed from Yahoo finance. IT JUST HAPPENS VERY RARELY... OTHERWISE IT DON'T SHOW UP. I randomly get fatal error saying on line 140 ... and line 140 is break; i am copying below quote to understand the code. EDIT: NOW I HAVE PUT THE ENTIRE PHP FILE...!!
<?php
/*
Plugin Name: Stock Quotes
Plugin URI: http://www.dagondesign.com/articles/stock-quotes-plugin-for-wordpress/
Description: Displays stock quotes on your website
Author: Dagon Design
Version: 1.0.1
Author URI: http://www.dagondesign.com
*/
$ddsq_version = '1.0.1';
// Setup defaults if options do not exist
add_option('ddsq_format', '%NAME%: %LAST% ( %CHANGE% )');
add_option('ddsq_up_color', '00BB00');
add_option('ddsq_down_color', 'FF0000');
add_option('ddsq_update_time', '10');
function ddsq_add_option_pages() {
if (function_exists('add_options_page')) {
add_options_page('Stock Quotes', 'DDStockQuotes', 8, FILE, 'ddsq_options_page');
}
}
function ddsq_options_page() {
global $ddsq_version;
if (isset($_POST['set_defaults'])) {
echo '<div id="message" class="updated fade"><p><strong>';
update_option('ddsq_format', '<strong>%NAME%</strong> %LAST% [<strong>%CHANGE%</strong>]');
update_option('ddsq_up_color', '00BB00');
update_option('ddsq_down_color', 'FF0000');
update_option('ddsq_update_time', '10');
echo 'Default Options Loaded!';
echo '</strong></p></div>';
} else if (isset($_POST['info_update'])) {
update_option('ddsq_format', (string) $_POST["ddsq_format"]);
update_option('ddsq_up_color', (string) $_POST["ddsq_up_color"]);
update_option('ddsq_down_color', (string) $_POST["ddsq_down_color"]);
update_option('ddsq_update_time', $_POST["ddsq_update_time"]);
echo 'Configuration Updated!';
echo '</strong></p></div>';
} ?>
<div class=wrap>
<h2>Stock Quotes v<?php echo $ddsq_version; ?></h2>
<p>For information and updates, please visit:<br />
http://www.dagondesign.com/articles/stock-quotes-plugin-for-wordpress/</p>
<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
<input type="hidden" name="info_update" id="info_update" value="true" />
<h3>Usage</h3>
<p>There are two ways you can display quotes:</p>
<p><strong>1) In a post or page</strong>
<br />
[stock MSFT]</p>
<p><strong>2) In a template file</strong>
<br />
<?php echo ddsq_get_quote('MSFT'); ?></p>
<h3>Options</h3>
<table width="100%" border="0" cellspacing="6" cellpadding="4">
<tr valign="top"><td width="13%">
<strong>Output Format </strong>
</td><td align="left">
<input name="ddsq_format" type="text" size="100" value="<?php echo htmlspecialchars(stripslashes(get_option('ddsq_format'))) ?>"/>
<br />Placeholders for data: <strong>%NAME% %LAST% %CHANGE%</strong>
</td></tr>
<tr valign="top"><td width="13%">
<strong>Up Color </strong>
</td><td align="left">
<input name="ddsq_up_color" type="text" size="7" value="<?php echo get_option('ddsq_up_color') ?>"/>
Color to use for price change when up (leave blank to disable)
</td></tr>
<tr valign="top"><td width="13%">
<strong>Down Color </strong>
</td><td align="left">
<input name="ddsq_down_color" type="text" size="7" value="<?php echo get_option('ddsq_down_color') ?>"/>
Color to use for price change when down (leave blank to disable)
</td></tr>
<tr valign="top"><td width="13%">
<strong>Update Time </strong>
</td><td align="left">
<input name="ddsq_update_time" type="text" size="3" value="<?php echo get_option('ddsq_update_time') ?>"/>
Number of minutes to wait, before fetching updated stock prices
</td></tr>
</table>
<div class="submit">
<input type="submit" name="set_defaults" value="<?php _e('Load Default Options'); ?> »" />
<input type="submit" name="info_update" value="<?php _e('Update options'); ?> »" />
</div>
</form>
</div><?php
}
function ddsq_get_quote($symb) {
$up_color = trim(get_option('ddsq_up_color'));
$down_color = trim(get_option('ddsq_down_color'));
$quote_format = stripslashes(get_option('ddsq_format'));
$update_time = trim(get_option('ddsq_update_time'));
$update_time = $update_time * 60;
$t_out = '';
$time_diff = '';
// Trying to open local cached file first
$file_path = WP_PLUGIN_DIR . "/" . $symb . ".txt";
if (file_exists($file_path)){
$time_diff = date('U') - filemtime($file_path);
}
$lf = #fopen($file_path, "r");
if (($lf == FALSE) || ($time_diff >= $update_time)) {
$url = "http://finance.yahoo.com/d/quotes.csv?s=" . $symb . "&f=sl1c1";
$fp = #fopen($url, "r");
if ($fp == FALSE) {
#$t_out = 'Error opening: ' . htmlspecialchars($url);
break;
} else {
$array = #fgetcsv($fp , 4096 , ', ');
#fclose($fp);
$sq_name = $array[0];
$sq_last = $array[1];
$sq_change = $array[2];
$col = NULL;
if (($sq_change[0] == '-') && ($down_color != '')) {
$col = $down_color;
} else if (($sq_change[0] == '+') && ($up_color != '')) {
$col = $up_color;
}
if ($col !== NULL) {
$sq_change = '<span style="color: #' . $col . ';">' . $sq_change . '</span>';
}
$t_out = $quote_format;
$t_out = str_replace('%NAME%', $sq_name, $t_out);
$t_out = str_replace('%LAST%', $sq_last, $t_out);
$t_out = str_replace('%CHANGE%', $sq_change, $t_out);
$cache_file = fopen($file_path, "w+");
fwrite($cache_file, $t_out);
}
} else {
fclose($lf);
$t_out = file_get_contents($file_path);
if ($t_out == FALSE){
echo "ERROR opening cache file";
}
}
return $t_out;
}
function ddsq_process($content) {
$results = array();
preg_match_all("/\[\s?stock\s?(.*)\s?\]/", $content, $results);
$i = 0;
foreach ($results[0] as $r) {
$content = str_replace($r, ddsq_get_quote($results[1][$i]), $content);
$i++;
}
return $content;
}
add_filter('the_content', 'ddsq_process');
add_action('admin_menu', 'ddsq_add_option_pages');
?>
As far as I can see there is no loop or control structure (like switch), that accepts break; within itself. I guess, that you sometimes call this code within a loop. In this case break; is allowed. But sometimes it's not. At all break; doesn't make any sense within an if-block.
I´m not sure if a file-pointer can evaluate to false, but when checking fopen for errors, you need to use:
if ($fp === FALSE)
Apart from that, take a look at #mhitza's comment.
first I want to say that I'm a beginner in postgresql and php.. my company told me to create a database that they can view and edit on local server.. so I created the database in postgresql.. created a page that views the database:
<html>
<head>
<title>Ongoing projects</title>
</head>
<body bgcolor="666657">
<?php
//database access information
require_once("DB.php");
$host = "localhost";
$user = "admin";
$pass = "";
$db = "Project_list";
$port = "5432";
//open a connection to the database server
$connection = pg_connect("host=$host dbname=$db user=$user password=$pass port=$port");
if (!$connection)
{
die("Could not open connection to database server");
}
?>
<?php
$query = 'select * from ongoing';
$result = pg_query($query); $i = 0;
echo '<html><table bgcolor="666657" width="10" height="30" border="0" cellpadding="0" cellspacing="0"><td align="center"> <h1><font color = "#ffb200"> Ongoing projects</h1>';
echo '<html><body><table border= 2 BORDERCOLOR="000000" cellpadding="1" cellspacing="0"> <tr >';
while ($i < pg_num_fields($result)) {
$fieldName =pg_field_name($result, $i);
echo '<b>'.'<td width="2" bgcolor="666657" align="center">'.'<font color = "#ffb200">'. '</b>'.'<b>'. $fieldName . '</b>'. '</td>';
$i = $i + 1; }
echo("<td><align= center><font color = #ffb200><b>Action</td>");
echo '</tr>' ;
$i = 0;
while ($row = pg_fetch_row($result)) {
echo '<tr align="center" width="1">';
$count = count($row);
$y = 0;
while ($y < $count) {
$c_row = current($row);
echo '<td>' .'<font color = "#ffb200">'. $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo("<td><align= center><a href='editongoing.php?ProjectID=".$row[0]."'>Edit</a></td>");
echo '</tr>';
$i = $i + 1;
}
pg_free_result($result);
echo '</table></body></html>';
?>
<h3>
<a href="projects.php"</a>Back to projects page</a>
</h3>
<SCRIPT LANGUAGE="JavaScript">
if (window.print) {
document.write('<form> '
+ '<input type=button name=print value="Click" '
+ 'onClick="javascript:window.print()"> To Print!</form>');
}
// End -->
</script>
when you click the edit button, you will go to this page where you can edit the raw you want, this is the (edit) code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Edit Ongoing projects</title>
</head>
<body bgcolor="666657">
<?php
// attempt a connection
$connection = pg_connect("host=localhost dbname=Project_list user=admin password=");
if (!$connection) {
die("Error in connection: " . pg_last_error());
}
if ($_REQUEST['ProjectID']!=''){
$QueryStr = "Select * from ongoing where project_no='".$_REQUEST['ProjectID']."'";
$result = pg_query($connection, $QueryStr);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
$row = pg_fetch_row($result);
print_r($row);
}
if ($_POST['submit']) {
// escape strings in input data
$project_no = pg_escape_string($_POST['project_no']);
$title = pg_escape_string($_POST['title']);
$duration = pg_escape_string($_POST['duration']);
$manager = pg_escape_string($_POST['manager']);
$country = pg_escape_string($_POST['country']);
$total_fee = pg_escape_string($_POST['totalfee']);
$performed = pg_escape_string($_POST['performed']);
$remaining = pg_escape_string($_POST['remaining']);
$gross_profit = pg_escape_string($_POST['gross_profit']);
$gp = pg_escape_string($_POST['gp']);
$performance_year = pg_escape_string($_POST['performance_year']);
$gp_year = pg_escape_string($_POST['gp_year']);
// execute query
$sql = "INSERT INTO ongoing (project_no, project_title, duration, manager, country, total_fee,
performed, remaining, gross_profit, gp, performance_year, gp_year)
VALUES('$project_no', '$title', '$duration', '$manager', '$country','$total_fee','$performed','$remaining',
'$gross_profit','$gp', '$performance_year','$gp_year')";
$result = pg_query($connection, $sql);
f (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($connection);
}
?>
<form action= "<?php echo $_SERVER['PHP_SELF']; ?>" method="post"><b><font color = "#ffb200">
Project No.: <br> <input id="project_no" type="text" name="project_no" size="20" value=<?= $row[0] ?>>
<p>
Project Title: <br> <input id="title" type="text" name="title" value='<?= $row[1] ?>'>
<p>
Duration: <br> <input ID="duration" type="text" name="duration" value=<?= $row[2] ?>>
<p>
Project Manager: <br> <input ID="manager" type="text" name="manager" value=<?= $row[3] ?>>
<p>
Country: <br> <input ID="country" type="text" name="country" value=<?= $row[4] ?>>
<p>
Total Fee: <br> <input ID="totalfee" type="text" name="total_fee" value=<?= $row[5] ?>>
<p>
Already performed: <br> <input ID="performed" type="text" name="performed" value=<?= $row[6] ?>>
<p>
Remaining performance: <br> <input ID="remaining" type="text" name="remaining" value=<?= $row[7] ?>>
<p>
Gross Profit: <br> <input ID="gross_profit" type="text" name="gross_profit" value='<?= $row[8] ?>'>
<p>
GP%: <br> <input ID="gp" type="text" name="gp" value=<?= $row[9] ?>>
<p>
Performance actual year: <br> <input ID="performance_year" type="text" name="performance_year" value=<?= $row[10] ?>>
<p>
GP actual year: <br> <input ID="gp_year" type="text" name="gp_year" value=<?= $row[11] ?>>
<p>
<input type="submit" name="submit" value="Sumbit my table" size="30">
<P>
<a href="ongoing.php"</a>View ongoing projects</a>
<a href="editproject.php"</a>Back to editing menu</a>
</form>
</body>
</html>
My problem is, when I edit the data and click on submit my table, a new raw is inserted.. but I want it to be updated not inserted... help plz
You need to select which record (id number) you want to update, and then your query will look like
$sql = "UPDATE ongoing SET field1='value', field2='value' ... WHERE id = 'id of project you want to edit'";