Jump to content
Larry Ullman's Book Forums

margaux

Members
  • Posts

    453
  • Joined

  • Last visited

  • Days Won

    52

Posts posted by margaux

  1. @giantsfan24 - good point, there is actually no need to create the first instance of $image, can't remember what I was thinking when I created it.

     

    In my previous post, the amended code didn't show up so here it is,

    if ($image = @getimagesize ("../uploads/$pid")) {
      echo "<td align=\"center\"><img src=\"showPrint.php?image=$pid&name=" . urlencode($row['imagename']) . "height=\"200\" width=\"200\" alt=\"{$row['printname']}\" />
      </td>\n";
    

     

    nothing new logically, just a height and width on the image tag to help with the display. Probably not the best way performance wise as I think all this re-sizing could slow down the page load.

    • Upvote 1
  2. ok I think I get what you are trying to do, sorry for not getting it the first time. You'll need to do some formatting/image re-sizing to get a nice display but here's what worked for me.

    <?php
    $page_title = 'Display the Prints';
    include ('includes/header.html');
    require ('includes/mysqli_connect.php');
    
    $q= "SELECT artists.artist_id, CONCAT_WS(' ', firstname, middlename, lastname) AS artist, printname, price, description, print_id, imagename
    FROM artists, prints WHERE artists.artist_id = prints.artist_id ORDER BY artists.lastname ASC, prints.printname ASC";
    
    if (isset($_GET['aid']) && filter_var($_GET['aid'], FILTER_VALIDATE_INT, array('min_range' => 1)) ) {
       $q = "SELECT artists.artist_id, CONCAT_WS(' ', firstname, middlename, lastname) AS artist, printname, price, description, print_id, imagename
       FROM artists, prints WHERE artists.artist_id = prints.artist_id  AND prints.artist_id={$_GET['aid']} ORDER BY prints.printname";
       }
    echo '<table border="0" cellspacing="3" cellpadding="3" align="center">
    <tr>
    <td align="left" width="15%"><b>Artist</b></td>
    <td align="left" width="25%"><b>Thumbnail</b></td>
    <td align="left" width="15%"><b>Print Name</b></td>
    <td align="left" width="20%"><b>Description</b></td>
    <td align="right" width="5%"><b>Price</b></td>
    </tr>';
    $r = mysqli_query($dbc, $q)  or trigger_error("Query: $q\n <br />MySQL Error: " . mysqli_error($dbc));
    
    while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
    $image = $row['imagename'];
    $pid = $row['print_id'];
    echo "<tr><td align=\"left\"><a href=\"browsePrints.php?aid={$row['artist_id']}\">{$row['artist']}</a></td>";
       if ($image = @getimagesize ("../uploads/$pid")) {
               echo "<td align=\"center\"><img src=\"showPrint.php?image=$pid&name=" . urlencode($row['imagename']) . "\" $image[3] alt=\"{$row['printname']}\" />
               </td>\n";
       }
    
    echo "<td align=\"left\"><a href=\"viewPrint.php?pid={$row['print_id']}\">{$row['printname']}</td>
    <td align=\"left\">{$row['description']}</td>
    <td align=\"right\">{$row['price']}</td>
    </tr>\n";
    }
    echo '</table>';
    mysqli_close($dbc);
    include ('includes/footer.html');
    ?>
    

    • Upvote 1
  3. browse-prints.php is part of the ecommerce example. You need to provide your own images, store them in a directory and set up the database which accesses the filename of the images. Ideally use the admin functions addArtist.php and addPrint.php to populate the d/b and get the files stored in the correct directory. If you work through the beginning of the chapter you'll set up the database, file structure and admin functions.

     

    I've modified the scripts to enable a client to upload images to his portfolio site - a mini CMS without the ecommerce side.

  4. I've realised that in the artists table there is a typo on the description field which I've corrected and the affected_rows statement is incorrect, it should be

    if (mysqli_stmt_affected_rows($stmt) == 1) {
    

     

    AlsoI've put some debugging code in the script which yields the following:

     

    Notice: Query: INSERT INTO prints (artist_id, printname, price, size, description, imagename) VALUES (?, ?, ?, ?, ?, ?)

    MySQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?, ?, ?, ?)' at line 1 in /Applications/MAMP/htdocs/Ecommerce/admin/addPrint.php on line 57

     

    The print is inserted into the d/b and the file is uploaded to the uploads directory but I'm not sure what the above notice is referring to. I'd appreciate your suggestions. Thanks!

  5. I'm having trouble with the addPrint php script and hoping someone can spot my error.

     

    The form validation works as I get the appropriate error messages and I know I'm connecting to the database as the list of artists is being displayed in a drop down menu on the form. I also receive the message 'the image file has been uploaded' so I'm getting part way there.

     

    but I also get the following warnings:

    Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given in /Applications/MAMP/htdocs/Ecommerce/admin/addPrint.php on line 55

     

    Warning: mysqli_stmt_execute() expects parameter 1 to be mysqli_stmt, boolean given in /Applications/MAMP/htdocs/Ecommerce/admin/addPrint.php on line 56

     

    Notice: Use of undefined constant mysqli_stmt_affected_rows - assumed 'mysqli_stmt_affected_rows' in /Applications/MAMP/htdocs/Ecommerce/admin/addPrint.php on line 57

     

    and my error message 'The print could not be inserted etc...".

     

    I'm thinking the problem is with the prepared insert statement and possibly to do with the $a variable as the selected artist is not 'sticky'. any suggestions??? Also I'm not familiar with the $_POST['existing'], is there somewhere I could learn more about that bit of code, didnt find anything in the php manual.

     

    here's my addPrint.php code

     

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Add an Artist</title>
    <style>
    body {font-family:sans-serif; color:#666666}
    .error {font-weight:bold; color:#c00;}
    </style>
    </head>
    <body>
    <?php
    //ADD Print -
    //
    require ('../../mysqli_connect.php');
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $errors = array();
    if (!empty($_POST['printname'])) {
    $pn = trim($_POST['printname']);
    } else {
     $errors[] = 'Please enter the print\'s name';
     }
     if (is_uploaded_file($_FILES['image']['tmp_name'])){
     $temp = '../../uploads/' . md5($_FILES['image']['name']);
      if (move_uploaded_file($_FILES['image']['tmp_name'], $temp)) {
      echo '<p>The image file has been uploaded.</p>';
      $i = $_FILES['image']['name'];
     } else {
      $errors[] = "The file could not be moved.";
      $temp = $_FILES['image']['tmp_name'];
      }
     } else {
      $errors[] = 'No file was uploaded.';
      $temp = NULL;
      }
    
    $s = (!empty($_POST['size'])) ? trim($_POST['size']) : NULL;
      if (is_numeric($_POST['price']) &&  ($_POST['price'] > 0)) {
      $p = (float)$_POST['price'];
      } else {
      $errors[] = 'Please enter the print\'s price.';
      }
    
    $d = (!empty($_POST['descrip'])) ? trim($_POST['descrip']) : NULL;
    
    if (isset($_POST['artist']) && filter_var($_POST['artist'], FILTER_VALIDATE_INT, array('min_range' => 1))  ) {
     $a = $_POST['artist'];
     } else {
     $errors[] = 'No artist was selected, please select the print\'s artist.';
     }
    // insert the record into the database
    if (empty($errors)) {
    $q = 'INSERT INTO prints (artist_id, printname, price, size, description, imagename) VALUES (?, ?, ?, ?, ?, ?)';
    $stmt = mysqli_prepare($dbc, $q);
    mysqli_stmt_bind_param($stmt, 'isdsss', $a, $pn, $p, $s, $d, $i);
    mysqli_stmt_execute($stmt);
    if (mysqli_stmt_affected_rows ==1) {
     echo '<p>The print has been inserted successfully</p>';
     $id = mysqli_stmt_insert_id($stmt);
     rename ($temp, "../../uploads/$id");
     $_POST = array();
     } else {
      echo '<p class="error">The print could not be inserted due to a system error. Please try later.</p>';
      }
     mysqli_stmt_close($stmt);
     }
    if (isset($temp) && file_exists($temp) && is_file($temp) ){
    unlink ($temp);
    }
    }
    if (!empty($errors) && is_array($errors)) {
    echo '<h2 class="error">Error!</h2><p class="error">The following errors occurred:<ul>';
     foreach ($errors as $msg) {
     echo '<li>' . $msg . '</li>';
     }
     echo '</ul><p>Please reselect the print image and try again.</p>';
    }
    ?>
    <h1>Add a Print</h1>
    <form enctype="multipart/form-data" action="addPrint.php" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="524288" />
    <fieldset><legend>Please fill in the form to add a print to the catalogue:</legend>
    <p><b>Print name: </b><input name="printname" type="text" size="30" maxlength="60"
    value="<?php if (isset($_POST['printname'])) echo htmlspecialchars($_POST['printname']); ?>"/></p>
    <p><b>Image: </b><input type="file" name="image" /></p>
    <p><b>Artist: </b><select name="artist"><option>Select One</option>
    <?php
    $q = "SELECT artist_id, CONCAT_WS(' ', firstname, middlename, lastname) FROM artists ORDER BY lastname, firstname ASC";
    $r = mysqli_query($dbc, $q);
    if (mysqli_num_rows($r) > 0) {
    while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) {
     echo "<option value = \"$row[0]\"";
      if (isset($_POST['existing']) && ($_POST['existing'] == $row[0]))
    echo ' selected="selected"';
    echo ">$row[1]</option>\n";
    }
      } else {
    echo '<option>Please add a new artist first.</option>';
    }
    mysqli_close($dbc);
    ?>
    </select></p>
    <p><b>Price: </b> <input type="text" name="price" size="10" maxlength="10"
    value="<?php if (isset($_POST['price'])) echo $_POST['price']; ?>" /><small>Do not include the currency sign or commas.</small></p>
    <p><b>Size: </b> <input type="text" name="size" size="10" maxlength="10"
    value="<?php if (isset($_POST['size'])) echo htmlspecialchars($_POST['size']); ?>" /><small>optional</small></p>
    <p><b>Description: </b> <textarea name="descrip" cols="40" rows="6" >
    <?php if (isset($_POST['descrip'])) echo $_POST['descrip']; ?></textarea><small>optional</small></p>
    </fieldset>
    <div align="center"><input type="submit" name="submit" value="Add print" /></div>
    </form>
    </body>
    </html>
    

  6. I looked in Larry's PHP advanced book (chapter 9) to learn about cURL and saw that he was achieving what I wanted using fopen. I ended up using file_get_contents which has worked. Here's the final code.

    
    <?php 
    $weather = file_get_contents("http://free.worldweatheronline.com/feed/weather.ashx?q=10022&format=xml&num_of_days=5");
    $data = new SimpleXmlElement($weather);
    
    echo '<table id="forecast"><tr>';
    foreach ($data->weather as $weather) {
    $date = (string) $weather->date;
    $iconUrl = (string) $weather->weatherIconUrl;
    $maxF = (int) $weather->tempMaxF;
    $minF = (int) $weather->tempMinF;
    $desc = (string) $weather->weatherDesc;
    
    echo '<td><ul id="daily"><li class="desc">'. date('D', strtotime($date)) . '</li>
    <li><img src="' . $iconUrl . '" alt="weather icon" height="30" width="30"</li>
    <li class="temp">' . $maxF . '&deg/' . $minF . '&deg</li>
    </ul></td>';
    }
    echo '</tr></table>';
    echo '</body></html>';
    foreach ($data->weather as $weather) {
    $date = (string) $weather->date;
    $iconUrl = (string) $weather->weatherIconUrl;
    $maxF = (int) $weather->tempMaxF;
    $minF = (int) $weather->tempMinF;
    $desc = (string) $weather->weatherDesc;
    
    echo '<td><ul id="daily"><li class="desc">'. date('D', strtotime($date)) . '</li>
    <li><img src="' . $iconUrl . '" alt="weather icon" height="30" width="30"</li>
    <li class="temp">' . $maxF . '&deg/' . $minF . '&deg</li>
    </ul></td>';
    }
    echo '</tr></table>';

    You need to apply for an api key to use the online weather service and include it in the URL.

     

    Is there a reason that cURL would work better than this method?

     

    @Larry - I think your books are excellent, I learned so much from PHP and MYSQL for Dynamic Web Sites that I bought Advanced PHP. Thanks.

    • Upvote 1
  7. I've badly misunderstood how ajax works and realise that my xmlhttprequest needs to be done in a way that allows me to get data that originates from a different server. The xmlhttprequest should be to

     request.open("GET","http://free.worldweatheronline.com/feed/weather.ashx",true);

    then I need to access the returned file

    request.responseXML

    and make it available to forecast.php, which I'm not sure how to do. I'm also not sure how to initiate the xmlhttprequest. Clearly I'm out of my depth here - any light you can shed or pointers to resources would be great.

  8. I'm trying to insert some weather data from on online service to a web page using xmlhttprequest to get the data and a php script to output the data. The php script, below, works fine as I've tested it on a static xml file

    <?php
    include 'weather.php';
    $data= new SimpleXMLElement($xmlstr);
    echo '<table id="forecast"><tr>';
    foreach ($data->weather as $weather) {
    $date = (string) $weather->date;
    $iconUrl = (string) $weather->weatherIconUrl;
    $maxF = (int) $weather->tempMaxF;
    $minF = (int) $weather->tempMinF;
    $desc = (string) $weather->weatherDesc;
    echo '<td><ul id="daily"><li class="desc">'. date('D', strtotime($date)) . '</li>
    <li><img src="' . $iconUrl . '" alt="weather icon" height="30" width="30"</li>
    <li class="temp">' . $maxF . '&deg/' . $minF . '&deg</li>
    </ul></td>';
    }
    echo '</tr></table>';
    ?>
    

    but I'm struggling to understand how to get the data from the xmlhttprequest to the php script. I've tried to code an xmlhttprequest but need some help. If I used the script below, how does the php script access the returned data which is sent as an xml file? Thanks.

    request.onreadystatechange = function() {
    if request.readyState == 4 && request.status == 200{
     return true;
    }
    }
    if (window.XMLHttpRequest)
    request=new XMLHttpRequest();
    else request=new ActiveXObject("Microsoft.XMLHTTP");  // code for IE 6 or before.
    request.onreadystatechange;
    request.open("GET","forecast.php",true);
    request.send();		   // Send "Get" request to specified PHP script.
    }
    

  9. thanks for the replies -

     

    @Antonio -see post 6 where I spotted that error.

    @Josee - I put $q in quotes just for that post, not in the actual code. My bad.

     

    Here's what I've used

    $q = "SELECT comments.comment, DATE_FORMAT(comments.dateSub, '%M %Y') AS ds, CONCAT(users.firstName, ' ', users.lastName) AS author
    FROM comments LEFT JOIN users ON userId = comments.userId ORDER BY comments.dateSub DESC";
    

    It doesn't work as I want it to but at least I am no longer getting a syntax error. I'm now getting all comments displayed as many times as there are userIds on the user database. So I'm going back to read more about joins.

  10. Thanks for your suggestion. Here's the error I received: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '$q = "SELECT c.comment, DATE_FORMAT(c.dateSub, '%M, %Y') AS ds, CONCAT(m.firstNa' at line 1

     

    I'm not sure what kind of join to use - I chose the left join as I want to display all the comment fields from the comments table with its corresponding author, getting the author's name via the userID. You can view my protocol to get an idea of what I'm trying to do. After each comment the first number is the userId which I want to display as the author - firstName lastName - then the date formatted as month, year.

  11. I"m struggling to understand how best to use joins. Here's an example I'm trying to code. I have 2 tables in a d/b - User table stores userId, firstName, lastName, dateOfStay and some other fields; Comments table stores commentId, userId, comment, dateSubmitted.

     

    I would like to display all the comments with the corresponding firstName, lastName and dateSubmitted in descending order by dateSubmitted. I know I need to use a join of some kind, an outer join I think, and would like to use a CONCAT so I can display the author of the comment as firstname lastname and display the dateSubmitted formatted to month, year which is stored as a timestamp using the NOW function.

     

    Any suggestions?

  12. I've only read the first section and already I'm finding this chapter very useful. 2 questions:

     

    1. I've created the spam_scrubber function to use on one of my own forms and during testing the characters \r and \n instead of being replaced by spaces are preceded by an additional slash. $0a and %0d are being replaced by spaces as anticipated. Any suggestions?

     

    2. when tabbing to the comments box of the form, the cursor goes to the middle of the first line rather than the start of the first line. this also happens when i test for the condition when name and email are completed but the comment field is not. What do I need to do to have the cursor appear at the start of the comment block. I know this is not strictly a php question, but if you have any suggestions it would be appreciated.

  13. I've got this script working nicely but while I was testing 2 questions cropped up:

     

    1. If the new password entered is the same as the current password, it is rejected. Is that a feature of mysql?

     

    2. mysqli_error didn't show up the error that I was encountering as a result of question 1. Is there something wrong with my code?

     

    echo '<h1>System Error</h1>
      <p class="error">You password could not be changed due to a system error. We apologise
      for any inconvenience.</p>';
      echo '<p>' . mysqli_error($dbc) . '</p><p>Query: ' . $q . '</p>';
    

     

    Everything displayed including the $q variable but not the mysqli_error($dbc). Thanks for replying.

×
×
  • Create New...