tanisha s tanisha s - 7 months ago 31
PHP Question

add data into a table w.r.t user id of another table

I have two tables:

  1. USERS (id primary-key auto-increment, username,email_id, password)

  2. QUESTIONS (id primary-key auto-increment , type, question, date, time)

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">
<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>
</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">

$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);

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>";



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