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.
Related
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
I managed to create a search bar that searches my forum,it searches the categories table then displays the results,however i want to make a link that redirects me to that result found ,for example i search for a category called business and it displays the result but i want the result to have a link such that when i click it it redirects me to that category
but i am getting an error
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';' in C:\xampp\htdocs\mysite\captcha2\tut.php on line 43
my code on line 43 is
<td>'.$category_title.="<a href='view_category.php?cid=".$id."' class='cat_links'>".$title." - <font size='-1'>".$description."</font></a>"'</td>
</tr>'
and this is my search bar code
if(isset($_POST['search'])){ //form submitted, clicked Submit Search
$query = strip_tags(mysql_real_escape_string($_POST['query'])); //try to prevent sql injections
if(!$query){ //not enterered a query
echo 'You must enter a search query!';
}else{
$table = 'categories'; //the table you want to search
$row = 'category_title'; //the row in which you want to search
$sql = mysql_query("SELECT * FROM `".$table."` WHERE `".$row."` LIKE '%".$query."%'"); //search query
if($sql){ //no errors
if(mysql_num_rows($sql) == 0){ //No results found.
echo 'No results were found for <strong>'.$query.'</strong>';
}else{ //one or more results have been found
echo 'We have found <strong>'.mysql_num_rows($sql).'</strong> for <strong>'.$query.'</strong>.<br><br>
<table>
<tbody>
<tr>
<td><strong>category_title</strong></td>
</tr>';
while($r = mysql_fetch_array($sql)){ //get data of every user where their category_title is like the $query string
$category_title = $r["category_title"];
//lets put the part they searched in bold.
$category_title = str_ireplace($query, '<strong>'.$query.'</strong>', $category_title);
//lets put the part they searched in bold.
echo '<tr>
<td>'.$category_title.="<a href='view_category.php?cid=".$id."' class='cat_links'>".$title." - <font size='-1'>".$description."</font></a>"'</td>
</tr>';
}
echo '</tbody></table>';
}
}else{
echo 'Sorry, an MySQL error occurred:<br><br>'.mysql_error(); //an error occurred, so echo it
}
}
}else{ //not clicked Submit Search, so echo the form
echo '<h3>Search</h3>
<br><br>
<form method="post">
<label for="q"></label> <input type="text" size="100" name="query" id="q" value="m0nsta.">
<input type="submit" name="search" value="Search">
</form>';
}
?>
Get rid of the = sign, and an extra quotation
<td>'.$category_title.="<a href='view_category.php?cid=".$id."' class='cat_links'>".$title." - <font size='-1'>".$description."</font></a>"'</td>
</tr>'
Should be
<td>'.$category_title."<a href='view_category.php?cid=".$id."' class='cat_links'>".$title." - <font size='-1'>".$description."</font></a></td>
</tr>"
."</font></a>"'</td>
</tr>';
This should end with a double quotation mark and not single like
echo '<tr> <td>'.$category_title."<a href='view_category.php?cid=".$id."' class='cat_links'>".$title." - <font size='-1'>".$description."</font></a></td></tr>";
USE
<td>'.$category_title."=<a href='view_category.php?cid=".$id."' class='cat_links'>".$title." - <font size='-1'>".$description."</font></a></td>
</tr>'";
Make use of eclipse IDE as a habit, it will really help you to avoid such errors
I am building an employee directory that has 3 simple forms. The first adds records, the second searches for records, the third searches then deletes records.I want to display all the records on the same page, and then when a search is done, just display those records that fit the search keyword.
I have built the DB and the Table correctly. The first form adds records to the DB successfully. Before I make the search and delete forms work correctly I am trying to get the records to display. They are not displaying. Sometimes I can get my html table to display, but none of the records appear. However, I know that the records exist because I can see them in MyAdmin.
I am getting this error right now, but my errors are changing by the moment as I try new things: Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in C:\xampp\htdocs\Employees.php on line 84
I would love some help to do the following:
1. Help me understand why I am getting this error.
2. Help me understand how to display my records (I've done this successfully before, but with a simpler task).
I know this code is unfinished. I am building it piece by piece and trying to get each individual piece to function before I add the next. Thanks!
<html>
<body>
<?php error_reporting (E_ALL ^ E_NOTICE);
$keyword = $_GET['keyword']; ?>
<?php
$con = mysql_connect("localhost", "employees", "employeepw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("employees", $con);
mysql_query("INSERT INTO employeeinfo (firstname, lastname, phone, email, department, position)
VALUES ('$_POST[firstname]', '$_POST[lastname]', '$_POST[phone]', '$_POST[email]', '$_POST[department]', '$_POST[position]')");
mysql_query($sql,$con);
function buildQuery() {
$keyword = $_GET['keyword'];
$sql = "SELECT * from employeeinfo WHERE
(
firstname LIKE '%$keyword%'
OR
lastname LIKE '%$keyword%'
OR
phone LIKE '%$keyword%'
OR
email LIKE '%$keyword%'
OR
department LIKE '%$keyword%'
OR
position LIKE '%$keyword%'
)";
return $sql;
} ?>
<form action="Employees.php" method="post">
<fieldset>
<legend>Submit Employee Info</legend>
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Phone: <input type="text" name="phone" />
Email: <input type="text" name="email" />
Department: <input type="text" name="department" />
Position: <input type="text" name="position" />
<input type=submit name=submit value=Submit />
</fieldset>
</form>
<form action="Employees.php" method=get>
<fieldset>
<legend>Search Employee Info</legend>
<label for="keyword">Enter Keyword</label>
<input id="keyword" name="keyword" value="<?php echo "$keyword"; ?>" />
<input type=submit name=submit value=Search />
</fieldset>
</form>
<form action="Employees.php" method=get>
<fieldset>
<legend>Delete Employee Info</legend>
<label for="keyword">Enter Keyword</label>
<input id="keyword" name="keyword" value="<?php echo "$keyword"; ?>" />
<input type=submit name=submit value=Delete />
</fieldset>
</form>
<?
function getRecords()
{
$sql = buildQuery();
$resource = mysql_query($sql);
}
while($row = mysql_fetch_array($resource)) { // The error is for this row
$results[] = $row;
}
return $results;
$records = getRecords(); {
foreach ($records as $record) {
}?>
<table>
<tbody>
<table border='1'>
<tr>
<td><?= $row['firstname']; ?></td>
<td><?= $row['lastname']; ?></td>
<td><?= $row['phone']; ?></td>
<td><?= $row['email']; ?></td>
<td><?= $row['department']; ?></td>
<td><?= $row['position']; ?></td>
<td>Return to Search</td>
</tr>
<? } ?>
</tbody>
</table>
</body>
</html>
You aren't getting any rows back. Try changing this
function getRecords()
{
$sql = buildQuery();
$resource = mysql_query($sql);
}
to
function getRecords()
{
$sql = buildQuery();
echo $sql;
exit();
$resource = mysql_query($sql);
}
this will output the SQL you are querying against the database. If it is not immediately apparent, copy and run this query against your database. See if any rows come back. If not then thats your problem!
Also you can use "echo mysql_error();" to get the text of the last error mysql threw.
EXAMPLE:
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
Your mysql query is not going through, or it is retuning 0 rows.
Try to put this
if(!$resource){
echo mysql_error();
echo ' <br>Query: .$sql;
}
statement directly after $resource = mysql_query($sql);
and see what it outputs. Also, make sure error reporting is turned on.
I edited my answer on your post yesterday, you might want to look at it; it may give you some ideas for a different approach.
The link is here:
Fatal error: Call to undefined function getRecords() in C:\xampp\htdocs\Employees.php on line 101
Maybe.. just maybe there is some problem with your code..
function getRecords()
{
$sql = buildQuery();
$resource = mysql_query($sql);
}
while($row = mysql_fetch_array($resource)) { // The error is for this row
$results[] = $row;
}
return $results;
my guess is that your above code should be something like this
function getRecords()
{
$sql = buildQuery();
$resource = mysql_query($sql);
$results = array();
if($resource != null)
{
while($row = mysql_fetch_array($resource))
{
$results[] = $row;
}
}
return $results;
}
Hope it helps :)
Please never do such thing:
mysql_query("INSERT INTO employeeinfo (firstname, lastname, phone, email, department, position) VALUES ('$_POST[firstname]', '$_POST[lastname]', '$_POST[phone]', '$_POST[email]', '$_POST[department]', '$_POST[position]')");
This will produce a HUGE hole in your site security called sql-injection.
You should always check any data gained from user.
The simple example of how it should be:
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$phone = mysql_real_escape_string($_POST['phone']);
$email = mysql_real_escape_string($_POST['email']);
$department = mysql_real_escape_string($_POST['department']);
$position = mysql_real_escape_string($_POST['position']);
mysql_query("INSERT INTO employeeinfo (firstname, lastname, phone, email, department, position)
VALUES ('{$firstname}', '{$lastname}', '{$phone}', '{$email}', '{$department}', '{$position}')");
For more info read: http://php.net/manual/en/mysqli.real-escape-string.php
I think you should find a good book for novices in PHP and read at least from time to time it.
It will help you understand what you writing and how to make it better.
The first book that i googled for this purpose - http://www.amazon.com/Learning-MySQL-JavaScript-Step-Step/dp/0596157134/
I have three files; index.php, searchbar.php and search.php
now when i have search.php show its results on its own page its fine but when i try to include the search page in index.php i get nothing.
so i include the searchbox.php in index.php so i have a search bar, i then search for something and include the search.php page by using the $_GET['p'] on the index.php but the search always come up blank, if i just leave search.php as its own page and dont try to include it then i get my results but id like for them to be included on the page they were searched from.
index.php
<?php
if (isset($_GET['p']) && $_GET['p'] != "") {
$p = $_GET['p'];
if (file_exists('include/'.$p.'.php')) {
#include ('include/'.$p.'.php');
} elseif (!file_exists('include/'.$p.'.php')) {
echo 'Page you are requesting doesn´t exist<br><br>';
}
} else {
#include ('news.php');
}
?>
searchbox.php
<div id="searchwrapper"><form action="?p=search" method="get">
<input type="text" class="searchbox" name="query" value="" id="query"/>
<input type="image" src="search.png" class="searchbox_submit" value="" ALT="Submit Form" id="submit"/>
</form>
</div>
search.php
<?php
include 'connect.php';
$searchTerms = $_GET['query'];
$query = mysql_query("SELECT * FROM misc WHERE itemname LIKE '%$searchTerms%' ORDER BY itemname ");
{
echo "<table border='1' cellpadding='2' cellspacing='0' width=608 id='misc' class='tablesorter'><thead>";
echo "<tr> <th> </th> <th>Item Name</th> <th>Desc.</th></tr></thead><tbody>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $query )) {
// Print out the contents of each row into a table
echo "<tr><td width=50>";
echo $row['image'];
echo "</td><td width=150>";
echo $row['itemname'];
echo "</td><td width=250>";
echo $row['desc'];
echo "</td></tr>";
}
echo "</tbody></table>";;
}
if (mysql_num_rows($query) == 0)
{
echo 'No Results';
}
?>
When I reproduced your code, the "p=search" wasn't carrying over. The better way to set it up is to have the action just go to your index.php file and have a hidden input with:
<input type="hidden" name="p" value="search" />
That will work properly for you!
A blank page almost always means you have whitespace after your closing ?>. Remove the closing ?> in index.php and search.php - this will force the preprocessor to dynamically determine EOF, which is exactly what you want (and what nearly every PHP framework/company includes within their coding standards).
UPDATE: I narrowed it down, when I got rid of this tag in the header.php file it all works, can someone please explain this.
<script src="#" type="text/javascript"></script>
Hi I'm having quite an annoying issue with my php code. I am trying to update a php database, from a form, when I do this however the fields in the data base become empty after submitting. Please Help! You can view it in action here http://andcreate.com/shoelace/admin/edit1.php click on the lists on the right to edit them and see what happens.
<?php
include("header.php");
echo "<h2>Edit Posts</h2>";
echo "<div id='editNav'>";
echo "<p>Choose Post to Edit</p>";
//////////GET ALL RECORDS AND BUILD A NAV SYSTEM FROM THEM////////
$results = mysql_query("SELECT * FROM shoeData ");
while($row = mysql_fetch_array($results)){
$id = $row['id'];
$name = $row['name'];
$about = $row['about'];
echo "$date " . substr($name, 0, 40) . " <br/> ";
}
$thisID = $_GET['id'];
if(!isset($thisID)){
$thisID = 22;
}
//////////FINISH ALL RECORDS AND BUILD A NAV SYSTEM FROM THEM////////
echo "</div>";
///////IF USER SUBMITS CHANGES UPDATE THE DATABASE//////////
//has user pressed the button
$update = $_GET['update'];
if($update == "yes") {
$name = $_POST['name'];
$about = $_POST['about'];
$company = $_POST['company'];
$buy = $_POST['buy'];
//update data for this record
$sql = "UPDATE shoeData SET
name = \"$name\",
about = \"$about\",
company = \"$company\",
buy = \"$buy\"
WHERE id= $thisID";
$thisUpdate = mysql_query($sql) or die(mysql_error());
}
///////END IF USER SUBMITS CHANGES UPDATE THE DATABASE//////////
/////////// HERE WE GET THE INFO FOR ONE RECORD ONLY////////
$results = mysql_query("SELECT * FROM shoeData WHERE id=$thisID");
while($row = mysql_fetch_array($results)){
$name = $row['name'];
$about = $row['about'];
$company = $row['company'];
$buy = $row['buy'];
}
//////////////FINISH GETTING INFO FOR ONE RECORD ONLY/////////////
?>
<form name="formS" method="post" action="<?php echo $_SERVER['PHP_SELF']."?id=$thisID&update=yes";?>">
Name
<p>
<input type="text" name="name" id="name" value="<?php echo $name;?>" />
</p>
About
<p>
<input type="text" name="about" id="about" value="<?php echo $about;?>" />
</p>
Company
<p>
<input type="text" name="company" id="company" value="<?php echo $company;?>" />
</p>
Name
<p>
<input type="text" name="buy" id="buy" value="<?php echo $buy;?>" />
</p>
<p>
<input type="submit" name="submit" id="submit" />
</p>
</form>
<p><a class="delete" href="delete.php?id=<?php echo $thisID;?>">Delete this post</a></p>
<?php
include("footer.php");
?>
You have $update = $_GET['update'];, but then right after that, you're using $_POST. A given request is either GET or POST, not both - thus whenever $_GET['update'] is set to "yes", there aren't going to be any POST vars set, and thus the update will be done with all of the values it's setting blank.
Chances are you actually meant to use either $_GET or $_POST in both places - since your updates are going through, but are blank, it sounds like you want to use $_GET (though for form submission/updates, you should probably really be using POST instead).
This may seem silly, but are you confusing $_GET and $_POST variables? You use one to check whether to enter the loop, and another to populate the string.
Also, as a minor aside, your SELECT statement towards the end of the snippet can be optimized by adding LIMIT 1 to the end of it, as presumably you're only going to be recalling one entry per id, no?