user4106283
user4106283

Reputation: 1

Can't write variables to SQL database

I've attempted to make a simple PHP system that takes the user's login name, recipients name and message contents and write it to an SQL database. I'm at the point where there are no errors at all, even after I send a message and the page refreshes. However no new entries appear in my SQL database (checking through phpMyAdmin). By the way all of this code is on the same page.

Starts off with a HTML form to gather data:

<form name="login" action="" method="POST">
<p>Recipient: <input type="text" name="recipient"/></p>
<p>Message: <input type="text" name="contents"/></p>
<input type="Submit" Name="submit" value="Send"/>
</form>

Then I setup the connection to the SQL database:

<?php
$link = mysqli_connect('host','username','password','database');
$sqlaction = 'INSERT INTO $userinbox (Sender, Message) VALUES ($email, $username)';
?>

Then the function that enters the information into the database:

<?php

session_start();

function message($link, $sqlaction)
{
$sender = $_SESSION['name'];
$recipient = strtolower($_POST['recipient']);
$contents = $_POST['contents'];

switch ($recipient) {
    case 'person1':
        $userinbox = 'person1';
        $result = mysqli_query($link, $sqlaction);
        echo 'Message sent.';
        break;
    case 'person2':
        $userinbox = 'person2';
        $result = mysqli_query($link, $sqlaction);
        echo 'Message sent.';
        break;
    case 'person3':
        $userinbox = 'person3';
        $result = mysqli_query($link, $sqlaction);
        echo 'Message sent.';
        break;
    case 'person4':
        $userinbox = 'person4';
        $result = mysqli_query($link, $sqlaction);
        echo 'Message sent.';
        break;
    default:
        echo 'Current valid users are list of users';
}
}

And lastly, I call the function, passing the database connection variables:

message($link, $sqlaction);

But like I said, nothing appears in the database. I've spent 4 days trying to debug this and am on the verge of giving up. Any help would be greatly appreciated.

Upvotes: 0

Views: 54

Answers (2)

ehwas
ehwas

Reputation: 248

You don't have

$email and $username

defined in this code. If you enable error reporing

error_reporing(E_ALL);

you will receive something like

Notice: undefined variable $email on line xxx in file.php
Notice: undefined variable $username on line xxx in file.php

Also the things @devaldcool said

Upvotes: 0

Deval Khandelwal
Deval Khandelwal

Reputation: 3548

You must use quotes for inserting strings like "$email" and not just $email. You must also escape table names with backticks i.e. this-> ` Your sql query will thus be :-

$sqlaction = "INSERT INTO `$userinbox` (Sender, Message) VALUES ('$email','$username')";

Note that for numbers (integers,double values,decimals etc) quotes are optional. Please see that you accept an answer if it helps you.

Upvotes: 1

Related Questions