Edit Page PHP for Mysql Data - php

I'm stucked. I have some pages to edit fields on my database. I can see the tasks and i want to edit them by clicking in "edit" button and redirects to a page where will be displayed the info about that task using the "Nome"(Name), since its unique, but i can't manage how to transfer the name from one page to another.
The code is:
eventos.tarefas.php
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td width=5%>" . $row[Nome] . "</td>";
(...)
echo "<td width=10%>" . $row['Evento'] . "</td>";
echo ("<td>Editar</td></tr>"); //I'm stuck in this line
echo "</tr>";
}
editar_tarefa.php
<?php
$con=mysqli_connect("","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tarefas WHERE Nome= '$Nome'");
echo $Nome;
while($row = mysqli_fetch_array($result))
{
?>
<table width="744" height="697">
<tr>
<td width="188" height="10"><p style="font-size:30px; font-family:verdana;">ID</p></td>
<td>
<input type="text" readonly name="ID" size="20" value="<?php echo "$row[ID]"?>" style="width: 400px; height:30px; font-size:150%;background-color:#EEE9E9">
</td>
</tr>
<tr>
(...) and so on...
I usually use POST to show the data on database, but i want this to be different.
Can someone help me?
Thanks.

Use $_GET['Nome'] to get the value of the URL parameter. You'd need to assign it to a variable ($Nome) before you make your query, obviously
As you are making a query with user-editable data, you should look into using prepared statements for security.

Use Session
<?php
session_start();
// store session data
$_SESSION['name']=$row[Nome]; // $_SESSION['name'] will carry your data until session end
?>
On another page
<?php
session_start();
// store session data
$nome=$_SESSION['name'];
?>
Refer http://www.w3schools.com/php/php_sessions.asp

Related

Select multiple options from option

So I have a selector which gets its information from a database.
When I select something from the selector and press: Add to list, it generates a table with the selected information.
Now this what it should do. But now, when I select another result and press Add to list. It removes the old one and replaces it with the new one.
But I actually don't want it to remove the old one, but make a new row under it. So that table gets bigger. How do I do this?
Code for selector:
<!--Selector-->
<?php
//Get name and id data from the db. In an assoc array
$results = $database->Selector();
echo "<form name='form' method='POST' id='selector'>";
echo "<select name='train_name' id='train_name' multiple='multiple'>";
// Loop trough the results and make an option of every train_name
foreach($results as $res){
echo "<option value=" . $res['train_name'] . ">" . $res['train_name'] . "</option>";
}
echo "</select>";
echo "<br />" . "<td>" . "<input type='submit' name='Add' value='Add to list'/>" . "</td>";
echo "</form>";
if(isset($_POST["train_name"])){
//Get all data from database, in an assoc array
$results = $database->getAllAssoc();
//Make table headers
?>
<div id="train_select_table">
<form name="selector" method="post" action="customer_list.php?user_id=<?php echo $_SESSION['user_id']?>">
<table>
<tr>
<th>Train name</th>
<th>Number of bogies</th>
<th>Number of axles</th>
<th>Delete</th>
<th>More info</th>
<th>Check</th>
<!--Only for admins (later!)-->
<!--<th>XML</th>
<th>SQL</th> -->
</tr>
<div id="looprow">
<?php
foreach($results as $res){
//Loop trough results, generate a tablerow every time
?>
<tr>
<td name="train_name"><?php echo $res['train_name']?></td>
<td><?php echo $res['number_of_bogies']?></td>
<td><?php echo $res['number_of_axles']?></td>
<td>Delete</td>
<td>More Information</td>
<td><input type="checkbox" name="checkbox[]" value="<?php echo $res['train_id']?>"></td>
<!--Only for admins (later!)-->
<!--<td>XML</td>
<td>SQL</td>-->
</tr>
<?php
}
?>
</div>
</table><br />
<input name="Add to list" type="submit" id="add_to_list" value="add_to_list">
</form>
</div>
<?php
}
?>
Function:
function getAllAssoc() {
$sql = "SELECT * FROM train_information WHERE train_name = :train_name";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(":train_name", $_POST["train_name"]);
$sth->execute();
return $sth->fetchAll();
}
function selector() {
$sql = "SELECT train_name, train_id FROM train_information";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
I understand why it keeps replacing the old row. this is because I send a new query. but I don't know how to keep the old one.
as each time user will chose a single value while not mutiple value, so if you want to use the new value and the old value too, you should store the old value using cookie or session or hidden input in that form. It depends on you.
E.g. at the beginning, do this:
<?php
session_start();//make it be before your output if you want to use session or cookie
if(!$_SESSION['train_name']) $_SESSION['train_name'] = array();
if(isset($_POST["train_name"])) $_SESSION['train_name'] = array_merge ($_SESSION['train_name'], $_POST["train_name"]);
.......
//next step, inquiry with $_SESSION['train_name']
Simply change the name of your multiple select list from train_name to train_name[] as follows:
...
echo "<select name='train_name[]' id='train_name' multiple='multiple'>";
...
By this way your $_POST['train_name'] will be an array passed to bindParam

How to delete multiple rows from mysql database with checkbox using PHP?

I try to delete my data in "admin" database, but the delete button does not function.
This is my top part
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="admin"; // Database name
$tbl_name="admin"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
This is my checkbox code
<tbody>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $rows['course_code']; ?></td>
<td><?php echo $rows['course_name']; ?></td>
<td><?php echo $rows['lecture_id']; ?></td>
<td><input name="checkbox[]" type="checkbox"
id="checkbox[]" value="<?php echo $rows['course_code'];?>"></td>
<td><form>
</form>
</td>
</tr>
<?php
}
?>
</tbody>
and, this is my button code
<input type='button' id="delete" value='Delete' name='delete'>
This is my php function code
<?php
if(isset($_POST['delete'])){
for($i=0;$i<$count;$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM $tbl_name WHERE course_code='$del_id'";
$result = mysql_query($sql);
}
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete.php\">";
}
}
mysql_close();
?>
include all the input elements within your <form> tags: <form> all inputs are here </form>
update:
<input name = "checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $rows['course_code'];?>">
to (id doesn't matter here):
<input name="checkbox[]" type="checkbox" value="<?php echo $rows['course_code'];?>"/>
and your button code:
<input type='button' id="delete" value='Delete' name='delete'>
to
<input type="submit" value="Delete"/>
set opening <form> tag to <form action="delete.php" method="post">
Note:
I assume below codes are in delete.php file. if not replace "delete.php" with that name in above opening form tag.
your delete.php file:
<?php
$cheks = implode("','", $_POST['checkbox']);
$sql = "delete from $tbl_name where course_code in ('$cheks')";
$result = mysql_query($sql) or die(mysql_error());
mysql_close();
?>
Note:
Since mysql_ will deprecate on future, better is use mysqli extension. But before use that, you have to enable it on your server. mysqli is a part of php and newer version of php has it but not enabled. To enable this, view php info page and find the path of php.ini file in "Loaded Configuration File" row on that page.
You can see php info page by loading below php file in the browser:
<?php
phpinfo();
?>
open that php.ini file in a text editor and un-comment or add a line extension=php_mysqli.dll at the extensions list there.
also search for "extension_dir" and open the directory it says and make sure php_mysqli.dll file is there.
(you may have .so extension if you not use windows OS)
Then restart your server and you are done!
By Fred -ii-
Using mysqli_ with prepared statements is indeed a better and
safer method. However, some will even suggest PDO, but even PDO
doesn't have some of the functionalities that mysqli_ offers;
strangely that. Even PDO needs sanitization. Many think that using PDO will solve injection issues, which is false.
-Thanks Fred.
try this code. it is working well.
connection.php
<?php $hostname_conection = "localhost"; /* this is the server name(assigned to variable) which is localhost since it runs on local machine */
$database_conection = "company"; /* this is the database name( assigned to variable)*/
$username_conection = "root"; /* user name (assigned to variable)*/
$password_conection = ""; /*password (assigned to variable) */
$conection = mysql_connect($hostname_conection, $username_conection, $password_conection) or trigger_error(mysql_error(),E_USER_ERROR); /* Mysql_connect function is used to conncet with database it takes three parameters server/hostname, username,and password*/
mysql_select_db($database_conection,$conection) or die(mysql_error("could not connect to database!")); /* Mysql_select is used to select the database it takes two parameters databasename and connection variable in this case $conection */
?>
multiple_delete.php
<?php require_once('conection.php'); ?>
<?php
in
/* now to display the data from the database which we inserted in above form we */ /* we make the query to select data from the table EMP */
$display = "select * from test_mysql";
$result = mysql_query($display, $conection) or die(mysql_error()); /* the query is executed and result of the query is stored in variable $result */
if ($result == FALSE) {
die(mysql_error()); /* displays error */
} ?> <h1 align="center"> Displaying Recods in Table </h1>
<form method="get" action="" id="deleteform" >
<table width="245" border="1" align="center">
<tr>
<td width="51">
<input type="submit" name="delete" id="button" value="delete" onclick="document.getElementById('deleteform').action = 'delete.php';document.getElementById('deleteform').submit();"/> <!--- here on clicking the button the form is submitted and action is set to delete.php Here we have used javaScript document refers to this whole page and now we can access any tag that has its id with help of getElementById() method and after the we specify the operation we want to perform in this case action and submit. --->
</td>
<td width="50">id</td>
<td width="55">name</td>
<td width="47">lastname</td>
</tr>
<?php
while ($rows = mysql_fetch_array($result))
{ /* here we make use of the while loop which fetch the data from the $result int array form and stores in $row now we can display each field from the table with $row[‘field_name’] as below */
?>
<tr>
<td>
<input type="checkbox" name="empids[]" value="<?php echo $rows['id']; ?>" /> <!--here with each checkbox we send the id of the record in the empids[] array --->
</td>
<td>
<?php echo $rows['id'] ?>
</td>
<td>
<?php echo $rows['lastname'] ?>
</td>
<td><?php echo $rows['name'] ?></td>
<?php } ?>
</tr>
</table>
</form> ?>
</body>
</html>
delete.php
<?php
require_once('conection.php');
?>
<?php
if (isset($_GET['delete'])) /* checks weather $_GET['delete'] is set*/
{
if (isset($_GET['empids'])) /* checks weather $_GET['empids'] is set */
{
$checkbox = $_GET['empids']; /* value is stored in $checbox variable */
if (is_array($checkbox))
{
foreach ($checkbox as $key => $your_slected_id) /* for each loop is used to get id and that id is used to delete the record below */
{
$q="DELETE FROM test_mysql WHERE id=$your_slected_id "; /* Sql query to delete the records whose id is equal to $your_slected_id */
mysql_query($q,$conection) ; /* runs the query */
}
header("location:multiple_delete.php"); /* Goes back to index.php */
}
} else
{
echo" you have not selected reords .. to delete";
}
} ?>
$sql = "SELECT * FROM blacklist";
$result = $link->query($sql);
$count=mysqli_num_rows($result);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc())
{
echo "<table>";
echo "<th>";
echo "<td>" . "ID: " . $row["id"]."</td>";
echo "<td>" . " Dial Target: " . $row["dial_target"]."</td>";
echo "<td>" . " Destination: " . $row["pozn"]."</td>";
echo "<td>" . " Date: " . $row["block_date"] . "</td>";
echo "<td>" . "<div class='background' style='position: relative; top:8px;'>" . "<form>" . "<input action='index.php' method='post' type='checkbox' name='chechbox[]' value='".$row["id"]."'/>" ."</form>" . "</div>" . "</td>";
echo "</th>";
echo "</table>";
echo "</br>";
}
}
else
{
echo "0 results";
}
if(isset($_POST['Delete']))
{
for($i=0;$i<$count;$i++)
{
$del_id = $checkbox[$i];
$del = "DELETE FROM blacklist WHERE Delete='$del_id'";
$result = $link->query($del);
}
if($result)
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=index.php\">";
}
}
<!-- DELETE BUTTON -->
<form>
<input type='Submit' id="Delete" value='Delete' name='Delete'/>
</form>
<?php
$args1 = array(
'role' => 'Vendor',
'orderby' => 'user_nicename',
'exclude' => $user_id.',1',
'order' => 'ASC'
);
$subscribers = get_users($args1); foreach ($subscribers as $user) {
$fvendorck = $wpdb->get_row("select * from wp_vandor where parent_id = '".$user_id."' and child_id = '".$user->id."'");
$isfavvendor = $fvendorck->child_id;
if(!empty($isfavvendor)) {
?>
<li><input type="checkbox" id="listID" value='<?php echo $user->id; ?>' name="chk1[]" checked=""/><?php echo $user->headline; ?></li>
<?php }else{ ?>
<li><input type="checkbox" id="listID" value='<?php echo $user->id; ?>' name="chk1[]" /><?php echo $user->headline; ?></li>
<?php } }?>
</ul>

How to write an update SQL statement to update multiple records

I have this code so far, which reads a simple table with 3 varchar fields:
<?php
//db connection code...
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$query = "SELECT * FROM Sheet1";
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<html><body><table cellpadding=10 border=1>";
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['stickerID']."</td>";
echo "<td>" .$row['stickerName']."</td>";
echo "<td>".$row['stickerSection']."</td>";
echo "<td>"?>
<form name="some form" action="editform.php" method="post">
<input type="checkbox" name="<?php echo $row['stickerID'] ?>" value=" <?php echo $row['stickerStatus'] ?> ">
<?php "</td>";
echo "</tr>";
}
echo "</table></body></html>";
echo " " ?>
<input type="submit" name="editWish" value="Edit">
</form>
<?php " ";
} else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
The database has 4 fields, 3 varchar and 1 int with current value of 0. I checked the page source code and confirmed each checkbox name is the stickerID. Now I will post this to the editform.php which I must create. What Im wondering is how should I write the update sql so that it takes into account each new value selected by the user in the form?
This is my idea, but how to I do it for every checkbox?
editform.php
<?php
//update multiple records
//UPDATE user_items SET stickerStatus = $_POST["stickerStatus"] WHERE stickerID = $_POST["stickerID"];
?>
First question: use mysql_fetch_assoc() instead of mysql_fetch_row(). That will return an associative array instead of an enumerated one.
Second question: read up on HTML forms and form handling.
The answer to the question in the comments:
// The <form> tag should only be echoed once.
echo '<form name="some form" action="editform.php" method="post">';
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['stickerID']."</td>";
echo "<td>" .$row['stickerName']."</td>";
echo "<td>".$row['stickerSection']."</td>";
echo "<td>"?>
<input type="hidden" name="status_<?php echo $row['stickerID"; ?>" value="0">
<input type="checkbox" name="status_<?php echo $row['stickerID'] ?>" value="<?php echo $row['stickerStatus'] ?> ">
<?php "</td>";
echo "</tr>";
}
// You need a submit button to send the form
echo '<input type="submit">';
// Close the <form> tag
echo '</form>';
Using a hidden input with the same name as the checkbox makes sure a value for the given input name is sent to the server. The value of a checkbox that's not checked will not be sent. In that case the hidden input will be used.
You can get the submitted values in editform.php as follows:
<?php
foreach ($_POST as $field => $value) {
if (strpos($field, 'status_')) {
// Using (int) makes sure it's cast to an integer, preventing SQL injections
$stickerID = (int) str_replace('status_', '', $field);
// Again, preventing SQL injections. If the status could be a string, then use mysql_real_escape_string()
$stickerStatus = (int) $value;
// Do something with the results
}
}
Do
print_r($row)
to find out exactly how your row arrays are constructed and work from there.
For your comparison operator, use
$row[3] === 0
instead of
$row[3] == 0
This will return true if both the value and data type match rather than just the value.
0 can mean the Boolean false aswell as the numeric value 0

php script was working, now second $_POST suddenly not working

I am fairly new to php and have been searching for three days to find my problem. The script below worked for two years, and now suddenly the second POST command never populates (it is the last lines of code, and when I echo $_POST['input']; nothing is ever there.) I have looked at var_dump$[_$POST] and it gets $formType, but never $input.
Why would this suddenly stop working? It goes to the next form, but nothing works because it all counts on $input being passed on.
I am running on a unix server, Network Solutions.
Any help is greatly appreciated!!
here is the code (sanitized names of directories and databases, obviously):
<?php
session_start();
if ($_SESSION['auth'] != "yes") {
header("Location: login.php");
exit();
}
if (isset($_REQUEST['Enter'])) {
header("Location: http://www.mysite.com/subdirectory/nextform.php");
} else if (isset($_REQUEST['Delete'])) {
header("Location: http://www.mysite.com/subdirectory/deleterow.php");
}
########################################
####checks what kind of service request######
#########################################
?>
<form name="form" method="post" action="<?php
echo htmlentities($_SERVER['PHP_SELF']);
?>">
<p><legend>Form Type</legend></p>
<p> <basefont size = "4"></p>
<p><label for="formType" required>*Select Type of Form:</label></p>
<p><select name="formType"></p>
<p><option value="">select</option></p>
<p><option value="Garda">Security Officer</option></p>
<p><option value="Surveil">Surveil</option></p>
<p><option value="EmployApp">Employment Application</option></p>
<p></select></p>
<p><input type="submit" name="Submit" value="Submit" /></p>
</form>
<?php
$formType = $_POST['formType'];
SESSION_register("formType");
if ($formType == Garda) {
// Connects to your Database
include("introGardaform.php");
$database = "Gardaform"; // provide your database name
$db_table = "GardaINQ"; // leave this as is
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database, $db);
$data = mysql_query("SELECT * FROM GardaINQ") or die(mysql_error());
// puts the "GardaINQ"database table info into the $info array
//$info = mysql_fetch_array( $data );
Print "<table border cellpadding=15>";
while ($info = mysql_fetch_array($data)) {
Print "<tr>";
Print "<th>Inquiry Number:</th> <td>" . $info['Inquiry_num'] . "</td> ";
Print "<th>Contact Name:</th> <td>" . $info['contactName'] . " </td>";
Print "<th>Contact Number:</th> <td>" . $info['contactNum'] . " </td></tr>";
}
Print "</table>";
}
if ($formType == Surveil) {
// Connects to your Database
include("investfm.php");
$database = "investigateform"; // provide your database name
$db_table = "surveil"; // leave this as is
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database, $db);
$data = mysql_query("SELECT * FROM surveil") or die(mysql_error());
// puts the "surveil"database table info into the $info array
//$info = mysql_fetch_array( $data );
Print "<table border cellpadding=15>";
while ($info = mysql_fetch_array($data)) {
Print "<tr>";
Print "<th>Inquiry Number:</th> <td>" . $info['Inquiry_num'] . "</td> ";
Print "<th>Contact Name:</th> <td>" . $info['contactName'] . " </td>";
Print "<th>Contact Number:</th> <td>" . $info['contactNum'] . " </td></tr>";
}
Print "</table>";
}
if ($formType == EmployApp) {
// Connects to your Database
include("introhires.php");
$database = "hires"; // provide your database name
$db_table = "hiresentry"; // leave this as is
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database, $db);
$data = mysql_query("SELECT * FROM hiresentry") or die(mysql_error());
// puts the "hiresentry"database table info into the $info array
//$info = mysql_fetch_array( $data );
Print "<table border cellpadding=15>";
while ($info = mysql_fetch_array($data)) {
Print "<tr>";
Print "<th>First Name:</th> <td>" . $info['firstName'] . " </td>";
Print "<th>Last Name:</th> <td>" . $info['lastName'] . " </td>";
Print "<th>Date:</th> <td>" . $info['date'] . " </td></tr>";
}
Print "</table>";
}
?>
<form name="finddata" method="POST" action="<?php
echo htmlentities($_SERVER['PHP_SELF']);
?>">
<p> <basefont size = "4"></p>
<p><label for="finddata" required>Enter Inquiry Number for Garda or Surveil, Last name for Employment
Application:</label></p>
<p><input type = "text" size="20" maxlength="40" required onKeyPress="return noenter()"
name="input"></p>
<p><input type="hidden" value="<?php
echo $formType;
?>" name="formType"></p>
<p><input type="submit" name="Enter" value="Enter" ></p><br/>
<p><input type="submit" style="font-face: 'Comic Sans MS'; font-size: larger; color: red; background-color: #FFFFC0; border: 3pt ridge lightgrey" name = "Delete" value="Delete"></p>
</form>
<?php
$input = $_POST['input'];
SESSION_register("input");
echo $_POST['input'];
?>
You have used SESSION_register("formType"); undefined function and This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
So you can use $_SESSION["formType"]=$formType;, also
Need to wrap " or ' to check the string. Try this,
if($formType=="Garda"){
and if($formType=="EmployApp"){
instead of
if($formType==Garda){
if($formType==EmployApp){
You have a lot of issues on your code.
You are comparing your $formtype variable to a constant instead. It has to be like this. if($formType=="Garda"){ and if($formType=="Surveil"){ and if($formType=="EmployApp"){ add the double quotes to all those if statements as shown.
You are using a deprecated version i.e. session_register
can you try the following:
Remove the action attribute completely from both the forms as by default it is POST to self.
replace the font-face css property to font-family property in the last element of the second form. however that should not be the cause of the issue you are facing.
As there are 2 forms in the page and there are 2 code blocks depending on the form post, I assume that your second form post creates the issue in the first part of the code as the data for the first from will not be posted from the submit button in the second form. so before executing the piece of code you should identify if that piece of code should be executed or not. A simple multi form setup should look something like this:
<form name="form1" method="post">
<input type="text"/>
<input type="submit" name="form1-submit" value="Submit Name" />
</form>
<!-- form1 specific code -->
<?php
if(isset($_POST["form1-submit"]))
{
// do your stuff here
}
?>
<form name="form2" method="post">
<input type="text"/>
<input type="submit" name="form2-submit" value="Submit Name" />
</form>
<!-- form2 specific code -->
<?php
if(isset($_POST["form2-submit"]))
{
// do your stuff here
}
?>
<!-- independent code -->
<?php
// do your common code here.
?>
If you can write the code in above manner you will be able to resolve your problem yourself. please let us know in case above helped.

View/Edit/Delete in PHP

I got a system where users have to register and login to my website to add recipes in which the non-registered users and obviously registered users can view from the front end.
What I have done so far is, I have done the registration page, login page, and an 'my account' page for users to login and submit recipes. Everything works but now I am trying to add another functionality in my system whereby users can edit/delete their own recipes. The way I've done the login is by creating a session which holds the username rather then outputting it in the url like so: www.cooking.com/my-account.php?user_id=26.
I want the same sort of thing but this time I want the recipes to be stored in a session rather then the recipe id being shown on the url. I am clueless in how to do this. I have a 'starters' table in mysql with the following fields:
username ()
recipename
ingredients
method
time
id
Once you login and want to edit/delete the recipes you have uploaded, there is a table shown which contains all the recipes you uploaded. What i want is for the user to click on any recipe and it shall take the user to another page where it allows the user to edit their stuff.
I have tried this but with no success. The following are the codes I have used with the error displaying once clicked on edit:
EDIT STARTERS PAGE (editstarters.php)
<?php
session_start();
require_once '../database.php';
if (isset($_SESSION['myusername'])){
echo "Welcome ". $_SESSION['myusername'];
}
?>
<br /><br />You have uploaded the following starters:
<br /><BR />
<?php
include '../database.php';
$userid = $_SESSION["myusername"];
$result = mysql_query("SELECT * FROM starters WHERE username = '". $_SESSION['myusername']."' ");
echo "<table border='1'><table border width=65%><tr><th>Recipie Name</th><th>Ingredients</th><th>Method</th><th>Time</th></tr>";
while($getrecipie = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $recipiename = $getrecipie['recipename']. "</td>";
echo "<td>" . $ingredients = $getrecipie['ingredients']. "</td>";
echo "<td>" . $method = $getrecipie['method']. "</td>";
echo "<td>" . $time = $getrecipie['time']. 'minutes'."</td>";
?>
<td><a href = "startersedited.php?rec=<?php echo $getrecipie['id'] ?>" >Edit</a></td>
<td><a href = "DELETE1.php?rec=<?php echo $getrecipie['Recipie_ID'] ?>&id=<?php echo $user_id?>" >Delete</a></td>
<!--using the stu_id value in the URL to select the correct data when wego to the relevant pages -->
<?php
}
echo "</tr>";
echo "</table>";
?>
STARTERS EDITED PAGE (startersedited.php)
<?php
session_start();
require_once '../database.php';
if (isset($_SESSION['myusername'])){
echo "Welcome ". $_SESSION['myusername'];
}
?>
<br /><br />EDIT/DELETE YOUR STARTERS
<br /><BR />
<?php
include '../database.php';
$userid = $_SESSION["myusername"];
$result = mysql_query("SELECT * FROM starters WHERE username = '". $_SESSION['myusername']."' AND recipie_id='{$_GET['rec']}'");
$getrecipie = mysql_fetch_array($result);
$recipie = $getrecipie['recipename'];
$ingredients = $getrecipie['ingredients'];
$method = $getrecipie['method'];
$time = $getrecipie['time'];
?>
<h1>Edit Recipies</h1>
<p> </p>
<form name="form1" method="post" action="startereditsuccess.php?rec=<?php echo $_GET['id']?>">
<table width="609" height="250" border="0">
<tr>
<td width="155">Recipie Name</td>
<td width="347"><label for="recipiename"></label> <input type="text" name="recipename" value="<? echo $recipe ?>" id="recipename" >
</td>
</tr>
<tr>
<td>Ingredients</td>
<td><label for="ingredients"></label> <textarea name="ingredients" cols="50" rows="5" id="ingredients"><? echo $ingredients ?></textarea></td>
</tr>
<tr>
<td>Method</td>
<td><label for="method"></label> <textarea name="method" cols="50" rows="5" id="method"><? echo $method ?></textarea></td>
</tr>
<tr>
<td>Time</td>
<td><label for="time"></label> <input type="text" name="time" value="<? echo $time ?>" id="time"></td>
</tr>
</table>
<p>
<input type="submit" name="update" id="update" value="Update">
</p>
</form>
This is the error I get:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/jahedhus/public_html/cook/editdelete/startersedited.php on line 55
Please help me, I am LOST!
First off, don't shout in your posting titles. It's not necessary.
Second, we don't need a wall of code showing everything, when the actual only relevant bit is your error message. That particular error message means that your query has failed (probably due to a syntax error), which means mysql_query() has returned its usual boolean FALSE, and you didn't check for that. You used this false as a statement handle and tried to fetch a row from it, which has caused the actual error message.
As a general rule, NEVER assume that a database query succeeds. Even if the query string itself is 100% syntactically valid, there's many many other reasons that can cause it to fail.
Your basic MySQL query code structure should be:
$sql = "...";
$result = mysql_query($sql) or die(mysql_error());
This is good for debugging/development: if a query fails, it'll halt the script immediately and tell you why. For production code, you'd want something a bit more robust, rather than sending a long SQL error message to your users.
Your call to mysql_query() in startersedited.php at this line:
$result = mysql_query("SELECT * FROM starters WHERE username = '". $_SESSION['myusername']."' AND recipie_id='{$_GET['rec']}'");
is returning boolean FALSE, because an error has occurred. You should add some error handling code to deal with this whenever you call mysql_query(), for example:
$result = mysql_query("SELECT * FROM starters WHERE username = '". $_SESSION['myusername']."' AND recipie_id='{$_GET['rec']}'");
if($result === FALSE) {
echo "Database Error: ".mysql_error() ;
exit ;
}
$getrecipie = mysql_fetch_array($result);
The above is probably more useful for development error checking, in a production site you would probably want to capture the error and display something more graceful.
Also, I noticed you are calling require_once '../database.php'; and include '../database.php';. You don't need both, just the first will do.

Categories