Let's start that I am newbie in php, so still I am trying to learn. I have created a form on Wordpress and I want to insert the values on one table (data_test table, i have managed that) and then take all the columns from data_test table(id that is auto increment number,name,email,product, quantity that the user enter) and insert to other table. I used this html code for the form to parse the values:
<form action="../enter_data_insert.php" method="post" onsubmit="return form_validation()" name="myForm">
Name <input id="name" name="name" type="text" />
Email <input id="email" name="email" required type="email"/>
Product<input id="prod" name="prod" required type="text" />
Quantity<input id="quant" name="quant" required type="number" min="1" / >
<input type="submit" value="Submit" />
</form>
And then this php to take the values:
<?php
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["prod"]) && !empty($_POST["quant"])){
//connect with database
include "database_conn.php";
//get the form elements and store them in variables
session_start();
$name=$_POST["name"];
$email=$_POST["email"];
$prod=$_POST["prod"];
$quant=$_POST["quant"];
//insert data on data_test table
$sql="INSERT INTO `site_db`.`data_test` ( `name` , `email`, `prod`,`quant`) VALUES ( '$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//retrieve data
$sql = "SELECT data_test_id FROM data_test WHERE prod='$prod'";
$result = mysqli_query($con,$sql);
if(!$result){
echo mysqli_error($con);
} else{
while($value = mysqli_fetch_object($result)){
$id = intval($value->id);
$_SESSION['myid'] = $value->id;
var_dump($value);
//insert data on data_test_ins table
$sql="INSERT INTO site_db.data_test_ins` ( id,name , email, prod,quant) VALUES ( $id,'$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//Redirects to the specified page
// header("Location: http://localhost/site/");
}
}
}
}
}
?>
Now it inserts all the values except the id on data_test table, i guess that it is null because it must close the first insert on php and then i have to call a second insert (with //insert data on data_test_ins table) on other php?
But i am not sure, can anyone help me please? or just guide me what is the right way to do.
I start to think that i have to create two php to parse the values and take on the first table and then on the other php to insert the values?
Any thoughts are helpful! :-)
What you are doing is not right. It is not a good approach to add value to id field to the database manually. It should be generated automatically by the database. What I would recommend is, add another field to your data_test_ins table eg: test_id which points to the id of your data_test table. This is the concept of foreign key.
Read about the concept of foreign keys here
Your code would now be:-
<?php
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["prod"]) && !empty($_POST["quant"])){
//connect with database
include "database_conn.php";
//get the form elements and store them in variables
session_start();
$name=$_POST["name"];
$email=$_POST["email"];
$prod=$_POST["prod"];
$quant=$_POST["quant"];
//insert data on data_test table
$sql="INSERT INTO `site_db`.`data_test` ( `name` , `email`, `prod`,`quant`) VALUES ( '$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//retrieve data
$sql = "SELECT data_test_id FROM data_test WHERE prod='$prod'";
$result = mysqli_query($con,$sql);
if(!$result){
echo mysqli_error($con);
} else{
while($value = mysqli_fetch_object($result)){
$id = $value->id;
//insert data on data_test_ins table
$sql="INSERT INTO `site_db`.`data_test_ins` ( `id`,`name` , `email`, `prod`,`quant`, `test_id`) VALUES ('$name','$email','$prod','$quant', '$id')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//Redirects to the specified page
header("Location: http://localhost/site/");
}
}
}
}
}
?>
have you tried passing $value->id into the query instead of $value?
its an object which has the current row of a result set, so you should only pass the id attribute of this object.
$sql="INSERT INTO `site_db`.`data_test_ins` ( `id`,`name` , `email`, `prod`,`quant`) VALUES ( '$value->id','$name','$email','$prod','$quant')";
Addition:
stop using the mysql deprecated library.
you should check the posted data if its isset or not
EDIT:
your code should looks like:
<?php
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["prod"]) && !empty($_POST["quant"])){
//connect with database
include "database_conn.php";
//get the form elements and store them in variables
session_start();
$name=$_POST["name"];
$email=$_POST["email"];
$prod=$_POST["prod"];
$quant=$_POST["quant"];
//insert data on data_test table
$sql="INSERT INTO `site_db`.`data_test` ( `name` , `email`, `prod`,`quant`) VALUES ( '$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//retrieve data
$sql = "SELECT data_test_id FROM data_test WHERE prod='$prod'";
$result = mysqli_query($con,$sql);
if(!$result){
echo mysqli_error($con);
} else{
while($value = mysqli_fetch_object($result)){
$_SESSION['myid'] = $value->data_test_id;
$id = intval($value->data_test_id);
//insert data on data_test_ins table
$sql="INSERT INTO `site_db`.`data_test_ins` ( id,name , email, prod,quant) VALUES ( '$id','$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//Redirects to the specified page
header("Location: http://localhost/site/");
}
}
}
}
}
?>
Related
Attempting to insert a Score based on the User's Session ID and POST , I've set up the database to use the UserID as a foreign key constraint but dont know how to do an insert query.
enter image description here
Database Values ^^
My attempt below
<?php
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
//echo "all good here";
$newsoanxscore = mysqli_real_escape_string($conn, $_POST['socanxscore']);
$insertquery = "INSERT INTO socanxscore(socialanxietyscore)" . "VALUES('$newsoanxscore')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
mysqli_close($conn);
?>
My insert form
<form action="insertsoanxietyscore.php" method="post">
Insert your score <input type="number" name="socanxscore" /><br><br>
<input type="submit" />
</form>
There are a few things here that may be helpful.
Firstly, you are not passing the user ID into your insert query. which can be written in this case as.
$insertquery = "INSERT INTO socanxscore(socialanxietyscore, UserId) VALUES('$newsoanxscore', '$userID')";
Secondly, please take the time to explore prepared queries to prevent SQL injection when passing end-user input to a database table. You may find the following resource useful.
http://php.net/manual/en/mysqli.prepare.php
go for this:
<?php
session_start();
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
if(isset($_POST["socanxscore"]))
{
$query=INSERT INTO socanxscore(socialanxietyscore) VALUES('$newsoanxscore') WHERE userID=$userID";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
}
else
{
ehco "error";
}
mysqli_close($conn);
?>
I have a problem with inserting data into two different tables: When a new member is created, it will be insert into member and grade tables after getting the id course from course table. I used INSERT for both of them at the same time with a multi query function but it doesn't work.
Can you help me please?
The form:
<form>
<input type="text" name='m_fName'>
<input type="text" name='m_lName'>
<input type="text" name ='m_nId'>
</form>
Php
$id = $re['c_id']; //to get id of course that I want to insert
$sql="INSERT INTO member (m_fName, m_lName, m_nId)
VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');
INSERT INTO grade(c_id,m_nId)
VALUES( '$id','$_POST[m_nId]')";
mysqli_multi_query($conn,$sql);
$id = $re['c_id'];
$sql="INSERT INTO member (m_fName, m_lName, m_nId) VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');";
$sql .="INSERT INTO grade(c_id,m_nId) VALUES( '$id','$_POST[m_nId]')";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Hope this will help. but try to first validate the posted data. check if isset .you did not show in the are you using post and the page you are posting your data
Answer above is the correct one, alternative way is the code below
$id = $re['c_id']; //to get id of course that I want to insert
$sql="INSERT INTO member (m_fName, m_lName, m_nId) VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');";
$act = mysqli_query($conn,$sql);
if($act) {
$sql2 = "INSERT INTO grade(c_id,m_nId)
VALUES( '$id','$_POST[m_nId]')";
$act2 = mysqli_query($conn,$sql2);
}
I building an website and when i insert data in database it works but when i try to insert again,i want to give me error,for example if the data that i inserted before its the same off the data that im inserting now, i want to stay in the same page.And if i never inserted that data i want to insert in databse.
<?php
include_once 'dbconfig.php';
if($_POST){
$descricao = $_POST['descricao'];
$tipo_divisao = $_POST['tipo_divisao'];
$sql_query = "SELECT descricao FROM divisao WHERE descricao ='$descricao'";
$consulta = mysqli_query($link,$sql_query);
if(mysqli_num_rows($consulta)==1){
header("Location: Add_Divisao.html");
exit;
}else{
$sqlite_query = "INSERT INTO divisao(descricao,Tipo_Divisao,cenario) VALUES ('$descricao','$tipo_divisao',72)";
mysqli_query($link, $sqlite_query);
header("Location: Confirm_Divisao_Dispo.html");
exit;
}
}
?>
I am new to the html and php, I had created the database in mysql by using the html and php,i had inserted values and retrieve the data from mysql to php,how can i modify the table means deleting the row,updating the row.
Below is my html code:
<html>
<head>
<title>STUDENT_DATA</title>
</head>
<body>
<form action="1.php" method="post" >
<center>
sname: <input type="text" name="sname" required><br></br>
sno:<input type="text" name="sno"><br></br>
marks:<input type="text" name="marks"><br></br>
class:<input type="text" name="class"><br></br>
phno:<input type="text" name="phno" onkeypress='return event.charCode >
= 48 && event.charCode <= 57'><br></br>
DOB:<input type="date" placeholder="DD-MM-YYYY"
required pattern="(0[1-9]|1[0-9]|2[0-9]|3[01]).(0[1-9]|1[012]).[0-9]{4}"
name="DOB"/><br></br>
<button>submit</button></br>
</center>
</form>
Below is my PHP code:
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "student",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
error_reporting(0);
session_start();
$sname=$_POST['sname'];
$sno=$_POST['sno'];
$marks=$_POST['marks'];
$class=$_POST['class'];
$phno=$_POST['phno'];
$DOB=$_POST['DOB'];
if($sname!='' and $sno!='' and $marks!='')
{
$query = mysql_query("insert into hello1(sname, sno, marks, class, phno ,
DOB)
values ('$sname', '$sno', '$marks', '$class','$phno','$DOB')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else
{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
mysql_close($connection);
?>
Is there any one to help me?
Updation;
$query = "UPDATE hello1 SET column_name_1=value_1,column_2=value_2,... WHERE some_column=some_value;
$query = mysql_query($query);
Deletion
$query = "DELETE FROM hello1 WHERE some_column=some_value;
$query = mysql_query($query);
This is for ur comment :
take data from ur form, keep a unique constraint to use in where condition,
for example if the data u need to modify is "password" for username='admin', what u have to do is,
$query = "UPDATE hello1 SET password=$new_pw WHERE username=admin;
here $new_pasword should contain ur new pasword and username should be unique (if not, it will update all the rows with username as 'admin')
This is with reference to the code which u have sent to me.
$stmt = $mysql->prepare("UPDATE venu SET name = ?, rollnumber = ?, address = ? id = ?");
$stmt->bind_param( $name, $rollnumber, $address, $id);
You cannot update like this because you haven't specified the required row(s) for updation.
for that what u have to do is just add a where condition.
$stmt = $mysql->prepare("UPDATE venu SET name = ?, rollnumber = ?, address = ? WHERE id = ?");
$stmt->bind_param( $name, $rollnumber, $address, $id);
This means, u are updating name, adress and rollnumber of ur table venu, WHERE 'id' of
your row = 'the required one'
Hope this helps :)
I have an html form with checkboxes and I managed to store the values using an array to my database .
I added a name field to the form, and added a column on mysql table .
The problem is, the newly added name field is not storing any values and is malfunctioning the previous code. I'm pretty sure my definition for the $fname value is incorrect, here is the full php code
$dbcon = mysqli_connect("$host","$username","$password","$db_name") ;
if (!$dbcon) {
die('error connecting to database'); }
echo 'Courses successfully registerd , ' ;
// escape variables for security
$studentid = mysqli_real_escape_string($dbcon, $_GET['studentid']);
$fname = $_POST["name"];
// Get Cources
$name = $_GET['ckb'];
if(isset($_GET['ckb']))
{
foreach ($name as $courcess){
$cc=$cc. $courcess.',';
}
}
//$ckb = join (', ', var_dump($_POST['ckb']));
$sql="INSERT INTO courses (studentid, ckb)
VALUES ('$studentid', '$cc', $fname)";
if (!mysqli_query($dbcon,$sql)) {
die('Error: ' . mysqli_error($dbcon));
}
echo " Thank you for using IME Virtual Registeration ";
mysqli_close($dbcon);
?>
$sql="INSERT INTO courses (studentid, ckb)
VALUES ('$studentid', '$cc', $fname)";
is your problem. You are attempting to insert three values into two fields. You need to add your new field after ckb so that the argument $fname can be inserted into it.