0

I have a problem with my code. I have coded a guestbook, which works in itself. I would like to display subject, message and the username that captured the message. The guestbook gets its name from SQL, which is inserted into the database by the login script.

I would like now that if a guest writes a contribution on my side, which is not logged in, as name: "Anonym" in the guest book appears. But now I have the problem that my code does not allow anonymous guestbook entries. If I click on "Send message!", the message is added to the database, but the entry does not appear in the guestbook. With registered users it works smoothly. Does anyone have an idea? Enclosed you can find my code from login + guestbook:

Login:

`<form action="" method="post">
  Dein Benutzername:<br>
  <input type="text" name="benutzername" placeholder="Benutzername"><br>
  Dein Passwort:<br>
  <input type="password" name="passwort" placeholder="Passwort"><br>
  <input type="submit" name="absenden" value="Absenden"><br>
</form>
<?php
  include ('dbconnection.php');
  if(isset($_POST['absenden'])):
    $benutzername = strtolower($_POST['benutzername']);
    $passwort = $_POST['passwort'];
    $passwort = md5($passwort);
    $search_user = $db->prepare("SELECT userid FROM users WHERE benutzername = ? AND passwort = ?");
    $search_user->bind_param('ss',$benutzername,$passwort);
    $search_user->execute();
    $search_result = $search_user->get_result();
  if($search_result->num_rows == 1):
    $search_object = $search_result->fetch_object();
    $_SESSION['user'] = $search_object->userid;
    header('Location: '.$_SERVER['PHP_SELF']);
  else:
    $_SESSION['user'] = NULL;                  
    echo 'Deine Angaben sind leider nicht korrekt!';
  endif;
endif; 
?>`

Guestbook:

`<!DOCTYPE HTML>                                                                                          
<html lang="de">                                               
    <head>
        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>
    <?php
        session_start();
        include ('dbconnection.php');
        include 'checklogin.php';
        include 'head_nav.html';
        include 'kontakt.html';
    ?>
        <form action="" method="post">
            <input type="text" name="betreff" placeholder="Betreff?"><br>
            <textarea name="nachricht" placeholder="Ihre Nachricht!"></textarea><br>
            <input type="submit" name="submit" value="Absenden!"><br>
        </form>
    <?php
            if(isset($_POST['submit'])):
                $betreff = $_POST['betreff'];
                $nachricht = $_POST['nachricht'];
                $userid = $_SESSION['user'];                
                $StrSQL = "INSERT INTO kontakt (userid_fk,betreff,nachricht,datum)
                VALUES (?,?,?,NOW())";                                                
                $absenden = $db->prepare($StrSQL);                       
                $absenden->bind_param('iss', $userid, $betreff, $nachricht);
                $absenden->execute();
            endif;
            $StrSQL2 = "SELECT users.benutzername as bn,
            kontakt.betreff, kontakt.nachricht
            FROM users INNER JOIN kontakt
            ON users.userid = kontakt.userid_fk ORDER BY datum DESC";             
            $abfrage = $db->query($StrSQL2);                   
            echo  'Es wurden '.$abfrage->num_rows.' Nachrichten gefunden!<br>';
            while($ausgabe = $abfrage->fetch_object()){
                echo '
                <b>Datum:</b> '.$ausgabe->datum.' <br>
                <b>Betreff:</b> '.$ausgabe->betreff.' <br>
                <b>Nachricht:</b><br> '.$ausgabe->nachricht.' <br>
                <b>Benutzer:</b><br> '.$ausgabe->bn.'<br><hr>'; 
            }
            include 'footer.html';
    ?>            
    </body>
</html>`

UI:

`<?php
    session_start();
    include ('dbconnection.php');
    $search_user = $db->prepare("SELECT * FROM users WHERE userid = ?");
    $search_user->bind_param('i',$_SESSION['user']);
    $search_user->execute();
    $search_result = $search_user->get_result();
    if($search_result->num_rows == 1):
        $search_object = $search_result->fetch_object();
    if(isset($_POST['abmelden'])):
        session_destroy();
        header('Location: '.$_SERVER['PHP_SELF']); 
    endif;
    echo 'Willkommen, '.$search_object->benutzername.'!<br>';
    echo '<form action="" method="post"><input type="submit" name="abmelden" value="Abmelden"></form>';
    endif;
?>`

checklogin:

`<?php
  $page = strtolower($_GET['page']);
  if(isset($_SESSION['user'])):
    require_once('ui.php');
  else:
    if($page == 'anmelden'):
      echo 'Doch <a href="index.php?page=registrieren">registrieren</a>?';
      require_once('anmelden.php');
    elseif($page == 'registrieren'):
      echo 'Doch <a href="index.php?page=anmelden">anmelden</a>?';
      require_once('registrieren.php');
    else:
      echo 'Hey! Willst du dich <a href="index.php?page=anmelden">anmelden</a> oder <a href="index.php?page=registrieren">registrieren</a>?';
    endif;
  endif; 
?>`

I know it could be better programmed, but I lack experience and I am in the learning process.

As I said, it is my goal that with this code an unregistered user can create an entry in the guestbook with the name "anonymous".

General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • *he message is added to the database, but the entry does not appear in the guestbook* -- sorry, how did you show the data on the guestbook? – Bagus Tesa Jan 31 '19 at 01:08
  • ahh, that part, sorry i was lost. perhaps the reason was this part of your query `FROM users INNER JOIN kontakt`, i'm not exactly understand your table structure but i guess the anonymous user dont have an entry on the `users` table (which they shouldn't, so its correct already, perhaps) and [`INNER JOIN` only returns result that exists on both table that being joined](https://stackoverflow.com/q/13997365/4648586). i believe you can try to use `RIGHT JOIN` instead. hope it helps. – Bagus Tesa Jan 31 '19 at 01:14

1 Answers1

0
  $StrSQL2 = "SELECT users.benutzername as bn,
  kontakt.betreff, kontakt.nachricht
  FROM users INNER JOIN kontakt
  ON users.userid = kontakt.userid_fk ORDER BY datum DESC";             
  $abfrage = $db->query($StrSQL2);                   
  echo  'Es wurden '.$abfrage->num_rows.' Nachrichten gefunden!<br>';
  while($ausgabe = $abfrage->fetch_object()){
      echo '
      <b>Datum:</b> '.$ausgabe->datum.' <br>
      <b>Betreff:</b> '.$ausgabe->betreff.' <br>
      <b>Nachricht:</b><br> '.$ausgabe->nachricht.' <br>
      <b>Benutzer:</b><br> '.$ausgabe->bn.'<br><hr>'; 
  }

The code that prints the guestbook entries above uses an INNER JOIN. INNER JOIN will only return results that exists on the two table being JOIN-ed which in this case would be users and kontakt. You should use RIGHT JOIN to allow the kontakt retrieved even though it do not have users.

  $StrSQL2 = "SELECT users.benutzername as bn,
  kontakt.betreff, kontakt.nachricht
  FROM users RIGHT JOIN kontakt
  ON users.userid = kontakt.userid_fk ORDER BY datum DESC";

The next problem would be your Benutzer field empty as it originates from the users.benutzername as bn the user table. You could modify the code a little bit to show "Anonymous" if the particular value is null. Something like is_null might worth to try. Your code will be looked like:

  while($ausgabe = $abfrage->fetch_object()){
      echo '
      <b>Datum:</b> '.$ausgabe->datum.' <br>
      <b>Betreff:</b> '.$ausgabe->betreff.' <br>
      <b>Nachricht:</b><br> '.$ausgabe->nachricht.' <br>
      <b>Benutzer:</b><br> '. !is_null($ausgabe->bn) ? $ausgabe->bn : 'Anonymous' .'<br><hr>'; 
  }

The code above uses ternary operator, the ? : pair.

Sorry, i was late to decide to write a proper answer for the question.

Bagus Tesa
  • 1,317
  • 2
  • 19
  • 42
  • @Sha, it still appear concatenated like that? hmm, weird. could you share your current code? sorry i was late to read your comment.. – Bagus Tesa Feb 02 '19 at 01:48