Question

I'm making a website that has a blog on it (project.intrepidem.net). I have it working so that when I make a new post in the phpmyadmin panel, it generates the HTML and puts the new blog post on the page, just like I want it. The problem is that I made an admin panel with a new post form, and I want to be able to fill out the form and automatically have the post be added to the database, and it won't update.

The form for the panel:

<h1>Create a new Post</h1>
<form action="new_script.php" method="post">
     <input type="text" name="title" placeholder="Post Title"/>
     <select name="authorId">
       <option value="1">First Name</option>
       <option value="2">Second Name</option>
       <option value="3">Third Name</option>
     </select>    
     <textarea name="post" placeholder="Write your post."></textarea>
     <input type="submit" value="post"/>        
</form>

Here's the new_script.php page:

<?php
$title = $_POST['title'];
$post = $_POST['post'];
$authorId = $_POST['authorId'];

//connect to database
$connect = mysqli_connect('localhost','username', 'password', 'database');

//SQL query
$query = "INSERT INTO `blog_posts`(`title`, `post`, `author_id`) VALUES ([$title],[$post],[$authorId])";

//run the query
$run = mysqli_query($connect, $query);

    //testing to see if values came from HTML page
    echo $title;
    echo $post;
    echo $authorId;

    echo "<br/><a href='../index.php' title='Go Home'><--Go Home</a>";

?>

The database name, username, and password in the $connect are all correct. I know the values from the form are coming through, because I print them out there at the bottom, and it shows the correct values when I try to update the form. For some reason, the post won't save to the database, which means it won't update the page.

Thanks. I am just learning PHP, so it could definitely be a dumb mistake that I just can't see. Let me know if you need more information.

Was it helpful?

Solution

Your variables have to be in quotes, not [], change:

$query = "INSERT INTO `blog_posts`(`title`, `post`, `author_id`) VALUES ([$title],[$post],[$authorId])";

into

$query = "INSERT INTO `blog_posts`(`title`, `post`, `author_id`) VALUES ('$title','$post','$authorId')";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top