Link to home
Start Free TrialLog in
Avatar of Peter Kroman
Peter KromanFlag for Denmark

asked on

FInalizing my project

I now have two pages. A Searchpage and a Presentation- and upload page.

Searchpage: http://kroweb.dk/gfdev/gravsten_raw/

Presentation/upload page: http://kroweb.dk/gfdev/dataupload/

Both these pages works fine as it is now. The presentation/upload page uploads the entered data in the dataform to a new record in the database, and it uploads an image to a specified folder on the server.

When entering a searchstring e.g.”Lyng” on the Searchpage, it returns a list of results, where entries in the first column (with the headline “Sogn”) links to the Presentation/upload page.

The task now, is to get these two pages to work together, and to create the right common functionality.

(From here I need help to create the right code)

Clicking the link that opens the Presentation/upload page should do two things:

1.      Grab the id of the selected record from the “id” column in the database
2.      Retrieve and insert in the headline of the updateform (where it says …. ‘Sogn’ right now), the entry in the row “Sogn” in the actual record in the db. And at the same time retrieve data, if any is present, from the rows “navn”, “tlf”, “email” and “besked” in the database and insert them in the appropriate fields in the form. Finally it should display images, if any present, tied to the specific record on the page (see also  bullet 2. Below).

Furthermore I need to use the id for:

1.      Use in an SQL update query like: $sql = "UPDATE my_table SET name='name in form', email=’email in form’, ‘tlf in form’, ‘besked in form’ WHERE id=grabbed id"; in order to update the actual record with the update data. This should execute when clicking the Update button on the Presentation/upload page.
2.      Create a subfolder named by the id for uploading imagefiles belonging to this record. When uploading an image the row “image_table” in the DB  should be updated with the URL to that folder ( I am not sure if this is the best/right way to do this, and I am certainly open to other suggestions to bind uploaded images to a specific record in the db). This should execute, checking if the subfolder we are trying to create is already present, when clicking the Upload button on the Presentation/upload page

You might say that it is not safe that everybody can make updates in the database and everybody can upload images to the server. This is handled through my user access-control and password system, Sitelok, so I am confident that only the persons with the right credentials will be able to make updates and uploads.

I copy in the code for the Presentation/upload page with the forms, for the php file that creates updates to the database, and for the php file that creates image upload to the server, and hope that someone can help me moving on towards the final goal for this project  

Presentation/upload page:
<?php 
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<!DOCTYPE html>
<html lang="da">
    <head>
        <meta charset="utf-8" lang="da">
        <title>Presentation/upload</title>
    </head>

    <style> 

    input[type=text] {
    width: 100%;
    height: 30px;
    padding: 2px 20px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    background-color: #f8f8f8;
    font-family: arial;
    font-size: 12px;
    resize: none;
}

    textarea {
    width: 100%;
   
    padding: 12px 20px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    background-color: #f8f8f8;
    font-family: arial;
    font-size: 12px;
    resize: none;
}

    .flex-container {
    display: -webkit-flex;
    display: flex;
    width: 510px;
    border-collapse: collapse;
    background-color: white;
    padding-bottom:10px;
    margin-right: 2px;
}

    .flex-item {

    margin: 0px;
    width: 250px;
    border: 1px  lightgrey;
    border-style: solid;
    border-collapse: collapse;
    padding-left: 5px;
    padding-right: 5px;
    padding-bottom: 5px;

}
    </style>
    <style type="text/css">
        .message { margin-top: 7px; font-family: arial; font-size: 12px; color: #666666; text-align: center; background-color: lightgreen; border: 1px solid lightgrey; padding-left: 0px; padding-right: 0px; }
        .message2 { margin-top: 7px; font-family: arial; font-size: 12px; color: white; text-align: center; background-color: red; border: 1px solid #666666; padding-left: 0px; padding-right: 0px; }
        .success { margin-top: 7px; font-family: arial; font-size: 12px; color: #666666; text-align: center; background-color: lightgreen; border: 1px solid lightgrey; padding-left: 0px; padding-right: 0px; }
        .error { margin-top: 7px; font-family: arial; font-size: 12px; color: white; text-align: center; background-color: red; border: 1px solid #666666; padding-left: 0px; padding-right: 0px; }
    </style>



    <body>

    <div class="flex-container">
        <div class="flex-item" style="margin-top:10px; float:left; margin-left:10px; overflow:auto; background-color:#f6f6f6;">

        <form id="myForm" form action="insert.php" method="post">

        <p>Kontaktperson 'Sogn':</p>
        <p>
            <label for="firstName"></label>
            <input type="text" placeholder="Navn" name="navn" id="Name">
        </p>
        <p>
        <label for="lastName"></label>
        <input type="text" placeholder="Tlf." name="tlf" id="Phone">
        </p>
        <p>
            <label for="emailAddress"></label>
            <input type="text" placeholder="e-mail" name="email" id="emailAddress">
        </p>
        <p>
            <label for="opl"></label>
            <textarea rows="3" placeholder="Oplysninger" name="besked" id="opl"></textarea>

        </p>

        <input type="submit" value="Update">
        </form>

        <?php if (isset($_SESSION['flash'])): ?>
        <div class="message">
        
        <?php
            echo $_SESSION['flash'];
            unset($_SESSION['flash']);
        ?>
        </div>
        <?php endif; ?>

         <?php if (isset($_SESSION['flash1'])): ?>
        <div class="message2">
        
        <?php
            echo $_SESSION['flash1'];
            unset($_SESSION['flash1']);
        ?>
        </div>
        <?php endif; ?>       

        <?php if (isset($_SESSION['flash2'])): ?>
        <div class="message2">
        
        <?php
            echo $_SESSION['flash2'];
            unset($_SESSION['flash2']);
        ?>
        </div>
        <?php endif; ?>


        </div>   

        <div class="flex-item" style="margin-top:10px; float:left; margin-left:10px; overflow:auto; background-color:#f6f6f6;">


        <form method="post" action="upload.php" enctype="multipart/form-data">
               <p>Vælg fil der skal uploades:</p>
                <input type="file" name="fileToUpload" id="fileToUpload">
                <br>
                <br>
                <input type="submit" value="Upload" name="submit">
        </form>

        <?php if (isset($_SESSION['response'])): ?>
            <?php
            $response = json_decode($_SESSION['response']);
            unset($_SESSION['response']);
            ?>

            <div class="message <?php echo $response->success ? "success" : "error" ?>">
                <?php echo $response->message; ?>
            </div>
        <?php endif ?>
        </div>
    </div>

    </body>
</html>

Open in new window


Image upload page:
<?php
// Prevent direct access to the script
if (!isset($_POST['submit'])) die("Access Denied!");

// Start the session
session_start();

// Assume the file is invalid until proven otherwise
$uploadValid = false;

// Get some info about the potential file upload
$file = $_FILES["fileToUpload"]["name"];
$folder = "./image_uploads/";
$destination = $folder . $file;
$imageInfo = $_FILES["fileToUpload"]["size"] ? getimagesize($_FILES['fileToUpload']['tmp_name']) : false;

// Check if we have a file
if ($_FILES["fileToUpload"]["error"] === 4) {
    $message = "We have no file";
}
// Check if it has a size
elseif ($_FILES["fileToUpload"]["size"] === 0) {
    $message = "The file is empty";
}
// Check if it's an image
elseif ($imageInfo === false || ($imageInfo[2] !== IMAGETYPE_GIF) && ($imageInfo[2] !== IMAGETYPE_JPEG) && ($imageInfo[2] !== IMAGETYPE_PNG)) {
    $message = "The file is not a valid image";
}
// Something else went wrong!
elseif ($_FILES["fileToUpload"]["error"] !== 0) {
    $message = "There was a problem uploading your file";
}
// Check if it already exists
elseif (file_exists($destination)) {
    $message = "The file already exists";
}
// All good - let's try to move the file :)
else {

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $destination)) {
        // The move was successful
        $message = "The file was uploaded sucessfully";
        $uploadValid = true;

    } else {
        // The move failed
        $message = "There was an error uploading your file";
    }
}

// Let's generate a response
$response = array(
    "success" => $uploadValid,
    "message" => $message
);

// Let's push the response to the SESSION
$_SESSION['response'] = json_encode($response);

// And send the user on his way
header('Location: ' . $_SERVER['HTTP_REFERER']);

?>

Open in new window


Database update page:
<?php
// Start the sesssion
session_start();
header('Location: index.php') ; 

$link = mysqli_connect("db credentials");
$link->set_charset("utf8");
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
 
// Escape user inputs for security
$navn = mysqli_real_escape_string($link, $_REQUEST['navn']);
$tlf = mysqli_real_escape_string($link, $_REQUEST['tlf']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$besked = mysqli_real_escape_string($link, $_REQUEST['besked']);
 
// attempt insert query execution

if ((($_POST['navn'])) || (($_POST['tlf'])) || (($_POST['tlf'])) || (($_POST['besked']))!="") {
$sql = "INSERT INTO gravsten (navn, tlf, email, besked) VALUES ('$navn', '$tlf', '$email', '$besked')";  
}else{
$_SESSION['flash1'] = "There are no data to upload";
// Redirect the user back
header('Location: ' . $_SERVER['HTTP_REFERER']);

}

if(mysqli_query($link, $sql)){
// if successful, set a session variable
$_SESSION['flash'] = "Record added successfully";

// Redirect the user back
header('Location: ' . $_SERVER['HTTP_REFERER']);	
   
} else{
$_SESSION['flash2'] = "Could not execute";
}
 
// close connection
mysqli_close($link);

?>

Open in new window

Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Hey Peter,

When you build your table after the search has been done, I'm guessing that information comes from the database. If at that point you have the Id of the record, the easiest thing to do would be to add that to the HREF of the link using a query string, so in your table you would end up with something like this:

<a href="http://kroweb.dk/gfdev/dataupload/?id=xxx" target="_blank">Lyng Sogn</a>

Then in the dataupload script, you can access that value like so:

$id = $_GET['id'];

You can then use it to query your database, pull down the record and insert the values into your form, as well as displaying the image.
Avatar of Peter Kroman

ASKER

Thanks Chris,

I will work with that :)
Yes - information in the table comes from the database, so I have the id at that point.

But I don't understand how and where to use this: <a href="http://kroweb.dk/gfdev/dataupload/?id=xxx" target="_blank">Lyng Sogn</a>
and how the id actually is grabbed to be used for other purposes.

Could you please elaborate a bit more over that :)
Sure. You haven't shown how you're building the Search Results, but at some point I'm guessing that you query your Db for the search term, and from that you get a set of records. If you're manually building the <a> tag from there, then that's the point where you add the query string, for example:

$link = sprintf("<a href='http://kroweb.dk/gfdev/dataupload/?id=%s' target='_blank'>%s</a>", $record->id, $record->text);

Once all your links have a querystring, (such as id=123), then whenever you access that page (click the link), the query string is available in the $_GET array, so if you access your page like so:

http://kroweb.dk/gfdev/dataupload/?id=123

then in the dataupload/index.php script you would access the id value by checking the 'id' key of the Get array:

$id = $_GET['id'];
echo $id; // this will echo out 123
Does that meat that I manually have to add the id's to all appr. 2.200 entries in the table?

I paste in the search code here:

<!-- Search code starts here -->
<?php
    if ((isset($_POST['query'])) && (trim($_POST['query'])!="")) {
    $con=mysqli_connect("db credentials") or die("Error connecting to database: ".mysql_error());
    
    mysqli_select_db($con,"genealogiskforum_dk_db4");    
    mysqli_set_charset($con,"utf8");    
?> 


</div>    
<div class="flex-container" style="width:site-width; background-color:white;">
<div class="flex-item" style="margin-top:10px; float:left; margin-left:20px;width: site-width; overflow:auto;">

<?php
    $query = trim($_POST['query']); 
    //print "query=".$query;
    // gets value sent over search form    

    $min_length = 2;

    if(strlen($query) >= $min_length){ 

        $query = htmlspecialchars($query,ENT_QUOTES,"utf-8"); 
             

        $query = mysqli_real_escape_string($con, $query);
        // makes sure nobody uses SQL injection

        $raw_results = mysqli_query($con, "SELECT * FROM gravsten
             WHERE (`Sogn` LIKE '%".$query."%') OR (`Provsti`='$query') OR (`Stift`='$query')") or die(mysql_error());

        if(mysqli_num_rows($raw_results) > 0){ 
             echo "<table><tr><th>Sogn</th> <th>Provsti</th> <th>Stift</th>  </tr>  " .$results['Sogn'];
 
            while($row = $result=mysqli_fetch_array($raw_results)) {
           

            echo "<tr><td>";

            echo  "<a href=\"".$row["URL"]."\"target=\"_blank\">" . $row["Sogn"]."<td>" . $row["Provsti"]. "<td>" . $row["Stift"]."<td>" ."</a>";  
  
            echo "</td></tr>";
         
    }
             echo "</table>"; 
         

        }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;
    }
mysqli_close($con);
}
?>
</div> 
<!-- End of search code -->

Open in new window

No. Each entry in the database will already have an ID (primary key), so just use that when you build your link (which still has HTML errors in!!)

echo  "<a href=\"".$row["URL"]."\"target=\"_blank\">" . $row["Sogn"]."<td>" . $row["Provsti"]. "<td>" . $row["Stift"]."<td>" ."</a>";

For example you would just tag the query string ono the end of the href. Something like this:

echo  "<a href=\"".$row["URL"]. "?id=" . $row["yourIdColumn"] . "\" target=\"_blank\">" . $row["Sogn"]."<td>" . $row["Provsti"]. "<td>" . $row["Stift"]."<td>" ."</a>";


I am a little confused though. In your code, it looks like you're setting the href to a value from the DB ($row["URL"]), but in your Search form, all the links point to http://kroweb.dk/gfdev/dataupload/
Sh.... I am checking for errors in Firefox all the time - but it is work in progress, so a missing </div> had sneaked in without I have noticed it. It should be fixed now :)

Yes - I am setting the the href value form the row URL, and right now I have the same value in all fields in the row URL, because I thought that opening this page could provide all the automatic. And some of it actually can I can see now. I have edited the href line now, and then I get a linkk like this kroweb.dk/gfedv/dataupload/?id=2068 which I assume means that the Presentation/upload form now relates to id 2068.

Is that a correct assumption?
Yes it is a correct assumption. I can see that now. I have managed to display the id in the headline in the update form. Fantastic :)

But how do I use the now grabbed id to access the other data in the record - both ways?
Haha - pretty much all of my coding is a work in progress :)

Sort of a correct assumption. The upload script doesn't relate to anything - you are now simply passing a value to the script in a querystring, which the script can retrieve with $_GET['id']
OK. So now you have the ID in your upload script, you use that to query your database. Pseudo-code looks like:

$id = $_GET['id'];
$sql= "SELECT field1, field2, field3 FROM yourTable WHERE id = $id";
$row = $db->query($sql);
echo $row->field1;
echo $row->field2;
echo $row->field3;
Yes - I get that (I think). I guess I can use your pseudo code-example with UPDATE in stead of SELECT as well.  

But I also need to use it in the index file with the forms. For two purposes.

1. To retrieve the value form the row "Sogn" in this headline over the first form where I now have managed to echo the id itself: Kontaktperson 2068
2. To retrieve data form the record in the form, if any is present and to display images, if any present, on the page.
When you have a link like this:

http://kroweb.dk/gfdev/dataupload/?id123

You don't have a page name (index for example) so it is assumed. Now in the index.php page which contains your form, at the start you would connect to your Db, and run the SELECT query, using the $_GET['id'] as I've already outlined.

This will return a record from your database. Further down the page, you can then echo out the values that have been returned directly into your form:

<?php
$id = $_GET['id'];
$sql= "SELECT field1, field2, field3 FROM yourTable WHERE id = $id";
$row = $db->query($sql);
?>
<html>
<head></head>
....
<form>
    <input type="hidden" name="id" value="<?php echo $id ?>" />
   <input type="text" name="someField" value="<?php echo $row->field1?>" />
</form>

<img src="/imageFolder/<?php echo $row->imageName ?>" />

Open in new window

Thanks. Sounds easy, but I'm sure it is not quite that easy after all :)
I will work with it, and get back when I crash into the fence .....
No, no, no - I have not reached the fence yet :)

I just have a question to clarify how I set up the UPDATE SET statement when I need to update records from the table.

update gravsten
  set 'form field name 'navn', form field name 'tlf' etc-
  where id = $id;
An update statement look like this:

UPDATE yourTable SET field1 = 'value1', field2 = 'value2', field3 = 'value3' WHERE id = xxx

If you absolutely trust your users, then you can use the post array (form fields) directly. If you don't then you should really use a parameterised query. To build your query with the post array you can do something like this (where the POST keys are the names of your form fields):

$sql = sprintf("INSERT INTO yourTable SET field1 = '%s', field2 = '%s', field3 = '%s' WHERE id = %s", $_POST['val1'], $_POST['val2'], $_POST['val3'], $_POST['id']);

Open in new window

Thanks Chris,
But I should use the UPDATE statement and not the INSERT INTO statement, right ??
I have set the firsr try (getting the value in the row Sogn for the headline over the first form) up like this, and I get an "Trying to get property of non-object" error. I just past the part of the code I am working with here - hope that is OK?

<?php 
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

$link = db credentials");
$link->set_charset("utf8");
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$id=$_GET['id'];


$sql = "SELECT Sogn, navn, tlf, email, besked FROM gravsten WHERE id = $id)"; 
$row = $link->query($sql);

?>

<!DOCTYPE html>
<html lang="da">
    <head>
        <meta charset="utf-8" lang="da">
        <title>Presentation/upload</title>
    </head>

   
    <body>
     
.....
  


        <form id="myForm" form action="insert.php" method="post">

        <p>Kontaktperson i  <?php echo $row->Sogn ?></p>
        <p>
            <label for="firstName"></label>
            <input type="text" placeholder="Navn" name="navn" id="Name">
        </p>
        <p>
        <label for="lastName"></label>
        <input type="text" placeholder="Tlf." name="tlf" id="Phone">
        </p>
        <p>
            <label for="emailAddress"></label>
            <input type="text" placeholder="e-mail" name="email" id="emailAddress">
        </p>
        <p>
            <label for="opl"></label>
            <textarea rows="3" placeholder="Oplysninger" name="besked" id="opl"></textarea>

        </p>

        <input type="submit" value="Update">
        </form>
    .......
     
  

Open in new window

Hey Peter. Yes - you use an UPDATE statement to update an existing record in your DB and you use an INSERT statement to create a new record.

The problem with your code is that you have ran the query, but not fetched any data. You have this:

$sql = "SELECT Sogn, navn, tlf, email, besked FROM gravsten WHERE id = $id)";
$row = $link->query($sql);

What you should have is this:

$sql = "SELECT Sogn, navn, tlf, email, besked FROM gravsten WHERE id = $id)";
$result = $link->query($sql);
$row = $result->fetch_object();
When putting $row = $result->fetch_object(); in I get a Undefined variable: result error in the line.

$link = mysqli_connect("db credentials");
$link->set_charset("utf8");
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$id=$_GET['id'];


$sql = "SELECT Sogn, navn, tlf, email, besked FROM gravsten WHERE id = $id)"; 
$row = $link->query($sql);
$row = $result->fetch_object();

Open in new window

Sorry. I made a mistake.

The code looks like this:

$link = mysqli_connect("db credentials");
$link->set_charset("utf8");
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$id=$_GET['id'];


$sql = "SELECT Sogn, navn, tlf, email, besked FROM gravsten WHERE id = $id)"; 
$result = $link->query($sql);
$row = $result->fetch_object();

?>

Open in new window


And I get this error:
Fatal error: Call to a member function fetch_object() on boolean in /var/www/kroweb.dk/public_html/gfdev/dataupload/index.php on line 19 - where line 19 is line 14 here.
Looks like you have an error in your SQL - you have a rogue closing parenthesis at the end:

$sql = "SELECT Sogn, navn, tlf, email, besked FROM gravsten WHERE id = $id)"; <!-- remove the closing bracket.
There is something wrong.

When I try to run the UPDATE it will not recognize the $id variable.

I get this error: Notice: Undefined index: id in /var/www/kroweb.dk/public_html/gfdev/dataupload/index.php on line 14

<?php 
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

$link = db credentials");
$link->set_charset("utf8");
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$id = $_GET[ 'id' ];


$sql = "SELECT Sogn, navn, tlf, email, besked FROM gravsten WHERE id = $id)"; 
//$result = $link->query($sql);
//$row = $result->fetch_object();
//$row = $link->query($sql);


?>

<!DOCTYPE html>
<html lang="da">
    <head>
        <meta charset="utf-8" lang="da">
        <title>Presentation/upload</title>


    <style> 

    input[type=text] {
    width: 100%;
    height: 30px;
    padding: 2px 20px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    background-color: #f8f8f8;
    font-family: arial;
    font-size: 12px;
    resize: none;
}

    textarea {
    width: 100%;
   
    padding: 12px 20px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    background-color: #f8f8f8;
    font-family: arial;
    font-size: 12px;
    resize: none;
}

    .flex-container {
    
}

    .flex-item {

    margin: 0px;
    width: 250px;
    border: 1px  lightgrey;
    border-style: solid;
    border-collapse: collapse;
    padding-left: 5px;
    padding-right: 5px;
    padding-bottom: 5px;

}
    </style>
    <style type="text/css">
        .message { margin-top: 7px; font-family: arial; font-size: 12px; color: #666666; text-align: center; background-color: lightgreen; border: 1px solid lightgrey; padding-left: 0px; padding-right: 0px; }
        .message2 { margin-top: 7px; font-family: arial; font-size: 12px; color: white; text-align: center; background-color: red; border: 1px solid #666666; padding-left: 0px; padding-right: 0px; }
        .success { margin-top: 7px; font-family: arial; font-size: 12px; color: #666666; text-align: center; background-color: lightgreen; border: 1px solid lightgrey; padding-left: 0px; padding-right: 0px; }
        .error { margin-top: 7px; font-family: arial; font-size: 12px; color: white; text-align: center; background-color: red; border: 1px solid #666666; padding-left: 0px; padding-right: 0px; }
    </style>

    </head>

    <body>
     

    <div class="flex-container">
        <div class="flex-item" style="margin-top:10px; float:left; margin-left:10px; overflow:auto; background-color:#f6f6f6;">



        <form id="myForm" form action="insert.php" method="post">

        <p>Kontaktperson i  <?php echo $id ?></p>
        <p>
            <label for="firstName"></label>
            <input type="text" placeholder="Navn" name="navn" id="Name">
        </p>
        <p>
        <label for="lastName"></label>
        <input type="text" placeholder="Tlf." name="tlf" id="Phone">
        </p>
        <p>
            <label for="emailAddress"></label>
            <input type="text" placeholder="e-mail" name="email" id="emailAddress">
        </p>
        <p>
            <label for="opl"></label>
            <textarea rows="3" placeholder="Oplysninger" name="besked" id="opl"></textarea>

        </p>

        <input type="submit" value="Update">
        </form>

        <?php if (isset($_SESSION['flash'])): ?>
        <div class="message">
        
        <?php
            echo $_SESSION['flash'];
            unset($_SESSION['flash']);
        ?>
        </div>
        <?php endif; ?>

         <?php if (isset($_SESSION['flash1'])): ?>
        <div class="message2">
        
        <?php
            echo $_SESSION['flash1'];
            unset($_SESSION['flash1']);
        ?>
        </div>
        <?php endif; ?>       

        <?php if (isset($_SESSION['flash2'])): ?>
        <div class="message2">
        
        <?php
            echo $_SESSION['flash2'];
            unset($_SESSION['flash2']);
        ?>
        </div>
        <?php endif; ?>


        </div>   

        <div class="flex-item" style="margin-top:10px; float:left; margin-left:10px; overflow:auto; background-color:#f6f6f6;">


        <form method="post" action="upload.php" enctype="multipart/form-data">
               <p>Vælg fil der skal uploades:</p>
                <input type="file" name="fileToUpload" id="fileToUpload">
                <br>
                <br>
                <input type="submit" value="Upload" name="submit">
        </form>

        <?php if (isset($_SESSION['response'])): ?>
            <?php
            $response = json_decode($_SESSION['response']);
            unset($_SESSION['response']);
            ?>

            <div class="message <?php echo $response->success ? "success" : "error" ?>">
                <?php echo $response->message; ?>
            </div>
        <?php endif ?>
        </div>
    </div>

    </body>
</html>

Open in new window

The wicket bracket solved the first problem. I kan now echo the Sogn name in the headline of the forst form.

But I still have the problem with the update. I get these errors:
Notice: Undefined index: id in /var/www/kroweb.dk/public_html/gfdev/dataupload/index.php on line 14

Fatal error: Call to a member function fetch_object() on boolean in /var/www/kroweb.dk/public_html/gfdev/dataupload/index.php on line 20

Using this code:

<?php 
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

$link = mysqli_connect("xxxxx", "xxxxx", "xxxxx", "xxxxx");
$link->set_charset("utf8");
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$id = $_GET[ 'id' ];



$sql = "SELECT Sogn, navn, tlf, email, besked FROM gravsten WHERE id = $id"; 
$result = $link->query($sql);
$row = $result->fetch_object();



?>

<!DOCTYPE html>
<html lang="da">
    <head>
        <meta charset="utf-8" lang="da">
        <title>Presentation/upload</title>
  

    <style> 

    input[type=text] {
    width: 100%;
    height: 30px;
    padding: 2px 20px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    background-color: #f8f8f8;
    font-family: arial;
    font-size: 12px;
    resize: none;
}

    textarea {
    width: 100%;
   
    padding: 12px 20px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    background-color: #f8f8f8;
    font-family: arial;
    font-size: 12px;
    resize: none;
}

    .flex-container {
    
}

    .flex-item {

    margin: 0px;
    width: 250px;
    border: 1px  lightgrey;
    border-style: solid;
    border-collapse: collapse;
    padding-left: 5px;
    padding-right: 5px;
    padding-bottom: 5px;

}
    </style>
    <style type="text/css">
        .message { margin-top: 7px; font-family: arial; font-size: 12px; color: #666666; text-align: center; background-color: lightgreen; border: 1px solid lightgrey; padding-left: 0px; padding-right: 0px; }
        .message2 { margin-top: 7px; font-family: arial; font-size: 12px; color: white; text-align: center; background-color: red; border: 1px solid #666666; padding-left: 0px; padding-right: 0px; }
        .success { margin-top: 7px; font-family: arial; font-size: 12px; color: #666666; text-align: center; background-color: lightgreen; border: 1px solid lightgrey; padding-left: 0px; padding-right: 0px; }
        .error { margin-top: 7px; font-family: arial; font-size: 12px; color: white; text-align: center; background-color: red; border: 1px solid #666666; padding-left: 0px; padding-right: 0px; }
    </style>

      </head>

    <body>
     

    <div class="flex-container">
        <div class="flex-item" style="margin-top:10px; float:left; margin-left:10px; overflow:auto; background-color:#f6f6f6;">



        <form id="myForm" form action="insert.php" method="post">

        <p>Kontaktperson i  <?php echo $row->Sogn ?></p>
        <p>
            <label for="firstName"></label>
            <input type="text" placeholder="Navn" name="navn" id="Name">
        </p>
        <p>
        <label for="lastName"></label>
        <input type="text" placeholder="Tlf." name="tlf" id="Phone">
        </p>
        <p>
            <label for="emailAddress"></label>
            <input type="text" placeholder="e-mail" name="email" id="emailAddress">
        </p>
        <p>
            <label for="opl"></label>
            <textarea rows="3" placeholder="Oplysninger" name="besked" id="opl"></textarea>

        </p>

        <input type="submit" value="Update">
        </form>

        <?php if (isset($_SESSION['flash'])): ?>
        <div class="message">
        
        <?php
            echo $_SESSION['flash'];
            unset($_SESSION['flash']);
        ?>
        </div>
        <?php endif; ?>

         <?php if (isset($_SESSION['flash1'])): ?>
        <div class="message2">
        
        <?php
            echo $_SESSION['flash1'];
            unset($_SESSION['flash1']);
        ?>
        </div>
        <?php endif; ?>       

        <?php if (isset($_SESSION['flash2'])): ?>
        <div class="message2">
        
        <?php
            echo $_SESSION['flash2'];
            unset($_SESSION['flash2']);
        ?>
        </div>
        <?php endif; ?>


        </div>   

        <div class="flex-item" style="margin-top:10px; float:left; margin-left:10px; overflow:auto; background-color:#f6f6f6;">


        <form method="post" action="upload.php" enctype="multipart/form-data">
               <p>Vælg fil der skal uploades:</p>
                <input type="file" name="fileToUpload" id="fileToUpload">
                <br>
                <br>
                <input type="submit" value="Upload" name="submit">
        </form>

        <?php if (isset($_SESSION['response'])): ?>
            <?php
            $response = json_decode($_SESSION['response']);
            unset($_SESSION['response']);
            ?>

            <div class="message <?php echo $response->success ? "success" : "error" ?>">
                <?php echo $response->message; ?>
            </div>
        <?php endif ?>
        </div>
    </div>

    </body>
</html> 

Open in new window

OK. I think you're getting confused between the GET array and the POST array. The GET array is populated when the address of your page has a querystring, such as index.php?id=123 (like the results on your Search page). The POST array get's populated when you submit a form:

<input type="hidden" name="id" value="123" />

When you want to retrieve (SELECT) information from the database, it's usually safe to do that by passing the ID in the querystring. When you want to edit or create (UPDATE / INSERT) a record in your database, you should always POST the data (submit a form).

You say that when you try to run the UPDATE, the id key is not recognised. In the code you've just posted there is no mention of an UPDATE, just a SELECT,  I'm guessing you've posted the wrong code. That page will only work if you access it with a querystring: dataupload/?id=123, and shold only be used for retrieving data from the database, not updating or creating.

Because you have 3 or 4 pages responsible for different parts of your application, sometimes you will need to use the GET array, and sometimes you will need to use the POST array.

As I understand it, you have a Search Page where you can type in a phrase and return a list of links. Each of these links contains a querystring:

dataupload/?id=123

In dataupload, you can retrieve the record from the database using the GET arrray value:

$row = "SELECT * FROM youTable WHERE id = $_GET['id']"

And then generate your form.

<form action="update.php">
<input type="hidden" name="id" value="$row->id">
<input type="text" name="firstName" value="$row->firstName">
...

Now when you post this form to the update.php script, you will have a POST array. Part of that array contains the id (the hidden field), so you would get the ID from POST:

$id = $_POST['id'];
UPDATE myTable SET firstName = $_POST['firstName'] WHERE id = $id;

Techincally you could use $_REQUEST instead of $_POST or $_GET as the $_REQUEST array contains all the info sent to the page whether by querystring or post. I tend to not use that as it makes the code slightly harder to read.

Hope that all makes sense.
That makes a lot of sense. I am working on with it.

By the way - is there a way to edit or delte my last post here - by mistake i have posted my db credentials again, and i really don't want to change password again, because it means that I have to change access code for 9 databases :)
No worries Peter. I've edited out your Db Credientials :)
Well - I have now addded this to my index file (with the forms):

       <form id="myForm" form action="insert.php" method="post">
        <input type="hidden" name="id" value="$row->id">

Open in new window


And my insert.php file looks now like this:

<?php
// Start the sesssion
session_start();
header('Location: index.php') ; 


$link = mysqli_connect("db credentials");
$link->set_charset("utf8");
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
 
// Escape user inputs for security
$navn = mysqli_real_escape_string($link, $_REQUEST['navn']);
$tlf = mysqli_real_escape_string($link, $_REQUEST['tlf']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$besked = mysqli_real_escape_string($link, $_REQUEST['besked']);
 
// attempt insert query execution

if ((($_POST['navn'])) || (($_POST['tlf'])) || (($_POST['tlf'])) || (($_POST['besked']))!="") {

$id = $_POST['id'];

$sql = sprintf("UPDATE gravsten SET navn, tlf, email, besked WHERE id = $id", $_POST['navn'], $_POST['tlf'], $_POST['email'], $_POST['besked']);
  
}else{
$_SESSION['flash1'] = "There are no data to upload";
// Redirect the user back
header('Location: ' . $_SERVER['HTTP_REFERER']);

}


if(mysqli_query($link, $sql)){
// if successful, set a session variable
$_SESSION['flash'] = "Record added successfully";

// Redirect the user back
header('Location: ' . $_SERVER['HTTP_REFERER']);	
   


} else{
$_SESSION['flash2'] = "Could not execute";
}
 
// close connection
mysqli_close($link);




?>

Open in new window


I still get these errors when trying to update:
Notice: Undefined index: id in /var/www/kroweb.dk/public_html/gfdev/dataupload/index.php on line 14

Fatal error: Call to a member function fetch_object() on boolean in /var/www/kroweb.dk/public_html/gfdev/dataupload/index.php on line 20
Sorry Peter. I'm struggling to see the big picture here. Maybe explain what pages you have and what each is supposed to do. For example, in your post above, you have a page called insert.php page, but all the code in there is doing an UPDATE, not an INSERT! Doesn't make a lot of sense at the moment. FYI - your update query is wrong. It doesn't set any values. It should be:

$sql = sprintf("UPDATE gravsten SET navn = '%s', tlf = '%s', email = '%s', besked = '%s' WHERE id = $id", $_POST['navn'], $_POST['tlf'], $_POST['email'], $_POST['besked']);

Open in new window


You then say that you get an error:

I still get these errors when trying to update:
Notice: Undefined index: id in /var/www/kroweb.dk/public_html/gfdev/dataupload/index.php on line 14
But as I understand it, the index page is just used for RETRIEVING the information from the database and building your forms. It's whats displayed when you click on a link fro the Search results page.

As I see the logic, you have a Search page. On this page are links that when clicked, take you to a page (dataupload/index.php page) where you can view the database record for the ID that's been passed through the query string . On this page (index.php), you use the querystring ($_GET['id']) to query the database for a matching record and you then use that record to build a form. This form has it's action property set to a script where you would update that database based on the infomation that was entered into the form. Let's call that script update.php. In the update.php script you will have all the information that was entered into the form available in the POST array (including the id from a  hidden field). On the update.php page, you then use that information to create an UPDATE query, which is when the database gets UPDATEd.

I don't see anywhere where you're actually INSERTing a new record into the database. And if you were, you wouldn't have an ID because there would be no record in the Database.
You have got the logic right :) and I believe that I am doing precisely as you explain. So I don't quite understand why I get an error message telling me that an index in the index file is not set, when I try to rund the UPDATE script and when it is just used to build the form.

I have four files.
The Search page located in the folder /gravsten_raw, which is OK, and which adds the hashtag to the links as it should. No problem there.

The three files we are working with now are located in the same foider /dataupload:
index.php which holds the two forms. One for updating the database and one for uploading images.
insert.php which holds the code for updating the database and is called from the corresponding form
upload.php which holds the code that uploads images ti a folder and is called from the corresponding (this one we are not discussing at the moment, I think that this will be the final thing we do)

And it is absolutely correct that I have no need to INSERT records to the database, because the records are static. But I do have the need to UPDATE them with the information from the form.

Hope it makes some sense?
OK. That makes sense. You might want to rename your insert.php page to update.php :)

I've got to head out for a few hours but I'll come back to this when I return. We'll get there.

One thing you can look. When you visit the index page from the Search Page, take a look at the source code in your browser to make sure your hidden id field is being set correctly, and that you have the correct names for th other 4 fields in the form: navn, tlf, email & besked
Thanks Chris,

I will take a look into that
We'll be talking later
No red lines in Firefox for the index.php in /dataupload :)
No red lines in the index.php in /gravsten_raw (the search page)
Hey Peter.

Had a look through the pages in your site. It looks like the Search page is working OK, so when you click on a link from the results, it takes you to the dataupload/?id=xx page which is correct. In the dataupload/index.php page it looks like you're making the correct query to the database, because the Kontaktperson information is showing, so that's good. Now you need to take the code in your index.php page one step further and put the values from the Db into your form.  At the start of the index.php page you have this:

$id = $_GET['id'];
$sql = "SELECT Id, Sogn, navn, tlf, email, besked FROM gravsten WHERE id = $id"; 
$result = $link->query($sql);
$row = $result->fetch_object();

Open in new window

** Because we need to use the Id, I've added the Id column to the SELECT clause in your query above ^

So after that, you have the database record in the $row variable, so you then do;

<p>Kontaktperson i  <?php echo $row->Sogn ?></p>
       
All good so far.

Now, you need the information from the database pushing into the form so that you can update it. As well as pushing the info into the form that you need to update, you also need to pass the id, so that you know which record to update. To do that, you would create your form something like this:

<form id="myForm" action="insert.php" method="post">
   <p>Kontaktperson i  <?php echo $row->Sogn ?></p>

   <input type="hidden" name="id" value="<?php echo $row->id ?>">

   <label for="firstName"></label>
   <input type="text" placeholder="Navn" name="navn" id="Name" value="<?php echo $row->navn ?>">

   <label for="lastName"></label>
   <input type="text" placeholder="Tlf." name="tlf" id="Phone" value="<?php echo $row->tlf ?>">

   <label for="emailAddress"></label>
   <input type="text" placeholder="e-mail" name="email" id="emailAddress" value="<?php echo $row->email ?>">

   <label for="opl"></label>
   <textarea rows="3" placeholder="Oplysninger" name="besked" id="opl"><?php echo $row->besked ?></textarea>

   <input type="submit" value="Update">
</form>

Open in new window

So now on the index.php page you have a form that is pre-populated with the data from your database, and also includes the ID in a hidden field.

The action of this form is insert.php. When the submit button is clicked, the form content will be POSTed to insert.php, so all the form fields, including the hidden ID will be passed to insert.php as part of the POST array. This means than in the insert.php page, you can update your database by building your UPDATE query

$sql = sprintf("UPDATE gravsten SET navn = '%s', tlf = '%s', email = '%s', besked = '%s' WHERE id = %s", $_POST['navn'], $_POST['tlf'], $_POST['email'], $_POST['besked'], $_POST['id']);

Hope that makes sense. Build your app piece by piece so it's easier to see how each moving part operates.
CHEERS AND BEERS :)

It works beautifully now. I get the data in the form, and I update the records. Thanks a h... of a lot - this is fantastic :)

Well - now we only need to get the last thing working together with the other stuff.

That is the image upload.

Right now I have an imageupload script that works fine uploading images to a folder named /image_uploads.
The upload function uploads one image at the time which is just fine though more images might be added to a record over time

What I need is:

1. To tie the image(s) to the record
2. To display the image(s) together with the forms (same page)
3. To have a small text box under the image where information about the actual image can be added

What would be nice (but not strictly necessary) to have:
1. That uploading the first image to a record sets a marker in (e.g. "OK") in the row "image_table" in the database. The reason is, that this would make it possible to make a query that returns all the records that have images attatched.

So now I paste in the full code of the index.php that holds the forms file as it looks now, and of the upload.php file which is the imageupload script.

index.php:
<?php 
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

$link = mysqli_connect("db credentials");
$link->set_charset("utf8");
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$id = $_GET[ 'id' ];
$sql = "SELECT id, Sogn, Stift, Provsti, navn, tlf, email, besked FROM gravsten WHERE id = $id"; 
$result = $link->query($sql);
$row = $result->fetch_object();



?>

<!DOCTYPE html>
<html lang="da">
    <head>
        <meta charset="utf-8" lang="da">
        <title>Presentation/upload</title>
  

    <style> 

    hr {

    color: #9F5584;;    
    }

    h5 {
    margin-top: 2px;
    margin-bottom: 0px;
    margin-right: 0px;
    margin-left: 0px;
    color: #9F5584;
    font-weight: normal;
    font-family: Georgia ;
    font-size: 14px;
    text-align: center;
    background-color: #f6f6f6;
}

    input[type=text] {
    width: 100%;
    height: 30px;
    padding: 2px 20px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    background-color: #f8f8f8;
    font-family: arial;
    font-size: 12px;
    resize: none;
}

    textarea {
    width: 100%;
   
    padding: 12px 20px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    background-color: #f8f8f8;
    font-family: arial;
    font-size: 12px;
    resize: none;
}

    .flex-container {
    
}

    .flex-item {

    margin: 0px;
    width: 250px;
    border: 1px  lightgrey;
    border-style: solid;
    border-collapse: collapse;
    padding-left: 5px;
    padding-right: 5px;
    padding-bottom: 5px;

}
    </style>
    <style type="text/css">
        .message { margin-top: 7px; font-family: arial; font-size: 12px; color: #666666; text-align: center; background-color: lightgreen; border: 1px solid lightgrey; padding-left: 0px; padding-right: 0px; }
        .message2 { margin-top: 7px; font-family: arial; font-size: 12px; color: white; text-align: center; background-color: red; border: 1px solid #666666; padding-left: 0px; padding-right: 0px; }
        .success { margin-top: 7px; font-family: arial; font-size: 12px; color: #666666; text-align: center; background-color: lightgreen; border: 1px solid lightgrey; padding-left: 0px; padding-right: 0px; }
        .error { margin-top: 7px; font-family: arial; font-size: 12px; color: white; text-align: center; background-color: red; border: 1px solid #666666; padding-left: 0px; padding-right: 0px; }
    </style>

      </head>

    <body>
     

    <div class="flex-container">
        <div class="flex-item" style="margin-top:10px; float:left; margin-left:10px; overflow:auto; background-color:#f6f6f6;">



        <form id="myForm" action="insert.php" method="post">
   <h5><?php echo $row->Provsti ?> Provsti, <? echo $row->Stift ?> Stift</h5> 
   <hr width="100%" >         
   <p>Kontaktperson i  <?php echo $row->Sogn ?> Sogn</p>

   <input type="hidden" name="id" value="<?php echo $row->id ?>">

   <label for="firstName"></label>
   <input type="text" placeholder="Navn" name="navn" id="Name" value="<?php echo $row->navn ?>">

   <label for="lastName"></label>
   <input type="text" placeholder="Tlf." name="tlf" id="Phone" value="<?php echo $row->tlf ?>">

   <label for="emailAddress"></label>
   <input type="text" placeholder="e-mail" name="email" id="emailAddress" value="<?php echo $row->email ?>">

   <label for="opl"></label>
   <textarea rows="3" placeholder="Oplysninger" name="besked" id="opl"><?php echo $row->besked ?></textarea>

   <input type="submit" value="Update">
</form>

        <?php if (isset($_SESSION['flash'])): ?>
        <div class="message">
        
        <?php
            echo $_SESSION['flash'];
            unset($_SESSION['flash']);
        ?>
        </div>
        <?php endif; ?>

         <?php if (isset($_SESSION['flash1'])): ?>
        <div class="message2">
        
        <?php
            echo $_SESSION['flash1'];
            unset($_SESSION['flash1']);
        ?>
        </div>
        <?php endif; ?>       

        <?php if (isset($_SESSION['flash2'])): ?>
        <div class="message2">
        
        <?php
            echo $_SESSION['flash2'];
            unset($_SESSION['flash2']);
        ?>
        </div>
        <?php endif; ?>


        </div>   

        <div class="flex-item" style="margin-top:10px; float:left; margin-left:10px; overflow:auto; background-color:#f6f6f6;">


        <form method="post" action="upload.php" enctype="multipart/form-data">
               <p>Vælg fil der skal uploades:</p>
                <input type="file" name="fileToUpload" id="fileToUpload">
                <br>
                <br>
                <input type="submit" value="Upload" name="submit">
        </form>

        <?php if (isset($_SESSION['response'])): ?>
            <?php
            $response = json_decode($_SESSION['response']);
            unset($_SESSION['response']);
            ?>

            <div class="message <?php echo $response->success ? "success" : "error" ?>">
                <?php echo $response->message; ?>
            </div>
        <?php endif ?>
        </div>
    </div>

    </body>
</html>

Open in new window



upload.php:
<?php
// Prevent direct access to the script
if (!isset($_POST['submit'])) die("Access Denied!");

$id=$_GET['id'];

// Start the session
session_start();

// Assume the file is invalid until proven otherwise
$uploadValid = false;

// Get some info about the potential file upload
$file = $_FILES["fileToUpload"]["name"];
$folder = "./image_uploads/";
$destination = $folder . $file;
$imageInfo = $_FILES["fileToUpload"]["size"] ? getimagesize($_FILES['fileToUpload']['tmp_name']) : false;

// Check if we have a file
if ($_FILES["fileToUpload"]["error"] === 4) {
    $message = "We have no file";
}
// Check if it has a size
elseif ($_FILES["fileToUpload"]["size"] === 0) {
    $message = "The file is empty";
}
// Check if it's an image
elseif ($imageInfo === false || ($imageInfo[2] !== IMAGETYPE_GIF) && ($imageInfo[2] !== IMAGETYPE_JPEG) && ($imageInfo[2] !== IMAGETYPE_PNG)) {
    $message = "The file is not a valid image";
}
// Something else went wrong!
elseif ($_FILES["fileToUpload"]["error"] !== 0) {
    $message = "There was a problem uploading your file";
}
// Check if it already exists
elseif (file_exists($destination)) {
    $message = "The file already exists";
}
// All good - let's try to move the file :)
else {

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $destination)) {
        // The move was successful
        $message = "The file was uploaded sucessfully";
        $uploadValid = true;

    } else {
        // The move failed
        $message = "There was an error uploading your file";
    }
}

// Let's generate a response
$response = array(
    "success" => $uploadValid,
    "message" => $message
);

// Let's push the response to the SESSION
$_SESSION['response'] = json_encode($response);

// And send the user on his way
header('Location: ' . $_SERVER['HTTP_REFERER']);

?>

Open in new window

Hey Peter. Excellent. Making Progress :)

The final part of your app should be fairly straight forward. Basically, when you call the index.php page to display the forms, you already have the ID of the gravsten record. If you add this as a hidden input on the image form along with a text input, then you will have all the info you need to create an record on the image table. So for example, in the index.php image form, you'd do something like this:

<form method="post" action="upload.php" enctype="multipart/form-data">
    <input type="hidden" name="id" value="<?php echo $row->id ?>">
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="text" name="info">
    <input type="submit" value="Upload" name="submit">
</form>

Open in new window

Then in the upload.php script you would have $_POST['id'] and $_POST['info'] so after you've moved the image, you would insert a new record into the database:

 
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $destination)) {
    // The move was successful so let's insert a new Db Record:
    $mysqli = /* create your Db connection here */
    $sqlStr = sprintf("INSERT INTO image_table ('relatedId', 'imageName', 'info') VALUES (%s, '%s' '%s')", $_POST['id'], $file, $_POST['info']);
    $mysqli->query($sqlStr);

    $message = "The file was uploaded sucessfully";
    $uploadValid = true;

Open in new window

For this to work, you would need to make sure your image_table has a column that can hold the ID from the gravsten table (relatedId in my example above). This will act as the foreign key and associate an image with a record from gravsten.

Because you'll be link the image to the gravsten record with a foreign key, you don't need an OK column to find records with an image. You can just use a JOIN query to pull information out of both tables at the same time (but let's address that later!)
Thanks Chris,

We have a little family get-together here today, so I will look into your input tomorrow.
Hi Chris,

Sorry it took so long. Family have to be nursed too :)

Well - just to be sure: Right now I don't have a specific image table - I have a row in the gravsten table I call image_table.
As I read your guidance above, you assume that there is a separate table for images. Is that a correct assumption? And if so, how should it be structured?
Hey Peter. When you say 'row', I'm assuming you mean 'column'. That scenario is fine if you only ever have one image per row in your gravsten table. As soon as you start to need more than one, or you have other image specific information (such as the text info) in that row then it makes sense to separate it out into a new table. This is called database normalisation.

As for the structure, you would need a table that has at least a primary key (auto id), plus a foreign key. Also the fields needed to store your information (image name etc.). The foreign key holds the ID of the related Gravsten record (and should be the same datatype). Assume your gravsten records looks like this:

id: 1
firstName: Chris
lastName: Stanyon

id: 2
firstName: Peter
lastName: Kroman

You would then have an image table that had 3 fields. For example: id, gravstenId, imageName. Your records would then look like:

id: 1
gravstenId: 1
imageName: image1.jpg

id: 2
gravstenId: 1
imageName: image2.jpg

id: 3
gravstenId: 2
imageName: image3.jpg

From that table, you can see that Chris has 2 images and Peter has 1. You can add as many as you like. To retrieve data from the imageTable, you can either run a second query, or you can run a JOIN query - depending on your needs
OK - thanks. I'll try to structure the table, and then i'll get back.
User generated imageHi Chris,

I have made an image-table now, with this structure:
 

I have edited the index file like this:
  <form method="post" action="upload.php" enctype="multipart/form-data">
        <p> Vælg fil der skal uploades:</p>
         <input type="hidden" name="id" value="<?php echo $row->id ?>">
        <input type="file" style= "font-family: arial; font-size: 12px;" name= "fileToUpload" id="fileToUpload">
        <input type="text" placeholder="Evt. kommentar til billedet" name="image_text" style="color: blue; font-weight: bold;">
        <br>
        <br>
        <input type="submit" style= "font-family: arial; font-size: 12px;" value="Upload" name="submit">
        </form>

Open in new window


And I have edited the upload.php file like this:
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $destination)) {
    // The move was successful so let's insert a ned Db record:
    $link = mysqli_connect("db credentials");
    $link->set_charset("utf8");
 
// Check connection
    if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
 
        
        $sqlStr = sprintf("INSERT INTO image_table ('gravsten_id', 'image_name', 'image_text') VALUES (%s, '%s' '%s')", $_POST['id'], $file, $_POST['image_text']);
        $link->query($sqlStr);
        $message = "The file was uploaded sucessfully";
        $uploadValid = true;

Open in new window

When I upload an image it uploads fine to the specified folder, but nothing else seem to happen. Nothing comes into the new image_table anyway.
What am I doing wrong :)
OK Peter. Your table structure and code look fine, so it's time to debug.

Make sure you have error_reporting turned on in your upload.php script, and also check the source of the HTML file to make sure the id is properly inserted into the Upload form before being submitted.

Without error reporting, you won't see any problems.
OK. The I get this error when I click the Upload button:

Notice: Undefined index: id in /var/www/genealogiskforum.dk/public_html/gravsten_pk/gravsten/upload.php on line 8

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /var/www/genealogiskforum.dk/public_html/gravsten_pk/gravsten/upload.php:8) in /var/www/genealogiskforum.dk/public_html/gravsten_pk/gravsten/upload.php on line 11

Warning: Cannot modify header information - headers already sent by (output started at /var/www/genealogiskforum.dk/public_html/gravsten_pk/gravsten/upload.php:8) in /var/www/genealogiskforum.dk/public_html/gravsten_pk/gravsten/upload.php on line 76

Here is the full code:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Prevent direct access to the script
if (!isset($_POST['submit'])) die("Access Denied!");

$id=$_GET['id'];

// Start the session
session_start();

// Assume the file is invalid until proven otherwise
$uploadValid = false;

// Get some info about the potential file upload
$file = $_FILES["fileToUpload"]["name"];
$folder = "./image_uploads/";
$destination = $folder . $file;
$imageInfo = $_FILES["fileToUpload"]["size"] ? getimagesize($_FILES['fileToUpload']['tmp_name']) : false;

// Check if we have a file
if ($_FILES["fileToUpload"]["error"] === 4) {
    $message = "We have no file";
}
// Check if it has a size
elseif ($_FILES["fileToUpload"]["size"] === 0) {
    $message = "The file is empty";
}
// Check if it's an image
elseif ($imageInfo === false || ($imageInfo[2] !== IMAGETYPE_GIF) && ($imageInfo[2] !== IMAGETYPE_JPEG) && ($imageInfo[2] !== IMAGETYPE_PNG)) {
    $message = "The file is not a valid image";
}
// Something else went wrong!
elseif ($_FILES["fileToUpload"]["error"] !== 0) {
    $message = "There was a problem uploading your file";
}
// Check if it already exists
elseif (file_exists($destination)) {
    $message = "The file already exists";
}
// All good - let's try to move the file :)
else {

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $destination)) {
    // The move was successful so let's insert a ned Db record:
    $link = mysqli_connect("db credentials");
    $link->set_charset("utf8");
 
// Check connection
    if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
 
        $sqlStr = sprintf("INSERT INTO image_table ('gravsten_id', 'image_name', 'image_text') VALUES (%s, '%s' '%s')", $_POST['id'], $file, $_POST['image_text']);
        $link->query($sqlStr);
        $message = "The file was uploaded sucessfully";
        $uploadValid = true;

    } else {
        // The move failed
        $message = "There was an error uploading your file";
    }
}

// Let's generate a response
$response = array(
    "success" => $uploadValid,
    "message" => $message
);

// Let's push the response to the SESSION
$_SESSION['response'] = json_encode($response);

// And send the user on his way
header('Location: ' . $_SERVER['HTTP_REFERER']);

?>

Open in new window

OK. Couple of things. We are POSTing to this page, so the GET array is empty, which is why this line causes you an error:

$id=$_GET['id'];

Remove it completely (we get the ID from the POST later on in the code).

The session_start() call needs to be made before any output is sent to the browser. The call to GET caused an error to be output which came before the session_start call, which is why you get the other errors. Simple rule is don't do ANYTHING before the session_start() that could generate output.

The top of your file should look like this:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start the session
session_start();

// Prevent direct access to the script
if (!isset($_POST['submit'])) die("Access Denied!");

// Assume the file is invalid until proven otherwise
$uploadValid = false;

Open in new window

I also suggested you take a look at the generated source of your HTML file in your browser (the upload form) to make sure the ID was being inserted correctly. Did you check that?
Thanks. I'll work with it and get back tomorrow
I have made the corrections you suggest. I get no errors now.
The right id is in the HTML code.
But nothing comes into the image_table
OK. I think it might be the query string that you're running. The column names are wrapped in quotes when they shouldn't be. Also, there's no comma between the last 2 values ('%s' '%s'). It should look like this:

$sqlStr = sprintf("INSERT INTO image_table (gravsten_id, image_name, image_text) VALUES (%s, '%s', '%s')", $_POST['id'], $file, $_POST['image_text']);

Open in new window


In your PHP scripts, you'll want to start adding in some debug information so you can see what's going on. For example, take a look at this edit to your code and try it out. You'll see that I'm echoing out the SQL string so we can check it. I'm also checking to see if the query executed successfully ($result will either be TRUE or FALSE). I'm then dumping all the data rather than doing a redirect at the end. This kind of debugging should become second nature what you're coding.

else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $destination)) {

        // The move was successful so let's insert a new Db record:
        $link = mysqli_connect("db credentials");
 
        // Check connection
        if($link === false){
            die("ERROR: Could not connect. " . mysqli_connect_error());
        }

        $link->set_charset("utf8");
 
        $sqlStr = sprintf("INSERT INTO image_table (gravsten_id, image_name, image_text) VALUES (%s, '%s', '%s')", $_POST['id'], $file, $_POST['image_text']);

        // Let's view the SQL Query
        var_dump($sqlStr);

        $result = $link->query($sqlStr);

        // Did the query run OK
        if ($result) {
            $message = "The file was uploaded sucessfully";
            $uploadValid = true;
        } else {
            $message = sprintf("There was a problem inserting the image into the database (Error: %s)", $link->error);
        }

    } else {
        // The move failed
        $message = "There was an error uploading your file";
    }
}

// Let's generate a response
$response = array(
    "success" => $uploadValid,
    "message" => $message
);

// Let's get some info to help up debug.
var_dump($response);
var_dump($_POST);

// Let's push the response to the SESSION
// $_SESSION['response'] = json_encode($response);

// And send the user on his way
// header('Location: ' . $_SERVER['HTTP_REFERER']);

Open in new window

FYI : after today I'll be away from the computer for a few days !
That helped :)

Now i get this in the image_table:

User generated image
So now we need to display the image and the image text on the page.

Any suggestions are very welcome :)
And just one more little thing.

I would like the messages to succes/fail messages from the insert.php and upload.php scripts to fade out after some seconds.
I have found a script that might do just that, but I am not sure how to use it right. it looks something like this:

   <script>
    $(document).ready(function(){
        $("#message").fadeOut(3000);
    });
    </script>

Open in new window

If you want to display it on the page that contains the forms, then you already have the ID from the GET array, so you would just need to do a query using that.

$sql = "SELECT image_name, image_text FROM image_table WHERE gravsten_id = $id";

if ($result = $link->query($sql)) {
    $image = $result->fetch_object();
    printf("<p>%s</p>", $image->image_text);
    printf("<img src='./image_uploads/%s'>", $image->image_name);
}

Open in new window

For the fading out, just add that script to <head> part of your page. Just make sure the #message part matches the element that you want to fade out. In this example it will fade out an element with an ID of message:

<div id="message">...</div>

If you want to fade out an element with a class of message, then just use the class selector:

$(".message").fadeOut(3000);

<div class="message">...</div>
Thanks. I'll work with the messages,

I am displaying images on the page now, but they are huge in size, no matter if I put the query into a small container.
Can I do anything about that too :)
The query has nothing to do with the image size.

You can do it simply with CSS. Here's the inline version of it:

<img src="..." style="width:250px">
Yes - i know, but how do I put that in, when my code looks something like this:

       <div class="w3-col w3-mobile" style="width:25%; margin-top: 15px; margin-left: 20px">
        <div class="w3-container w3-hide-small">    
         
        <?php
        $sql = "SELECT image_name, image_text FROM image_table WHERE gravsten_id = $id";

        if ($result = $link->query($sql)) {
        $image = $result->fetch_object();
        printf("<p>%s</p>", $image->image_text);
        printf("<img src='./image_uploads/%s'>", $image->image_name);
        }
        ?>
        </div>
        </div>

Open in new window

printf("<img src='./image_uploads/%s' style='width:250px;'>", $image->image_name);
If yuo want it to automatically fill an outer wrapper such as a div, then just change the width to 100%

printf("<img src='./image_uploads/%s' style='width:100%;'>", $image->image_name);

(you may have to escape the % sign with a double %%)
Thanks Chris,

I will now let you in peace for a few days, and then I 'll show you the final result once you are back again.

Thank you very much for all your help. It is going to be a very fine application :)
No worries Peter. Good luck with it :)
Sorry - just one more little thing before I let you loose :)

When I have more that one image attached to one id, I need a loop statement to catch and display them all.
I can't figure out how to write this loop statement.
Hey Peter, Just wrap fetch_object() in a while loop:

<?php
    $sql = "SELECT image_name, image_text FROM image_table WHERE gravsten_id = $id";

    if ($result = $link->query($sql)) {
        while($image = $result->fetch_object()):
            printf("<p>%s</p>", $image->image_text);
            printf("<img src='./image_uploads/%s'>", $image->image_name);
        endwhile;
    }
?>

Open in new window

And it is just working perfectly.

Hurry away :) :)
Excellent :)
Hi Chris,

You can see the application working here: https://genealogiskforum.dk/gravsten_pk/, but you have to log in, so I have set up a userprofile for you. If you have an e-mail adress I can mail the credentials to you.

Anyway, I still have some questions and clarifications I hope that you will help me with.

First about the search-page:

1. When viewing the page in Firefox (Mac and Windows) the charset on that page crashes when hitting the submit button. This happens only in Firefox - I have tested in Chrome (Mac and Windows), and in Safari and IE, and here are no problems.
2. As you will see on the page, I have aded a third button with the value "Se aktive". I would like this button to open a new tab and  present a table with Sogn, Provsti, Stift from the gravsten table and with the image and the image_text form the image_table.

I have a few more things I would like to disquss, but let's take them later.
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Chris,

Of course it is OK. I will start a open a new question to get the last things clarified.
Anyway, it is not the page that crashes, it is the charset it self. In Firefox (only) I get a lot of strange signs in stead of the danish characters . No more here - I'll open a new question a little later today.
Perfect assistance and help form Chris Stanyon