I have two tables:
if a user named TINA(id 3) logs in and posts a question, her question should be saved in the table QUESTIONS with her respective id i.e 3. How can this be achieved?
<div id="content">
</br>
<form action="" method="post">
<center> <h3> <font color="green"> Ask a new question:
<select name="type" required>
<option value="" disabled selected> Select the type of question </option>
<option value="technical"> Technical </option>
<option value="entertainment"> Entertainment </option>
<option value="fashion"> Fashion </option>
<option value="food"> Food </option>
<option value="education"> Education </option>
<option value="lifestyle"> Lifestyle </option>
<option value="relationships"> Relationships </option>
<option value="health"> Health </option>
<option value="random"> Random </option>
</select>
</font> </h3>
<textarea rows="3" cols="100" style="resize:none" placeholder="Please type your question here..." name="ques" required></textarea><br>
<input type="submit" value="POST" name="POST" align="middle">
</center>
</form>
<?php
if(isset($_POST['POST']))
{
$type=$_POST['type'];
$ques=$_POST['ques'];
$date = strftime("%B %d, %Y");
$time = strftime("%r");
$sql="INSERT INTO questions (type,question,date,time) VALUES ('$type', '$ques', '$date', '$time')";
$query = mysqli_query($conn, $sql);
if(isset($_SESSION['id']))
{
echo "<div class='boxtype'>";
echo strtoupper($type);
echo "</div>";
echo "<div class='boxtime'>";
echo '['.$date.']'.' '.'['.$time.']';
echo "</div>";
echo "<div class='box'>";
echo "<font color='red'>".'<b>'.'<i>'.'<u>';
echo strtoupper($_SESSION['user']);
echo '</u>'.'</i>'.'</b>'.'</font>';
echo ':'.' '.$ques;
echo "</div>";
}
}
</div>
First modify your table
QUESTIONS
. Create a field
user_id
to store the id
of user
who post question.
When a user say Tina logs in create a session
during login and store her id
in a session
variable
like SESSION['user_id'] = your_log_in_user_id
. Now just insert this into QUESTION Table like
$user_id = SESSION['user_id'];
$sql="INSERT INTO questions (type,question,date,time,user_id) VALUES ('$type', '$ques', '$date', '$time','$user_id')";
$query = mysqli_query($conn, $sql);
I'ts very easy one using php session.When the user login into the questions section just save the user id in session.The id is USER table id that is primary key.
$_SESSION['ID']=$id;
The question is saved into the table based on session id.Just create the column as user_id in the question table.
$user_id=$_SESSION['ID'];
$sql="INSERT INTO questions (user_id,type,question,date,time) VALUES ('$user_id','$type', '$ques', '$date', '$time')";