Mohamed Athif
Mohamed Athif

Reputation: 5

php sql form submit on same page, but sql loads too early to give error

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?

Upvotes: 0

Views: 39

Answers (1)

Ravi Hirani
Ravi Hirani

Reputation: 6539

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 :)

Upvotes: 1

Related Questions