0

okay i have this first form which is used to get the input text and supposed to send them to sql table

<form action="" method="post">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3 col-sm-offset-3">
<input type="text" placeholder="ask your question!"  class="assin assin-success assin-autosize" name="post_question">
<input type="submit">
</div>
</form>

and then i have this php below it

<?php
$connect = mysqli_connect("localhost","root","","dbname");
mysqli_query($connect,"INSERT INTO `as_questions`(`Qid`, `M_class`, `S_class`, `Question`, `Answer`, `Doctor`, `Time`) VALUES
('n','n','n','$_POST[post_question]','a','d',CURRENT_TIMESTAMP)");?>

it works once i enter a question and submit, but when i first load the page, the php query seems to run and give : Undefined index: post_question, because on load it is empty? and the query runs. how do i fix this?

1
  • Check that the form was submitted. See empty or isset. Also you are open to SQL injections. Commented Jan 30, 2016 at 18:53

1 Answer 1

1

Use isset OR !empty.

if(isset($_POST['post_question'])){
   $connect = mysqli_connect("localhost","root","","dbname");
   mysqli_query($connect,"INSERT INTO `as_questions`(`Qid`, `M_class`, `S_class`, `Question`, `Answer`, `Doctor`, `Time`) VALUES
   ('n','n','n','$_POST[post_question]','a','d',CURRENT_TIMESTAMP)");
}

Hope it will help you :)

Sign up to request clarification or add additional context in comments.

2 Comments

thanks :) how do i prevent double entry into database when i reload?
You need to write a SELECT query just before insert and check if record is exist then you do not need to reinsert it. Let me know if you will face any problem to doing that. All the best :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.