Jump to content

Drumlegend

Members
  • Posts

    26
  • Joined

  • Last visited

Posts posted by Drumlegend

  1.  

    I'm not quite sure whether you can able to use the same varialbe as the result of mysql_query() and then to fetched it, like that:

    $recipegallery = mysql_query("
            SELECT `id`,`name`, `image`, `description`
            FROM `recipe` 
    ORDER BY RAND () LIMIT 10;
        ");
    
    
    while ($recipegallery = mysql_fetch_assoc($recipegallery)) {
    

    I'm sorry, I didn't understand that but the problem was resolved :)

  2. So I am getting this error and I don't understand what I'm doing wrong.

     

    PHP Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in \\PDC3\sites\c\cupboard2stomach.com\public_html\index.php on line 102

     

     

    <?php
    
    
        $recipes = mysql_query("
            SELECT `id`,`name`, `image`, `description`
            FROM `recipe` 
    ORDER BY RAND() LIMIT 4;
        ");
    
    
    while ($recipe = mysql_fetch_assoc($recipes)) {
    echo '<section id="recipeslide">';
    
    
    
    
    echo "<a href='php/recipe.php?id=$recipe_id'><img src=\"{$recipe['image']}\" height=100 width=100 /></a><br />";
    echo '</section>';
    
    
        }
    
    
    echo '</section>';
    
    
    echo '<section id="indexcenter">';
    
    
    $recipegallery = mysql_query("
            SELECT `id`,`name`, `image`, `description`
            FROM `recipe` 
    ORDER BY RAND () LIMIT 10;
        ");
    
    
    while ($recipegallery = mysql_fetch_assoc($recipegallery)) {
    echo '<section id="recipegallery">';
    $recipe_id = $recipegallery['id']; 
    echo $recipegallery['name'];
    echo '<br />';
    echo "<a href='php/recipe.php?id=$recipe_id'><img src=\"{$recipegallery['image']}\" height=100 width=100 /></a><br />";
    
    
    echo '<section id="description">';
    echo $recipegallery['description'];
    echo '</section>';
    
    
    } 
    
    
    echo '</section>';
    echo '</section>';
    ?>

    I have two queries running;

     

    The first query pulls out 4 random recipes and displays them in a row at the top of the page.

     

    The second one is meant to pull 10 random ones out that are display in a main container on the home page but at the moment it's only displaying one recipe and displaying that error.

     

    Any thoughts?

     

  3. If you're going to use the anchor tag, you don't need the form tag anymore. If you want the link to look like a button, you can create one as an image...or use CSS to style the text.

     

    As for the ID, have you made sure that $recipe['id'] contains a value? You can use var_dump to find out:

    http://php.net/manual/en/function.var-dump.php

     

    Note that your original code used a different variable ($recipe_id).

    I will take this into account once I've stopped pulling my hair out :P I think I need to do some more reading before I go any further, otherwise I will be stuck on this part for ages. Thank you :)

  4. If you use Barand's suggestion, you'll need to use $_POST in your query instead of $_GET.

     

    Note that you probably don't need a form for the Look buttons. You could get away with using a simple link and an image for the buttons.

     

     

    Also, you'll want to make sure the ID is valid before running the query. Assuming the ID is a number, you could run it through the ctype_digit() function:

    http://php.net/manual/en/function.ctype-digit.php

    So I have changed the form to this.

     

    echo '<form action="recipe.php" method="POST">';
    echo "<a href='recipe.php?id=" . $recipe['id'] . "'>" . $recipe['name'] . "</a>";
    echo '</form>';

    There is no longer a button, but when clicking on the link I get this at the top of the url.

     

    recipe.php?id=

     

    It doesn't seem to be retrieving the ID

  5. I've been working on a project for the past few weeks and it's been a huge learning curve so I apologise in advance. 

     

    The idea is to choose ingredients and you will retrieve recipes that contain them. Once the results show up the user can click to view in more detail. The user will then be taken to a page which will show the recipe name, image, ingredients and steps of that recipe. That is where I am currently stuck at.

     

    r_YUIA.png

    These are the results from a search, when you click look you will be directed to this page.

     

    CF4_Sk.png

     

    I don't know if this is right but this is the what I used for the form action.

    echo '<form action="recipe.php?id=<?php echo $recipe_id;?>" method="POST">';
    echo '<input id="search" name="Look" type="Submit" value="Look" >';
    echo '</form>';

    On the recipe page I have this php code at the top

    <?php
    mysql_connect("10.168.1.56", "cupboard_test", "***") or die("Connection Failed");
    mysql_select_db("cupboard_test")or die("Connection Failed");
    
    
    $result = mysql_query("SELECT `name` 
    FROM `recipe` 
    WHERE `id` = ".$_GET['id']." LIMIT 1");
    
    
    ?>

    And I am trying to echo the name further down the page.

    <?php 
    echo $result['name'].'<br />'; 
    ?>

    I know I have probably made quite a few mistakes here and I do apologise but it's all part of the learning experience.

     

     

  6. Thanks for everyone's help but the million dollar question is how to pull a recipe image that is associated with that recipe.

     

    If you check out the site you will understand what I mean. http://www.cupboard2stomach.com/php/get.php

     

    This is the php code I have used.

     

     

    $ingredients = array(); //We use an array here to store data as we'll be using the ingredients query data twice, and we can't loop through with mysql_fetch_row twice on the same query
    
    
    $query = mysql_query("SELECT * FROM `ingredients`");
    while ($row = mysql_fetch_assoc($query)) {
        $ingredients[$row['id']] = $row['name']; //now we have all ingredients in an array with the array keys as the ingredient ids and the array values as the names
    }
    
    
    
    
    ?>
    <form action="<?php echo($_SERVER['PHP_SELF']); ?>" method="POST">
    <h3> Search your recipe here </h3>
    <fieldset>
    Ingredient 1:<select name="dropdown1" id = "drop1">
        <?php foreach($ingredients as $id => $name) { ?>
            <option value="<?php echo $id; ?>"><?php echo $name;?> </option>
        <?php } ?>
    </select>
    Ingredient 2:<select name="dropdown2" id = "drop2">
        <?php foreach($ingredients as $id => $name) { ?>
            <option value="<?php echo $id; ?>"><?php echo $name;?> </option>
        <?php } ?>
        </select>
    Ingredient 3:<select name="dropdown3" id = "drop3">
        <?php foreach($ingredients as $id => $name) { ?>
            <option value="<?php echo $id; ?>"><?php echo $name;?> </option>
        <?php } ?>
        </select>
        <input id="search" name="search" type="Submit" value="Search" >
    </fieldset>
    </form>

     

     

     

    <?php
    if (isset($_POST['search'])) {
        $ingredient1 = mysql_real_escape_String ($_POST['dropdown1']);
        $ingredient2 = mysql_real_escape_String ($_POST['dropdown2']);
    $ingredient3 = mysql_real_escape_String ($_POST['dropdown3']);
    
    
        $recipes = mysql_query("
            SELECT DISTINCT `name`, `step1`, `step2`, `step3`, `image`
            FROM `recipe` r
            INNER JOIN `recipe_ingredients` ri
            ON r.id = ri.recipe_id
            WHERE ri.ingredient_id IN (".$ingredient1.",".$ingredient2.",".$ingredient3.")
        ");
    echo '<section id="results">';
        while ($recipe = mysql_fetch_assoc($recipes)) {
    
    
    echo 'Recipe Name: ';
    echo $recipe['name'].'<br />'; 
    echo '<input id="search" name="Look" type="Submit" value="Search" >';
    echo '<br />';
    echo 'Step 1: ';
    echo $recipe['step1'].'<br />';
    echo '<br />';
    echo 'Step 2: ';
    echo $recipe['step2'].'<br />';
    echo '<br />';
    echo 'Step 3: ';
    echo $recipe['step3'].'<br />';
    echo '<br />';
    echo $recipe['image'].'<br />';
    echo '<br />';
    
    
    
    
    
    
    
    
        }
    }
    echo '</section>';
    ?>
  7. Basically, I have an image that is associated with a recipe. I have created a field in the recipe table called image which is set as VARCHAR and I don't know what I type in there. I don't know whether I need to put the url there and then I need to know how to retrieve that image and display it on my website. I can't find any tutorials explaining how. I'm sorry if you don't understand the question but I don't think I can explain it any clearer. 

  8. I have a folder in my ftp called recipeimages and it contains all images for different recipes.

     

    In my database I have a recipe table and an image path but I think I may have done it wrong and I was wondering how I would display that image to my webpage.

    <?php $path = "#"; ?> <img  src=<?php echo $src; ?> />

    I don't know whether or not this is the correct code I would use. The ideal way would be to display an image assigned to a certain recipe.

     

    recipe.png

    This is the recipe table, this is probably wrong but you get the idea of what I want to accomplish.

     

    image.png

    This is the table and the fields used. I have the imagepath set as varchar as I don't want to directly store the images in the database.

     

    I have never done anything like this before so I would love a bit of help.

     

    Thank you in advance.

     

     

     

  9. Currently I am able to pull the recipe name from the recipe table but I want to be able to grab the ingredients required from the ingredients table. I know it's to do with JOINS but I'm new to JOINS.

     

    This is the ingredients table

    ingredients.png

     

     

    This is the recipeingredients table, this has two primary keys so I am able to assign multiple ingredients to one recipe

     

     

    recipeingredients.png

     

    This is the recipe table

     

    recipes.png


     

     

     

     

    This is the search script

    <?php
    $query = $_GET['query'];
    // gets value sent over search form
    
    $min_length = 3;
    
    
    if(strlen($query) >= $min_length){
    
    $query = htmlspecialchars($query);
    
    
    $query = mysql_real_escape_string($query);
    // makes sure nobody uses SQL injection
    
    $raw_results = mysql_query("SELECT * FROM recipes
    WHERE (`recipename` LIKE '%".$query."%') OR (`ingredients` LIKE '%".$query."%')") or die(mysql_error());
    
    
    
    
    
    if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
    
    while($results = mysql_fetch_array($raw_results)){
    // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
    
    echo "<p>Recipe:".$results['recipename']."</p><p>Ingredients:".$results['ingredients']."<p>Instructions:".$results['instructions']."</p>";
    // posts results gotten from database(title and text) you can also show id ($results['id'])
    }
    
    }
    else{ // if there is no matching rows do following
    echo "No results";
    }
    
    }
    else{ // if query length is less than minimum
    echo "Minimum length is ".$min_length;
    }
    ?>

    This is the sample data from the ingredients table

    ingredientssample.png

     

    This is the sample data from the recipeingredients table

     

    recipeingredientssample.png

    This is sample date from the recipe table

     

    recipesample.png

     

     

     

     

  10. // Again, never trust user input!
    $user = $sql->real_escape_string($_POST['username']);
    
    $query = "SELECT id, password, username, UNIX_TIMESTAMP(created) AS salt
                            FROM users
                            WHERE username = '{$username}'";

    Variable mismatch.

     

    So what do I need to change, I am confused.

  11. I have been working on an application for a university project and I have somehow managed to break my code and I have no idea what I have done to break it.

     

    I have created a registration and log in script which used to work but I can no longer login with the registered details. I could really use some help on this so I don't spend hours ripping my hair out.

     

    I have attached an image of my user database. post-128086-0-36163400-1360617049_thumb.png

     

    Code for registration

     

     

    <?php
    include 'PasswordHash.php';
    $sql = new mysqli('localhost', '****', '****', '****');
    
    // Create an array to catch any errors in the registration form.
    $errors = array();
    
    /**
    * Make sure the form has been submitted before trying to process it. This is
    * single most common cause of 'undefined index' notices.
    */
    if (!empty($_POST))
    {
    // First check that required fields have been filled in.
    if (empty($_POST['username']))
    {
     $errors['username'] = "Username cannot be empty.";
    }
    
    
    // Restrict usernames to alphanumeric plus space, dot, dash, and underscore.
    /*
    if (preg_match('/[^a-zA-Z0-9 .-_]/', $_POST['username']))
    {
     $errors['username'] = "Username contains illegal characters.";
    }
    */
    if (empty($_POST['firstname']))
    {
     $errors['firstname'] = "First Name cannot be empty.";
    }
    
    if (empty($_POST['surname']))
    {
     $errors['surname'] = "Surname cannot be empty.";
    }
    
    if (empty($_POST['password']))
    {
     $errors['password'] = "Password cannot be empty.";
    }
    
    
    if (strlen($_POST['password']) < 
    {
     $errors['password'] = "Password must be at least 8 charcaters.";
    }
    
    
    // Force passwords to contain at least one number and one special character.
    /*
    if (!preg_match('/[0-9]/', $_POST['password']))
    {
     $errors['password'] = "Password must contain at least one number.";
    }
    if (!preg_match('/[\W]/', $_POST['password']))
    {
     $errors['password'] = "Password must contain at least one special character.";
    }
    */
    
    if (empty($_POST['password_confirm']))
    {
     $errors['password_confirm'] = "Please confirm password.";
    }
    
    if ($_POST['password'] != $_POST['password_confirm'])
    {
     $errors['password'] = "Passwords do not match.";
    }
    
    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
    if (!$email)
    {
     $errors['email'] = "Not a valid email address.";
    }
    
    /**
     * Escape the data we're going to use in our query. Never trust user input.
     */
    $username = $sql->real_escape_string($_POST['username']);
    $email = $sql->real_escape_string($email);
    $firstname = $sql->real_escape_string($_POST['firstname']);
    $surname = $sql->real_escape_string($_POST['surname']);
    $addressline1 = $sql->real_escape_string($_POST['addressline1']);
    $addressline2 = $sql->real_escape_string($_POST['addressline2']);
    $city = $sql->real_escape_string($_POST['city']);
    $county = $sql->real_escape_string($_POST['county']);
    $postcode = $sql->real_escape_string($_POST['postcode']);
    
    /**
     * Check that the username and email aren't already in our database.
     *
     * Note also the absence of SELECT *
    
     */
    $query = "SELECT username, email
    		 FROM users
    		 WHERE username = '{$username}' OR email = '{$email}'";
    $result = $sql->query($query);
    
    /**
     * There may well be more than one point of failure, but all we really need
     * is the first one.
     */
    $existing = $result->fetch_object();
    
    if ($existing)
    {
     if ($existing->username == $_POST['username'])
     {
    	 $errors['username'] = "That username is already in use.";
     }
     if ($existing->email == $email)
     {
    	 $errors['email'] = "That email address is already in use.";
     }
    }
    }
    
    
    
    if (!empty($_POST) && empty($errors))
    {
    /**
     * Hash password before storing in database
     */
    $hasher = new PasswordHash(8, FALSE);
    $password = $hasher->HashPassword($_POST['password']);
    
    $query = "INSERT INTO users (firstname, surname, username, email, password, addressline1, addressline2, city, county, postcode, created)
    		 VALUES ('{$firstname}','{$surname}','{$username}','{$email}',
    '{$password}','{$addressline1}','{$addressline2}','{$city}','{$county}','{$postcode}', NOW())";
    $success = $sql->query($query);
    
    if ($success)
    {
     $message = "Account created.";
    }
    else
    {
     $errors['registration'] = "Account could not be created. Please try again later.";
    }
    }
    ?>

     

    Login Code

     

    <?php
    session_start();
    
    
    
    // If the user is already logged in then redirect them to homepage
    if (isset($_SESSION['user_id']))
    {
    
    exit();
    
    }
    
    include 'PasswordHash.php';
    
    $sql = new mysqli('localhost', '****', '****', '****');
    
    $hasher = new PasswordHash(8, FALSE);
    
    if (!empty($_POST))
    {
    // Again, never trust user input!
    $user = $sql->real_escape_string($_POST['username']);
    
    $query = "SELECT id, password, username, UNIX_TIMESTAMP(created) AS salt
    		 FROM users
    		 WHERE username = '{$username}'";
    $user = $sql->query($query)->fetch_object();
    
    /**
     * Check that the query returned a result (otherwise user doesn't exist)
     * and that provided password is correct.
     */
    if ($user && $user->password == $hasher->CheckPassword($_POST['password'], $user->password))
    {
     /**
    	 * Set cookies here if/as needed.
    	 * Set session data as needed. DO NOT store user's password in
    	 * cookies or sessions!
    	 * Redirect the user if/as required.
    	 */
     session_regenerate_id();
     $_SESSION['user_id']	 = $user->id;
    $_SESSION['username']	 = $user->username;
     $_SESSION['authenticated'] = TRUE;
     $_SESSION['signature']	 = md5($user->id . $_SERVER['HTTP_USER_AGENT'] . $user->salt);
    header('Location:../login.php');
    
    }
    /**
     * Don't provide specific details as to whether username or password was
     * incorrect. If an attacker knows they've found a valid username, you've
     * just made their life easier.
     */
    else
    {
     $error = "Login failed.";
    }
    }
    
    ?>

     

    Thank you in advance and I'm sorry for the amount of code.

     

     

    Some of the code I used was from tutorials, as I am new to php.

  12. That is the upload script, so I have managed to upload the photo to the server but I want to retrieve it.

     

    This code might make more sense.

     

    <!DOCTYPE html>
    <html>
       <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
           <head><link rel="stylesheet" type="text/css" href="../style/user.css"></head>
        <title>Users</title>
       </head>
    <?php
    include('common.php');
    
       $sqlget ="SELECT * FROM recipes";
    
       $sqldata= mysqli_query($dbcon, $sqlget) or die('error getting data');
    ?>
    
       <body>
       <section id="mainContainer">
          <h1>test</h1>
               <section id="photo">
               <h1>test</h1>
               <a href="#">Edit Photo</a>
               </section>
               <section id="ad1">
               <h1>test</h1>
               </section>
               <section id="leftContainer">
               <h1>Saved Recipe</h1>
               <input type="Submit" Value="View more recipes"/>
               </section>
               <section id="ad2">
               <h1>test</h1>
               </section>
               <section id="middleContainer">
                   <?php
    
       echo "<table>";
       echo "<tr><th>ID</th><th>Recipe Name</th><th>Ingredients</th><th>Instructions</th></tr>";
    
       while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)) {    
           echo "<tr><td>";
           echo $row['recipeid'];
           echo "</td><td>";
           echo $row['recipename'];
           echo "</td><td>";
           echo $row['ingredients'];
           echo "</td><td>";
           echo $row['instructions'];
           echo "</td></tr>";
           }
           echo "</table>";
       ?>
               <h1>About Me</h1>
               </section>
    
    
          </section>
       </body>
    </html>

     

    I basically want each recipe to display an image

  13. I am still really new to php so I am sorry if I don't make much sense but what I want to be able to achieve is to retrieve images from a file directory that will be referenced in the database.

     

    Here is my code for submitting the images

     

    <?php
    $allowedExts = array("jpg", "jpeg", "gif", "png");
    $extension = end(explode(".", $_FILES["file"]["name"]));
    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/png")
    || ($_FILES["file"]["type"] == "image/pjpeg"))
    && ($_FILES["file"]["size"] < 20000)
    && in_array($extension, $allowedExts))
     {
     if ($_FILES["file"]["error"] > 0)
       {
       echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
       }
     else
       {
       echo "Upload: " . $_FILES["file"]["name"] . "<br>";
       echo "Type: " . $_FILES["file"]["type"] . "<br>";
       echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
       echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
    
       if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
       else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
       }
     }
    else
     {
     echo "Invalid file";
     }
    ?>

     

    Here is my sql for the created table

     

    CREATE TABLE `recipes` (
       `recipeid` INT(11) UNSIGNED ZEROFILL PRIMARY KEY AUTO_INCREMENT,
       `recipename` VARCHAR(50) NOT NULL,
       `ingredients` VARCHAR(50) NOT NULL,
       `instructions` VARCHAR(50) NOT NULL,
       `imagename` VARCHAR(50) NOT NULL,
    
    
       `created` DATETIME NOT NULL
    )

     

    Thank you in advance.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.