Can't Insert data into database

I am having trouble writing a query to insert data. I am able to select data and put it in a table, but my insert query just won’t work.
I’m attaching my code here. If someone can help me figure out what is wrong I would appreciate it.


addstaff.txt (1.63 KB)

It would be more helpful if you post the code rather than attach it.

Ok here is the code. Thanks for replying.

[php]

Staff Info

Insert Staff Info

Staff Information
First Name:
Last Name:
Email:
Phone:
<?php
$connect=mysqli_connect ("localhost","root","");

if (!$connect) {
	echo "Not Connected to Server";
}

if(!mysqli_select_db($connect,"osticket")){
	echo "No db Found";
}

if(isset($_POST['submit'])){
	$firstname=$_POST["firstname"];
	$lastname=$_POST["lastname"];
	$email=$_POST["email"];
	$phone=$_POST["phone"];
	
	$insert = "INSERT INTO ost_staff(firstname, lastname, email, phone) VALUES ('$firstname','$lastname','$email','$phone')";
	if(!mysqli_query($connect,$insert)){
		echo "Records Not Inserted.";

  } else{

        echo "Inserted Successfully";

  }
}

?>[/php]

Go to the link in my signature. The code you have isn’t uhh, worthwhile and is a security risk.

You shouldn’t have user supplied values just dropped into a query.
The PHP should process at the top of the page, if it is on the same page.
Your html elements are wrong.
You are using tables for layout.
There is no doctype in the header.
You are using dated element tags.

To name a few…

Sorry, it sucks I know. I am as fresh as it gets with this stuff. I am just doing this one time project and I need a simple code to insert data into my database. I got most of this code from a video tutorial and it seemed like it should work. My SELECT * query worked to display the data in a table. I had hoped that this one would work as well to insert new data. Sorry to have wasted your time. I’ll keep plugging away at it. Thank you for responding though.

While it’s a contact form I have a repository that might help you get going:

Here’s the link to it: https://github.com/Strider64/html-contact-form

Here’s the HTML and the PHP (Most of it is at the top of the page).

[php]<?php
require_once DIR . ‘/vendor/autoload.php’;
require_once DIR . ‘/connect/connect.php’;
$message = NULL;
$submit = filter_input(INPUT_POST, ‘submit’, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if (isset($submit) && $submit === ‘submit’) {
$name = filter_input(INPUT_POST, ‘name’, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$email = filter_input(INPUT_POST, ‘email’, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$phone = filter_input(INPUT_POST, ‘phone’, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$website = filter_input(INPUT_POST, ‘website’, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$subject = filter_input(INPUT_POST, ‘reason’, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$comments = filter_input(INPUT_POST, ‘comments’, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$mail = new PHPMailer();
$mail->Host = EMAIL_HOST; // You’re email host (I’m using a constant using the define() function):
if (filter_input(INPUT_SERVER, ‘SERVER_NAME’, FILTER_SANITIZE_URL) == “localhost”) {
$mail->isSmtp(); // Local Host:
$mail->Port = EMAIL_PORT; // Local Host Port: (Usually 587)
} else {
$mail->isSendMail(); // Remote Host:
}
$mail->SMTPAuth = true;
$mail->Username = EMAIL_ADDRESS; // SMTP username:
$mail->Password = EMAIL_PASSWORD; // SMTP password:
$mail->SMTPSecure = ‘tls’; // Enable encryption, ‘ssl’ also accepted:
$mail->From = $email;
$mail->FromName = $name;
$mail->addAddress(‘[email protected]’);
$mail->Subject = $subject;
$mail->Body = ‘

’ . $comments . ‘

’ . $phone . ‘

’;
$mail->isHTML(true);
if (!$mail->send()) {
echo 'Mailer Error: ’ . $mail->ErrorInfo;
exit;
} else {
$message = ‘Data Successfully Sent!’;
}
}
?> Contact Form Version 1.0

PHP Contact Form

'
        <fieldset>

            <legend><?php echo (isset($message)) ? $message : 'Contact Details'; ?></legend>

            <label for="name" accesskey="U">Your Name</label>
            <input name="name" type="text" id="name" placeholder="Enter your name" required="required" />

            <label for="email" accesskey="E">Email</label>
            <input name="email" type="email" id="email" placeholder="Enter your Email Address"  required="required" />

            <label for="phone" accesskey="P">Phone <small>(optional)</small></label>
            <input name="phone" type="tel" id="phone" size="30" placeholder="Enter your phone number" />

            <label for="website" accesskey="W">Website <small>(optional)</small></label>
            <input name="website" type="text" id="website" placeholder="Enter your website address" />

        </fieldset>

        <fieldset>

            <legend>Your Comments</legend>

            <div class="radioBlock">
                <input type="radio" id="radio1" name="reason" value="support" checked>
                <label class="radioStyle" for="radio1">support</label>
                <input type="radio" id="radio2" name="reason" value="advertise">
                <label class="radioStyle" for="radio2">advertise</label>  
                <input type="radio" id="radio3" name="reason" value="error">
                <label class="radioStyle" for="radio3">Report a Bug</label>    
            </div>

            <label class="textBox" for="comments">Comments</label>
            <textarea name="comments" id="comments" placeholder="Enter your comments" spellcheck="true" required="required"></textarea>             

        </fieldset>

        <input type="submit" name="submit" value="submit">

    </form>
</body>
[/php]

Here’s another repository that is more inline in what you are doing, but the html get’s muddle a little more:
https://github.com/Strider64/php-registration-tutorial

[php]<?php
/*

  • Turn on error reporting, set the default timezone, start sessions and create a constant PDO database
  • connection to the database in config.php under the directory includes in the the assests folder.
    /
    require_once ‘assests/includes/config.php’;
    /
  • Create a bunch of helper functions since we are creating the registration and input the procedural way,
  • if we had been doing the Object-Oriented Programming way we would had created an classes and a class
  • autoloader.
    /
    require_once ‘assests/functions/functions.inc.php’;
    /
  • Create an users table if one doesn’t already exists, once it exists you can comment out the call to the createTabase
  • function. Though it really doesn’t hurt leaving it in there.
    */
    createTables(); // You can comment this out when this is run at least once:

$data = []; // An array that we setup as $data:
$error = [];
/*

  • When user click on the submit button we grab the hidden input variable and the
  • reason we do that instead of the regular submit button is to ensure that we get the click.
  • For some older I.E. browsers don’t register the click on the submit button (or so I am told).
    */
    $submit = filter_input(INPUT_POST, ‘action’, FILTER_SANITIZE_FULL_SPECIAL_CHARS); // using htmlspecialchars sanitizes the variable:

if ($submit && $submit === ‘submit’) {
/*
* Grab all the user’s input responses and store them it the array called $data. We
* will shorting be validating all the input fields and then storing the values in a database table if everything
* passes validation.
*/
$data[‘username’] = htmlspecialchars($_POST[‘username’]);
$data[‘password’] = htmlspecialchars($_POST[‘password’]);
$data[‘password_verify’] = htmlspecialchars($_POST[‘verify’]);
$data[‘email’] = htmlspecialchars($_POST[‘email’]);
$data[‘email_verify’] = htmlspecialchars($_POST[‘verifyEmail’]);

/*
 * Validate user's input from registration form. Check to see if all fields have been entered, password is 
 * valid, email is valid, verify that both password and email address has been entered correct and make sure there
 * are no dupicate accounts being entered. 
 */
$error['empty'] = checkContent($data);
$error['password'] = checkPassword($data['password']);
$error['email'] = checkEmail($data['email']);
$error['passwordMatch'] = passwordMatch($data['password'], $data['password_verify']);
$error['emailMatch'] = emailMatch($data['email'], $data['email_verify']);
$error['account'] = accountStatus($data['email'], $pdo);

/*
 * Check to see if everything passes, if so save user's acount to database table users. Otherwise inform
 * user there was an error(s) when registering and please try again. 
 */
$result = validate($error);
if (!is_array($result)) {
    $info = saveRegistration($data, $pdo);
    unset($data);
} else {
    //echo "<pre>" . print_r($error, 1) . "</pre>\n";
}

}
?>

PHP Registration Tutorial
Registration Form username: password: verify password: email address: verify email:
<?php if (isset($info)) { ?>

Successfully Registered!

You have successfully registered with Registration Tutorial. If you want to you can login to the Demo Page at login?

<?php } else { ?>

Registration Tutorial

  1. >All input fields must be entered.
  2. >Password must contain at least 8 characters, have at least one uppercase, one lowercase and one numeric character.
  3. >Password and Verify Password must match.
  4. >Email Address must be valid.
  5. >Email Address and Verify Address must match.
  6. <?php echo (isset($result) && !$result['account']) ? '
  7. You already have an account registered with us!
  8. ' : NULL; ?>
<?php } ?>
[/php]

The top one is better for you when it comes to the HTML/CSS portion which I recommend anyone learning PHP to get a good grasp of HTML/CSS first. The second one is just as good, but you’ll have to dig a little to decipher the HTML and PHP a little more. Though taking a second look at it, the second repository doesn’t look all that bad. I know both of them work for I have tested them out on my local server (and remote server) though there might be a few quirks in them for the ARE NOT FULLY TESTED.

Sponsor our Newsletter | Privacy Policy | Terms of Service