简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM