PHP, MySQL Insert data from first table into second, third and fourth - php

I have one table called users (id, username, password), second table called profiles (id, user_id, username, name, lastname, age, gender, country, company_name), third table called companies (id, user_id, name, resources_id) and fourth table called resources (id, user_id, company_id, money). When users register their account, they need to create their profile. Now when they fill profile data, profiles and companies tables are filled just fine.
My problem is in resources table:
Error: Incorrect integer value: '' for column 'company_id' at row 1
When I refresh that page with error, resources table is filled fine, but now I got double rows for profiles and companies tables.
My Code :
<?php
session_start();
$dbserver = "localhost";
$dbusername = "root";
$dbpassword = "1234512345";
$db = "game";
$conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
if ($conn->connect_error)
{
die("Connection failed: ".$conn->connect_error);
}
if(isset($_SESSION['loggedin']))
$username = $_SESSION['loggedin'];
$query = "SELECT id FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$userId = $row['id'];
$_POST['id'] = $userId;
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$country = $_POST['country'];
$company_name = $_POST['company_name'];
$_POST['loggedin'] = $username;
$query = "SELECT id FROM companies WHERE name = '$company_name'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$companyId = $row['id'];
$_POST['id'] = $companyId;
//INSERT DATA INTO PROFILES
$sql = "INSERT INTO profiles (user_id, username, name, lastname, age, gender, country, company_name)
VALUES ('$userId', '$username', '$name', '$lastname', '$age', '$gender', '$country', '$company_name')";
//INSERT DATA INTO COMPANIES
$sql2 = "INSERT INTO companies (user_id, name)
VALUES ('$userId', '$company_name')";
//INSERT DATA INTO RESOURCES
$sql3 = "INSERT INTO resources (user_id, company_id)
VALUES ('$userId', '$companyId')";
if($conn->query($sql) && $conn->query($sql2) && $conn->query($sql3) === TRUE)
{
header("Location: ../../index.php?page=profile");
die();
}
else
{
echo "Error: ".$conn->error;
}
?>
What should I do differently? I'm still beginner into this, sorry for long post.
EDIT:
One guy helped me out with this code, it's more error proof than last version. Deleted companies table, merged it with profiles, now everything works correctly!
<?php
session_start();
$dbserver = "localhost";
$dbusername = "root";
$dbpassword = "1234512345";
$db = "game";
$conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
if ($conn->connect_error)
{
die("Connection failed: ".$conn->connect_error);
}
if(isset($_SESSION['loggedin']))
$username = $_SESSION['loggedin'];
$query = "SELECT id FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$userId = $row['id'];
$_POST['id'] = $userId;
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$country = $_POST['country'];
$company_name = $_POST['company_name'];
$_POST['loggedin'] = $username;
$query = "SELECT id FROM companies WHERE name = '$company_name'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$sql1 = "INSERT INTO profiles (user_id, username, name, lastname, age, gender, country, company_name) VALUES (?,?,?,?,?,?,?,?)";
$sql2 = "INSERT INTO resources (user_id) VALUES (?)";
try {
$conn->autocommit(false);
$statement = $conn->prepare($sql1);
$statement->bind_param("dsssdsss", $userId, $username, $name, $lastname, $age, $gender, $country, $company_name);
$statement->execute();
$statement = $conn->prepare($sql2);
$statement->bind_param("d", $userId);
$statement->execute();
// COMMIT THE CHANGES
$conn->commit();
header("Location: ../../index.php?page=profile");
}
catch(Exception $e){
// undo everything that was done in the try block in the case of a failure.
$conn->rollback();
echo "Error: ".$conn->error;
}?>

Related

Echo var before insert to database

Is it possible to show variable username before I am putting it into DB? Echo, alert, console or something? I want to check what is in $username before do INSERT
<?php
require_once 'connect.php';
$data = json_decode(file_get_contents("php://input"));
$username = mysqli_real_escape_string($connect, $data->username);
$query = "INSERT into tablename (username) VALUES ('$username')";
mysqli_query($connect, $query);
echo true;
?>
Try this
$username = mysqli_real_escape_string($connect, $data->username);
if($username)
{
echo $username;
$query = "INSERT into tablename (username) VALUES ('$username')";
mysqli_query($connect, $query);
}
<?php
require_once 'connect.php';
$data = json_decode(file_get_contents("php://input"));
$username = mysqli_real_escape_string($connect, $data->username);
$query = "INSERT into tablename (username) VALUES ('$username')";
echo "<script>alert('".$username."')</script>";
mysqli_query($connect, $query);
echo true;
?>

mysqli insert, what is wrong?

the data is not inserting. i think there is something wrong in
$sql = "INSERT INTO `users` (`Username`, `Password`, `FirstName`, `LastName`, `Email`, `ContactNumber`)
VALUES ('".$_POST["Username"]."','".$_POST["Password"]."','".$_POST["FirstName"]."','".$_POST["LastName"]."','".$_POST["Email"]."','".$_POST["ContactNumber"]."')";
When i try to change the statement in "else" with echo "successs"; its working.
please someone can tell me what is wrong.
<?php
error_reporting(E_ALL & ~E_NOTICE);
if(isset($_POST["Register"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbuseraccounts";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user = $_POST['Username'];
$pass = $_POST['Password'];
$query = mysqli_query($conn, "SELECT * FROM users WHERE Username= '".$user."'");
if(mysqli_num_rows($query) > 0)
{
echo "email already exists";
}
else
{
$sql = "INSERT INTO users (Username, Password, FirstName, LastName, Email, ContactNumber)
VALUES ('".$_POST["Username"]."','".$_POST["Password"]."','".$_POST["FirstName"]."','".$_POST["LastName"]."','".$_POST["Email"]."','".$_POST["ContactNumber"]."')";
}
$conn->close();
}
?>
Your data is not inserting because you haven't even executed your query.
if (mysqli_num_rows($query) > 0) {
echo "Username already exists";
} else {
$sql = "INSERT INTO users (Username, Password, FirstName, LastName, Email, ContactNumber) VALUES ('".$_POST["Username"]."','".$_POST["Password"]."','".$_POST["FirstName"]."','".$_POST["LastName"]."','".$_POST["Email"]."','".$_POST["ContactNumber"]."')";
/* Run your query and check for errors */
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
}
Please Execute query using
mysqli_query($conn, your query);

PHP is not inserting Data

I have run it on the local server and it worked perfectly, but when I uploaded it to my web hosting, it stopped working.
Basically when I submit the form the browser just keeps loading and when I check the database no data was inserted.
I checked my database connection and I was able to connect it but can't get data from it.
This is my php:
<?php
$servername = "localhost";
$username = "itclubac_root";
$password = "*******";
$dbname = "itclubac_itclub";
$tnp = 0;
$name = $_POST['name'];
$email = $_POST['email'];
$gender = $_POST['gender'];
$phone = $_POST['phone'];
$id = $_POST['id'];
$section = $_POST['section'];
$skills = $_POST['skills'];
$interests = $_POST['interests'];
$expectations = $_POST['expectations'];
$tnp = $_POST['tnp'];
$ip = $_SERVER['REMOTE_ADDR'];
if ( $tnp == 0 ) {
header('Location: ../../get_involved.php');
} else {
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$query = mysqli_query($con, "SELECT * FROM member_registration WHERE email = '".$email. "'");
if ( mysqli_num_rows($query) > 0 ) {
header('Location: ../../get_involved.php?status=exist');
} else {
$query = mysqli_query($con, "SELECT * FROM member_registration WHERE college_id = '".$id. "'");
if ( mysqli_num_rows( $query) > 0 ) {
header('Location: ../../get_involved.php?status=exist');
} else {
$sql = "INSERT INTO member_registration (name, email, gender, phone_no, college_id, section, skills, interests, expectations, ip_address) VALUES ('$name', '$email', '$gender', '+880$phone', '$id', '$section', '$skills', '$interests', '$expectations', '$ip')";
if ($con->query($sql) === TRUE) {
header('Location: ../../get_involved.php?status=success');
}
}
}
}
$con->close();
?>
Edit
This is the site: Form Pagehttp://itclub.acc.edu.bd/get_involved.php if you register here, the page will just keep loading. However if you try to access the registration.php directly it sends you to the form page page as I said it to. When I tested it on local, it worked perfectly but after uploading to the host this problem is occurring.
I tried to sort your code and maybe the error is related on the of your query,
$sql = "INSERT INTO member_registration (name, email, gender, phone_no, college_id, section, skills, interests, expectations, ip_address) VALUES ('$name', '$email', '$gender', '+880$phone', '$id', '$section', $'skills', '$interests', '$expectations', '$ip')";
Have you notice this part $'skills' of the line? change your code into,
$sql = "INSERT INTO member_registration (name, email, gender, phone_no, college_id, section, skills, interests, expectations, ip_address) VALUES ('$name', '$email', '$gender', '+880$phone', '$id', '$section', '$skills', '$interests', '$expectations', '$ip')";
maybe it help.

Trying to insert multiple form data into multiple tables to the database, no error given but not working

When I run my code, I get no errors and nothings being sent to the database as well and I can't seem to figure out what the problem could be here ?
I am new to this forum and mysql and php as well and Im not really sure if this is the right way of inserting the datas when you have multiple tables to fill in
or it could be something to do with the incorrect html input attributes?
$db = mysql_connect($dbhost, $dbusername, $dbpass);
$db_select = mysql_select_db($dbdatabase, $db);
if (!$db_select) {
die ("Unable to select database: " . mysql_error());
}
$query = "SELECT * FROM members, login, skills, indivoffers";
$result = mysql_query($query);
if (isset($_POST['mrmrs'],$_POST['fname'],$_POST['lname'],$_POST['gender'],$_POST['addr1'],
$_POST['addr2'],$_POST['city'],$_POST['postcode'],$_POST['hometel'],$_POST['mobtel'],
$_POST['email'],$_POST['job'],$_POST['user'],$_POST['pass'],$_POST['skill1'],
$_POST['skill2'],$_POST['skill3'],$_POST['skill4'],$_POST['skill5'],$_POST['skill6'],
$_POST['skill7'],$_POST['skill8'],$_POST['skill9'],$_POST['ortitle'],$_POST['message'],
$_POST['offereq'],$_POST['cost'],$_POST['pay'])){
$title = $_POST['mrmrs'];
$name = $_POST['fname'];
$name2 = $_POST['lname'];
$gender = $_POST['gender'];
$address1 = $_POST['addr1'];
$address2 = $_POST['addr2'];
$city = $_POST['city'];
$pc = $_POST['postcode'];
$telhome = $_POST['hometel'];
$telmob = $_POST['mobtel'];
$email = $_POST['email'];
$job = $_POST['job'];
$username = $_POST['user'];
$password = $_POST['pass'];
$skill1 = $_POST['skill1'];
$skill2 = $_POST['skill2'];
$skill3 = $_POST['skill3'];
$skill4 = $_POST['skill4'];
$skill5 = $_POST['skill5'];
$skill6 = $_POST['skill6'];
$skill7 = $_POST['skill7'];
$skill8 = $_POST['skill8'];
$skill9 = $_POST['skill9'];
$titleor = $_POST['ortitle'];
$mess = $_POST['message'];
$offerequest = $_POST['offereq'];
$cost = $_POST['cost'];
$pay = $_POST['pay'];
$sql = "INSERT INTO members (Mr/Mrs, fname, lname, gender, DOB, addr1, addr2, city, postcode, telnohome, telnomob, email, job)
VALUES ('$title','$name','$name2', '$gender', '$address1', '$address2', '$city', '$pc', '$telhome', '$telmob', '$email', '$job')";
$letsid = mysql_insert_id( $db);
$sql = "INSERT INTO login (letsID,username, password)
VALUES (letsID),'$username','$password')";
$letsid = mysql_insert_id( $db);
$sql = "INSERT INTO skills (letsID, skill1, skill2, skill3, skill4, skill5, skill6, skill7, skill8, skill9)
VALUES (letsID,'$skill1', '$skill2', '$skill3', '$skill4', '$skill5', '$skill6', '$skill7', '$skill8','$skill9')";
$letsid = mysql_insert_id( $db);
$sql = "INSERT INTO indivoffers (letsID, title, message, offer/request, cost, pay)
VALUES (letsID,'$titleor','$mess', '$offerequest', '$cost', '$pay')";
$letsid = mysql_insert_id( $db);
}
?>
You are creating the querys correctly but you aren't actually executing them.
So instead of doing <?php $sql = "INSERT INTO ..."; ?> you can do something like this
<?php $sql = mysql_query("INSERT INTO ..."); ?>
Setting the variable to a mysql query will execute the query so therefore this should run your querys now.

Insert form data in one table and then update an enum value in a different table?

I am using a code to insert a users form data into the database, that bit works fine. However, i also want to run another query and update an enum value 'form2_completed?' from No to Yes. I have added in the update query and now for some reason the script is not working and says 'ERROR'
Can someone please show me where i am going wrong. thanks
<?php
session_start();
$db_hostname = 'localhost';
$db_database = 'hewden1';
$db_username = 'root';
$db_password = '';
$db_server = mysql_connect($db_hostname, $db_username, $db_password)
or die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
$cname = $_POST['cname'];
$creg = $_POST['creg'];
$address = $_POST['address'];
$post = $_POST['post'];
$contactn = $_POST['contactn'];
$contactt = $_POST['contactt'];
$email = $_POST['email'];
$vat = $_POST['vat'];
$ipaddress = $_SERVER["REMOTE_ADDR"];
$sql="INSERT INTO supplier_registration (company_name, company_reg_number, company_address, company_postcode, contact_name, contact_number, contact_email, company_vat_number, date_time, user_ip)
VALUES ('$cname', '$creg', '$address', '$post', '$contactn', '$contactt', '$email', '$vat', NOW(), '$ipaddress')";
$sql="UPDATE supplier_session SET form2_completed? = 'Yes' WHERE form2_completed? = 'No'";
$result = mysql_query($sql);
if($result){
$success = "<div class='success'></div>"; // use the $success
//encode the URL parameter as :
$success = urlencode($success);
header("Location: index.php?success=$success");
}else {
echo "ERROR";
}
?>
You are overwriting the variable $sql and not running INSERT. Try:
$sql="INSERT INTO supplier_registration (company_name, company_reg_number, company_address, company_postcode, contact_name, contact_number, contact_email, company_vat_number, date_time, user_ip)
VALUES ('$cname', '$creg', '$address', '$post', '$contactn', '$contactt', '$email', '$vat', NOW(), '$ipaddress')";
$result = mysql_query($sql);
$sql="UPDATE supplier_session SET form2_completed? = 'Yes' WHERE form2_completed? = 'No'";
$result = mysql_query($sql);
Please note that the method you have used is deprecated from php 5.5.0. so i suggest you consider mysqli or PDO. examples can be found in below php manual links
http://www.php.net/manual/en/mysqli.query.php
http://www.php.net/manual/en/pdo.query.php

Categories