Calling from multiple tables and inserting into one table - php

I am created a small quiz with some functionality and i've ran into a hiccup. I am trying to write into a answers table with information gathered from 2 different tables.
My Question would be is there a way to insert UserId, QuestionId and the answer from the code i have below or can anyone help me with the code I have made.
Sorry if im abit of a noob. Code Below !
So far retrieve username from session
<?php
session_start();
//check if the user is already logged in.
if (!isset($_SESSION['username'])) {
header('Location: index.php');
}
?>
Then retrieve the QuestionId and userId and submit a answer
<section id="content" class="content">
<form action="testingq.php" method="post">
<p>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT QuestionId, QuestionText, InputTypeId FROM question";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> QuestionId: ". $row["QuestionId"]. " - : ". $row["QuestionText"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<?php
$host="localhost"; // Host name
$user="root"; // Mysql username
$pass="root"; // Mysql password
$db_name="mydb"; // Database name
// Connect to server and select databse.
$con = mysqli_connect($host, $user, $pass, $db_name);
$sql = "SELECT UserId FROM user WHERE username='$username'";
$result = mysqli_query($con, $sql);
?>
<input type="Radio" name="Answer" value="1" checked/>Yes</p>
<input type="Radio" name="Answer" value="0"/>No</p>
<p><input type="submit" value="Send it!"></p>
</form>
</section>
testingq.php
<!DOCTYPE html>
<html>
<body>
<?php
$host="localhost"; // Host name
$user="root"; // Mysql username
$pass="root"; // Mysql password
$db_name="mydb"; // Database name
// Connect to server and select databse.
$con = mysqli_connect($host, $user, $pass, $db_name);
$sql = "INSERT into answers (QuestionId, UserId, Answer) VALUES(
'$_POST[QuestionId]',
'$_POST[UserId]',
'$_POST[Answer]')";
$result = mysqli_query($con, $sql);
?>
</body>
</html>

Related

Program is not inserting into the database

My program doesn't insert into the database, tried various means, I'm new to php and tried to test myself with this but I'm finding it difficult to get. i think the problem is at the connection to the database but I'm not getting it
<!DOCTYPE html>
<html>
<head>
<title>LIST</title>
</head>
<body>
<h1> TODO LIST </h1>
<?php
if(isset($_POST["submit"])){
$servername = "localhost";
$username = "root";
$password = "";
try {
//create a database conneection
$conn = mysqli_connect("localhost", "root", "");
if(!$conn){
die("Database connection failed: ". mysql_error());
}
$sql = "INSERT INTO tasks (task, date, time) VALUES (:task, :date, :time)";
$query = $conn->prepare($sql);
$query->execute(array(':task'=>$task,
':date'=>$date,':time'=>$time));
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
?>
<form action = "todolist.php" method = "post">
Task: <input type="text" name="task" id="task"><br/>
Date: <input type="date" name="date" id="date"><br/>
Time: <input type="time" name="time" id="time"><br/>
<input type = "submit" value = "submit" name="submit">
</form>
</body>
</html>
You are not select any database.
Try something like this.
$conn = mysqli_connect("localhost", "root", "", "Yourdatabasename");
Are you connected to your database? You do not select any bdd and the logs are the right ones?
Maybe try:
$conn = mysqli_connect("localhost", "root", "", "databasename");
At first, see if you are connected to your database
I am using this way in one of my project. Create a connect.php file and create connection like this:
<?php
$conn = mysqli_connect("localhost", "root", "", "Yourdatabasename");
?>
Now in index.php file check if the submit button is pressed:
<?php
if(isset($_POST["submit"]))
{
// include connection file
include("connect.php");
// get values
$subject = mysqli_real_escape_string($con, $_POST["subject"]);
$comment = mysqli_real_escape_string($con, $_POST["comment"]);
// Insert in database
$query = "INSERT INTO comments(comment_subject, comment_text)VALUES ('$subject', '$comment')";
mysqli_query($con, $query);
}
?>

MySQL db isn't populating

I am trying to create a register/login html/php script. I created a database and I believe my html/php code is correct. I was wondering if I am missing something small. Here is my code so far.
Here is the database
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
if(isset($_POST["submit"]))
{
$User = "**";
$Password = "**";
$Database = "member";
$Host = "localhost";
$con = mysqli_connect($Host, $User, $Password);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,$Database);
$myusername = $_POST["username"];
$mypassword = $_POST["password"];
$sql = "INSERT INTO member (username, password) VALUES ('$myusername','$mypassword')";
mysqli_query($con,$sql);
mysqli_commit($con);
mysqli_close($con);
echo "Thank You! Information entered.";
}
else
{
?>
<form method="post" action="proInput.php">
Username:<input type="Text" name="username"><br>
Password:<input type="Text" name="password"><br>
<input type="Submit" name="submit" value="Register"></form>
<?
}
?>
Every time I type SELECT * FROM member; in MySQL my database is empty.
mysqli_commit($con);
mysqli_query($con,$sql);
mysqli_close($con);
You're committing before you insert, and then closing an uncommitted transaction. Try swapping the first two lines in the above excerpt.
As you answered already in your comment,
the name of the file isn't main_login.php but proinput.php
Your form is posting it's data to main_login.php and I'm assuming you don't have the insert query on that page, your code isn't run at all.
Options:
Try changing the name of this php file to main_login.php and then instead of the echo redirect the user to the login page
Move this part of the insert to your main_login.php
if(isset($_POST["submit"]))
{
$User = "";
$Password = "";
$Database = "member";
$Host = "localhost";
$con = mysqli_connect($Host, $User, $Password);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,$Database);
$myusername = $_POST["username"];
$mypassword = $_POST["password"];
$sql = "INSERT INTO member (username, password) VALUES ('$myusername','$mypassword')";
mysqli_query($con,$sql);
mysqli_commit($con);
mysqli_close($con);
echo "Thank You! Information entered.";
}
else
{
?>
for debugging add the following to the very top of your php file right after the opening of php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
This worked for me
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
if(isset($_POST["submit"]))
{
$User = "db_user";
$Password = "db_password";
$Database = "db_name";
$Host = "db_host";
$con = mysqli_connect($Host, $User, $Password);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,$Database);
$myusername = $_POST["username"];
$mypassword = $_POST["password"];
$sql = "INSERT INTO member (username, password) VALUES ('$myusername','$mypassword')";
mysqli_query($con,$sql);
mysqli_commit($con);
mysqli_close($con);
echo "Thank You! Information entered.";
}
else
{
?>
<form method="post" action="proinput.php">
Username:<input type="Text" name="username"><br>
Password:<input type="Text" name="password"><br>
<input type="Submit" name="submit" value="Register"></form>
<?php
}
?>
please add 'or die (mysqli_error())' at the end of your query and get the sql error report. That should tell you what is exactly wrong with sql . Php error reporting will only give php errors.

Returning results from database

I am trying to do a simple SELECT to return rows of data from my database. I have a valid connection from my database so I know the issue is not there. I have ensured the names of each column are correct but it just returns 0 results.
My table inside the db is called 'user' and here is the members.php file:
<?php include 'header.php'; ?> <- this is where the db conect file is pulled in.
<?php
$sql = "SELECT id, username, email_address FROM user";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
$row["id"];
}
} else {
echo "0 Members";
}
$conn->close();
?>
Just for ref here is my DB connection (Not the most secure i am just testing):
<?php
$servername = "localhost";
$username = "***********";
$password = "**********";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br><br>";
?>
you didnt select your database
$conn=new mysqli($servername, $username, $password);
this require another parameter which is your d.b name
$conn=new mysqli($servername, $username, $password,$db_name);

Inputted values not saved while inserting data from html form into sql database (html,php,sql)

The problem: insert.php connects fine, but only inserts empty values ('') when I hit 'save' on the html form. The text I type, which I'm trying to insert, isn't saved. Somewhere a connection isn't being made and that data is lost but I can't figure out exactly where. Any help?
HTML insert form (collecting data for 2 parameters, 'user' and 'thread')
<form action="insert.php" method="post">
user: <input type="text" name="user"><br>
thread: <input type="text" name="thread"><br>
<input type="submit" value="Save">
</form>
PHP code to connect to SQL, insert inputted values
<?php
$user = $_POST['user'];
$thread = $_POST['thread'];
$servername = "##.##.###";
$username = "harwoodjp";
$password = "~";
$dbname = "332";
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("SQL (&#9746)<br/> " . $conn->connect_error);
}
echo "SQL (&#9745) <br/>";
$sql = mysql_connect($servername,$username,$password);
mysql_connect($servername,$username,$password);
mysql_select_db("332project");
//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);
echo "<script>window.location='select.php'</script>"; //select.php displays the full table
//close MySQL
mysql_close($sql);
?>
try this
<?php
$user = $_POST['user'];
$thread = $_POST['thread'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
//create connection
$conn = mysql($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("SQL (&#9746)<br/> " . $conn->connect_error);
}
echo "SQL (&#9745) <br/>";
$sql = mysql_connect($servername,$username,$password);
mysql_select_db("db");
//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);
echo "<script>window.location='select.php'</script>"; //select.php displays the full table
//close MySQL
mysql_close($sql);
?>
It might be because the default form posting method is GET.
Either change your $_POST to $_GET or add method="POST" to your form tag.

Problems with input form

I created a simple form through with I would like to update some info in mysql database. I through it all looks fine but i get some error
I got (two files):
<?php
$db_name = "test2";
$un = "jharvard";
$pw = "crimson";
$host = "localhost";
$connect = mysql_connect($host, $un, $pw);
mysql_select_db($db_name) or die(mysql_error());
echo ("succesfully conneted to the database!");
?>
and
<?php
if (isset($_POST['submitted']))
{
//Dit is de php file waarmee je connectie met de database maakt.
include ("addEmployee.php");
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sqlinsert = "INSERT INTO customers (name, address) VALUES ('$fname', '$lname')";
if (!mysqli_query($connect, $sqlinsert))
{
die ('error!');
}
}
?>
<html>
Add somebody!
<body>
<form method= "post" action="oefInsertData.php">
<input type = "hidden" name ="submitted" value="true" />
First name: <input type = "text" name="fname"/>
Last name: <input type = "text" name="lname"/>
<input type="submit" value="Add new person"/>
</form>
</body>
If i run it I get the following error: ! ) Warning: mysqli_query() expects parameter 1 to be mysqli, resource given in /home/jharvard/vhosts/pset7/public/oefInsertData.php on line 16
Anybody know what goes wrong here?
You are using both my_sql and my_sqli extension together..
Use this..
$connect = mysqli_connect($host, $un, $pw, $db_name);
and avoid
mysql_select_db($db_name) or die(mysql_error());
replace
<?php
$db_name = "test2";
$un = "jharvard";
$pw = "crimson";
$host = "localhost";
$connect = mysql_connect($host, $un, $pw);
mysql_select_db($db_name) or die(mysql_error());
echo ("succesfully conneted to the database!");
?>
with
<?php
$con=mysqli_connect("localhost","jharvard","crimson","test2");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
you have switch from mysql_ to mysqli_ so $connect is not a mysqli parameter change this by using mysqli_connect reference
<?php
$db_name = "test2";
$un = "jharvard";
$pw = "crimson";
$host = "localhost";
?>
and
<?php
if (isset($_POST['submitted']))
{
//Dit is de php file waarmee je connectie met de database maakt.
include ("addEmployee.php");
mysql_connect("$host", "$un", "$pw")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = mysql_query("INSERT INTO customers (name, address) VALUES ('{$fname}', '{$lname}')");
if(!$query){ echo mysql_error(); }
}
?>

Categories