-1

I'm trying to get an input from a user-input box and put it in an SQL database but it returns an error every time.

Here is my code:

<?php

  include_once("./assets/inc/connect.inc.php");

  $myusername = $_SESSION["myusername"];

  if (isset($_POST["post_bar"])) {

    $post_status = $_POST["post_bar"];
    $date = date('m/d/Y h:i:s a', time());
    $loves = "0";

    $post_query = "INSERT INTO `posts` (post, posted_by, posted_at, loves) VALUES ($post_status, $myusername, $date, $loves)";

    $post_query_response = mysql_query($post_query);

    if ($post_query_response) {

      echo "<script>alert('Posted!');</script>";

    }
    else {
      echo "<script>alert('Error, not posted.');</script>";
    }

    }

?>
<div class="post">
   <p id="postfeed"></p>
</div>
<div class="share-box">
   <div class="shareboxextender" >
      <form method="POST" action="" name="post_bar" >
        <input type="input" name="post_bar" placeholder="Share..." class="sharebox" autocomplete="off" />
      </form>
   </div>
</div>

I would really appreciate some help with this! Thank you.

  • 2
    what might that error be that it's returning every time. Usually errors state what the problem was to help you correct them. – iam-decoder Nov 12 '15 at 17:55
  • can you state the error that you are getting ? – amanpurohit Nov 12 '15 at 17:58
  • And you should probably not write code like that - because of SQL Injection that is potentially unsafe. (Though some db offer some kind of protection) look into prepared statements. And like others mentioned we need to see the error :) – Dylan Meeus Nov 12 '15 at 17:58
  • 1
    it easy asnwar `VALUES ($post_status, $myusername, $date, $loves)"` should be `VALUES ('$post_status', '$myusername', '$date', '$loves')"` no matter if is it string mysql will try to convert, if can't will output a error. – Laurentiu Nov 12 '15 at 18:02
  • Instead of just `echo "";` try `echo "";` oh and by the way the mysql PHP extension is deprecated, consider switching to mysqli. – Doug McLean Nov 12 '15 at 18:02
  • Oh yeah very good point @Laurentiu - values not quoted - why did I not see that :) which also, I think, highlights Dylan Meeus' comment about SQL injection. One quotation mark in the data will cause it to fail (or worse!) – Doug McLean Nov 12 '15 at 18:05

2 Answers2

1

please check:

$post_query = "INSERT INTO `posts` (post, posted_by, posted_at, loves) VALUES ('$post_status', '$myusername', '$date', '$loves')";

You're inserting text not numbers.

Grzegorz
  • 121
  • 5
1

The problem is quoted, you shopuld use VALUES ('$post_status', '$myusername', '$date', '$loves'), but here you can have a problem with sql injection and my sugestion is to use PDO.

Laurentiu
  • 574
  • 6
  • 26