how to add data in 2 table in only one form - php

HTML CODE
<form method = "POST" action = "register.php">
<div class = "register">
<center>
<div class = "heading"></br>
<strong>--- REGISTER ---</strong></br></br>
</div>
</center>
<div class = "registration">
First Name: <input type = "text" placeholder = "Enter First Name" name = "Cus_fname" style = "margin-left: 48px;" required></br></br>
Last Name: <input type = "text" placeholder = "Enter Last Name" name = "Cus_lname" style = "margin-left: 49px;" required></br></br>
Username: <input type = "text" placeholder = "Enter Username" name = "Cus_Uname" style = "margin-left: 55px;" required></br></br>
Password: <input type = "password" placeholder = "Enter Password" name = "Cus_Pword" style = "margin-left: 61px;" required></br></br>
Address: <input type = "text" placeholder = "Enter Address" name = "Cus_address" style = "margin-left: 67px;" required></br></br>
Contact No.: <input type = "text" placeholder = "Enter Contact Number" name = "Cus_contactnum" style = "margin-left: 38px;" required></br></br>
Email: <input type = "text" placeholder = "Enter E-mail Address" name = "Cus_email" style = "margin-left: 88px;" required></br></br>
<input type = "submit" name = "submit" value = "Submit" style = "margin-left: 110px;"></br>
</div></br>
</form>
PHP CODE
<?php
if(isset($_POST['submit'])){
$cf = $_POST['Cus_fname'];
$cl = $_POST['Cus_lname'];
$cu = $_POST['Cus_Uname'];
$cp = $_POST['Cus_Pword'];
$ca = $_POST['Cus_address'];
$cn = $_POST['Cus_contactnum'];
$ce = $_POST['Cus_email'];
include("config.php");
mysqli_query($con, "INSERT INTO account (Cus_ID, Cus_Uname, Cus_Pword) VALUES ('null', '$cu', '$cp')");
mysqli_query($con, "INSERT INTO client (Cus_ID, Cus_lname, Cus_fname, Cus_address, Cus_contactnum, Cus_email) VALUES(null, '$cl', '$cf', '$ca', '$cn', '$ce')");
mysqli_close($con);
}
?>
The problem is that it's only adding on one table which is my client table and it only add 1 data to my account table no more than that
Im Using MySQL Workbench for my database

Using a prepared statement allows you to protect from SQL Injection. Checking all your posts helps ensure that they have some value if needed.
<?php
if(isset($_POST['submit'])){
// Populate each variable
$cf = isset($_POST['Cus_fname'])?$_POST['Cus_fname']:"";
$cl = isset($_POST['Cus_lname'])?$_POST['Cus_lname']:"";
$cu = isset($_POST['Cus_Uname'])?$_POST['Cus_Uname']:"";
$cp = isset($_POST['Cus_Pword'])?$_POST['Cus_Pword']:"";
$ca = isset($_POST['Cus_address'])?$_POST['Cus_address']:"";
$cn = isset($_POST['Cus_contactnum'])?$_POST['Cus_contactnum']:"";
$ce = isset($_POST['Cus_email'])?$_POST['Cus_email']:"";
include("config.php");
if ($stmt = $mysqli->prepare("INSERT INTO account (Cus_Uname, Cus_Pword) VALUES (?, ?, ?)")) {
// bind parameters for markers
$stmt->bind_param("sss", $cu, $cp);
// execute query
$stmt->execute();
// close statement
$stmt->close();
}
if ($stmt = $mysqli->prepare("INSERT INTO client (Cus_lname, Cus_fname, Cus_address, Cus_contactnum, Cus_email) VALUES (?, ?, ?, ?, ?)")) {
// bind parameters for markers
$stmt->bind_param("sssss", $cl, $cf, $ca, $cn, $ce);
// execute query
$stmt->execute();
// close statement
$stmt->close();
}
mysqli_close($con);
}
?>
This code assumes that your ID Column uses Auto-Increment. In this case, you do not need to include the IS in INSERT, it will be done automatically when the query runs.

Check the query for your account table.
mysqli_query($con, "INSERT INTO account (Cus_ID, Cus_Uname, Cus_Pword)
VALUES ('null', '$cu', '$cp')");
You have placed a typo 'null' which is a string into your Cus_ID which i assume the datatype is INT since it is a ID. Remove the single quotes null and see if that works.

Related

PHP MySQL UPDATE statement

I am making a website where after you have logged in and added all your contacts in the database you can also edit them. The way to go is the MYSQL UPDATE statement. I have written the code but sosmething does not seem to work and has been torturing me for hours. Here is the code
<?php
session_start();
$del_id = $_GET["id"];
$_SESSION["id"] = $del_id;
$del_name = $_GET["name"];
$del_phone = $_GET["phone"];
$del_address = $_GET["address"];
$del_email = $_GET["email"];
$name2 = $_POST["name"];
$address2 = $_POST["address"];
$number2 = $_POST["number"];
$email2 = $_POST["email"];
$query = "UPDATE `contacts` SET email = '$email2' AND phone = '$number2' AND address = '$address2' AND name = '$name2' WHERE id = '$del_id'";
$conn = mysqli_connect($servername,$username,$password,$dbname);
if(!$conn){
die("Connection failed: ".mysqli_connect_error());
}else{
echo "Connected successfully";
}
if(mysqli_query($conn,$query)){
echo "Contact edited";
}
?>
<html><head></head>
<body>
<form action="edit.php" method = "POST">
Add text only to the ones you want changed:<br><br>
NAME<input type="text" value="<?php echo $del_name?>" name="name"><br>
ADDRESS<input type="text" value="<?php echo $del_address?>" name="address"><br>
PHONE NUMBER <input type="text" value="<?php echo $del_phone ?>" name="number"><br>
EMAIL <input type="text" value="<?php echo $del_email ?>" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
What could be the problem because the contact in the database is not being updated after that?
Your UPDATE statement is wrong:
"UPDATE `contacts` SET email = '$email2' AND phone = '$number2' AND address = '$address2' AND name = '$name2' WHERE id = '$del_id'"
Try this instead
// Please sanitize the data
$email2 = filter_var( $email2, FILTER_SANITIZE_EMAIL );
$name2 = preg_replace( "#[^a-zA-Z ]#", '', $name2 );
$number2 = preg_replace( "#[^0-9 \-\+]#", '', $number2 );
$address = preg_replace( "[^\w \.\-\+]#", '', $address2 );
"UPDATE `contacts` SET email = '$email2', phone = '$number2', address = '$address2', name = '$name2' WHERE id = '$del_id' LIMIT 1"
Note
I added the limit clause LIMIT 1 to limit the number of rows that will be affected by the update statement. In this case, am setting it to 1 to make sure we're updating a single row. Am sure you would want that also.
* Please, consider using mysqli prepared query or PDO
Replace your $query line.
$query = "UPDATE `contacts`
SET email = '$email2', phone = '$number2', address = '$address2', name = '$name2'
WHERE id = '$del_id'";
AND can be used in WHERE clause.
$query = "UPDATE `users` SET `userpassword` = CONCAT(`userpassword`, 'a') WHERE `user_id` = 1";
READ THE GUIDELINES

Get the value from previous page php, sql

I can't get the value of id from update.php and give to it another page which is update2.php
Here is the code of my update.php
<form method = "post" action = "update2.php ?id=".$row['0'].">
<p class = "head">Update Account Basic Info</p>
<p class = "form">
<input type = "text" class = "name" name = "f_name" placeholder = "First Name">
<input type = "text" class = "name" name = "l_name" placeholder = "Last Name">
<br>
<input type = "text" class = "other" name = "email" placeholder = "Email Address">
<br>
<input type = "numeric" class = "other" name = "mob_no" placeholder = "Mobile Number">
<br></br>
<input type = "submit" name = "save" value = "Update Account">
</p>
</form>
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("dbfacebook", $con);
$query = "SELECT id_no, f_name, l_name, email, mob_no FROM tblaccount WHERE id_no = '$_GET[id]'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<p class = 'sub'>Current Account Basic Info</p>";
echo "<p class = 'form'>ID Number: ".$row['0']."<br>";
echo "First Name: ".$row['1']."<br>";
echo "Last Name: ".$row['2']."<br>";
echo "Email: ".$row['3']."<br>";
echo "Mobile Number: ".$row['4']."</p>";
}
mysql_close();
?>
Here is my code of update2.php
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("dbfacebook", $con);
echo $_GET['id'];
mysql_query("UPDATE tblaccount SET f_name = '$_POST[f_name]', l_name = '$_POST[l_name]', email = '$_POST[email]', mob_no = '$_POST[mob_no]' WHERE id_no = '$_GET[id]'");
echo "<h1>Account Updated</h1>";
mysql_close($con);
?>
My problem is my $_GET[id] function in update2.php can't get the value of id_no in update.php
You wont get the right result when you use
action = "update2.php ?id=".$row['0']."
because, .$row['0']. is not php.. It is just HTML..
Instead, you will have to use
action = "update2.php?id=<?php echo $row['0']; ?>"
UPDATE
Since you are getting Undefined variable: row error, it means that $row is null.
Thus, Move
$con = mysql_connect("localhost","root","");
mysql_select_db("dbfacebook", $con);
$query = "SELECT id_no, f_name, l_name, email, mob_no FROM tblaccount WHERE id_no = '$_GET[id]'";
$result = mysql_query($query);
to the line before opening the <form>.
ie, Now, the code should be like
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("dbfacebook", $con);
$query = "SELECT id_no, f_name, l_name, email, mob_no FROM tblaccount WHERE id_no = '$_GET[id]'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
<form method = "post" action = "update2.php?id=<?php echo $row['0']; ?>">
}
?>

Can't select id from different table in MySQL database

I'm building a website where users should be able to input music artists and albums into a database. I have tables artists and albums in the musique database.
I'm trying to select artistId from artists and associate it with whatever album the user is trying to input. The artistId keeps coming back as 0, though. I think something is wrong with my SELECT statement, but I'm not totally sure.
Does anyone see a reason why this is happening?
inputalbum.php:
<?php
include "session.php";
include "db.php";
SessionClient::checkIfLoggedIn();
// Get list of artists to suggest
$conn = DB::connect();
$results = $conn->query("SELECT artistName FROM artists");
$artists = [];
while ($row = $results->fetch_assoc()) {
$artists[] = $row;
}
?>
<?php include "header.php"; ?>
<div class="container">
<h1>INSERT ALBUM</h1>
<form class="form" enctype="multipart/form-data" action="albumredir.php" method="POST">
<fieldset>
<label for ="artistName">Artist</label>
<input type="text" name="artistName">
<br>
<!-- <div>
Artists already in the database: <span>?</span>
</div> -->
<script>
// Transfer php array to js to use on the browser
var artists = <?php echo json_encode($artists) ?>;
// Grab the artist input field
var artistInput = document.querySelector('input[name="artists"]');
// Set an event for when they change to suggest artists
artistInput.oninput = function () {
var currentValue = artistInput.value;
var suggestedArtists = [];
artists.forEach(function (artist) {
var enteredArtists = currentValue.split(',');
if (artist.label.match(enteredTags[enteredArtists.length - 1].trim())) {
suggestedArtists.push(artist);
}
});
var suggestionString = suggestedArtists.map(t => t.label).join(',');
document.querySelector('div span').innerHTML = suggestionString;
}
</script>
<label for="albumName">Album Name:</label>
<input type="text" name="albumName" placeholder="Album One">
<br>
<label for="relDate">Release Date:</label>
<input type="date" name="relDate">
<br>
</fieldset>
<fieldset>
<input type="submit" name="submit" value="Submit">
</fieldset>
</form>
</div>
albumredir.php:
<?php
session_start();
$artistName = $_POST['artistName'];
$albumName = $_POST['albumName'];
$relDate = $_POST['relDate'];
$submit = $_POST['submit'];
include "db.php";
$conn = DB::connect();
$artistId = $conn->query("SELECT artistId FROM artists WHERE artistName = $artistName");
$stmt = $conn->prepare("INSERT INTO albums (artistId, userId, albumName, relDate) VALUES (?, ?, ?, ?)");
$stmt->bind_param(
"iiss",
$artistId,
$_SESSION['currentUser']['userId'],
$_POST['albumName'],
$_POST['relDate']
);
if(isset($_SESSION['currentUser']['userId']))
{
$currentUser = $_SESSION['currentUser']['userId'];
}
else
{
$currentUser = NULL;
}
if(isset($_POST['albumName']))
{
$albumName = $_POST['albumName'];
}
else
{
$albumName = NULL;
}
if(isset($_POST['relDate']))
{
$relDate = $_POST['relDate'];
}
else {
$relDate = NULL;
}
$stmt->execute();
// Close the connection
$conn->close();
// header('Location: index.php');
?>
$artistId = $conn->query is returning a result set, so you can't bind to it directly later when you try:
$stmt->bind_param(
"iiss",
$artistId,
you will need to fetch the artistId from the result set first.
In this example, I change the name of the result set from $artistId to $result for clarity.
$result = $conn->query("SELECT artistId FROM artists WHERE artistName = $artistName");
// get row from result
$row = $result->fetch_assoc();
// get artistID from row
$artistId = $row["artistId"];
$stmt = $conn->prepare("INSERT INTO albums (artistId, userId, albumName, relDate) VALUES (?, ?, ?, ?)");
$stmt->bind_param(
"iiss",
$artistId,
$_SESSION['currentUser']['userId'],
$_POST['albumName'],
$_POST['relDate']
);

Cannot add values in Database using PHP

I am currently doing a project in adding values using database but I seem to have a problem. I am sure that my query is correct since I tried adding it manually in mysql. Only some of the fields seem to be able to get what I input. I get the error
"Error: INSERT INTO inventory (itemCode, dateReceived, typeOfFabric, details, unitOfMeasurement, amount, assignedOrderUse, section, row) VALUES ('', '', '', 'White', '', '5', '', 'C', 'C')"
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "gracydb";
if (isset($_POST['addInventory']))
{
if(isset($_POST['itemCode'])){ $itemcode = $_POST['itemCode']; }
if(isset($_POST['dateReceived'])){ $inventoryDateReceived = $_POST['dateReceived']; }
if(isset($_POST['typeOfFabric'])){ $fabric = $_POST['typeOfFabric']; }
if(isset($_POST['details'])){ $details = $_POST['details']; }
if(isset($_POST['unitOfMeasurement'])){ $measurement = $_POST['unitOfMeasurement']; }
if(isset($_POST['amount'])){ $amount = $_POST['amount']; }
if(isset($_POST['assignedOrderUse'])){ $order = $_POST['assignedOrderUse']; }
if(isset($_POST['section'])){ $section = $_POST['section']; }
if(isset($_POST['row'])){ $row = $_POST['row']; }
$conn = mysql_connect($host, $user, $pass);
$db_selected = mysql_select_db($db, $conn);
$sql = "INSERT INTO inventory (itemCode, dateReceived, typeOfFabric, details, unitOfMeasurement, amount, assignedOrderUse, section, row)
VALUES ('$itemcode', '$datereceived', '$fabric', '$details', '$measurement', '$amount', '$order', '$section', '$row')";
if (mysql_query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error($conn);
}
mysql_close($conn);
//header ('Location: .php');
}
?>
<form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method = "POST">
Item Code: <input type = "text" name = "itemcode"><br>
Date Received: <input type = "date" name = "inventoryDateReceived"><br>
Type of Fabric: <input type = "text" name = "fabric"><br>
Unit of Measurement:
<select name = "measurement">
<option value = "Grams">Grams</option>
<option value = "Kilograms">Kilograms</option>
</select><br>
Amount: <input type = "number" name = "amount"><br>
Assigned Order/Use: <input type = "text" name = "order"><br>
Section: <input type = "text" name = "section"><br>
Row: <input type = "text" name = "row"><br>
<input type = "submit" value = "submit" name = "addInventory">
</form>
These indexes not matched with your input form names:
$_POST['itemCode']
$_POST['dateReceived']
$_POST['typeOfFabric']
These should be:
$_POST['itemcode']
$_POST['inventoryDateReceived']
$_POST['fabric']
Check your form inputs:
<input type = "text" name = "itemcode">
<input type = "date" name = "inventoryDateReceived">
<input type = "text" name = "fabric">
I don't see any sense in this part of the code:
if(isset($_POST['itemCode'])){ $itemcode = $_POST['itemCode']; }
if(isset($_POST['dateReceived'])){ $inventoryDateReceived = $_POST['dateReceived']; }
if(isset($_POST['typeOfFabric'])){ $fabric = $_POST['typeOfFabric']; }
if(isset($_POST['details'])){ $details = $_POST['details']; }
if(isset($_POST['unitOfMeasurement'])){ $measurement = $_POST['unitOfMeasurement']; }
if(isset($_POST['amount'])){ $amount = $_POST['amount']; }
if(isset($_POST['assignedOrderUse'])){ $order = $_POST['assignedOrderUse']; }
if(isset($_POST['section'])){ $section = $_POST['section']; }
if(isset($_POST['row'])){ $row = $_POST['row']; }
Your are just setting values (if isset) to new variables - but if they not exists you will still use undefined variables. Also there is no escaping to prevent sql-injections and validation of the given values!
I think you will get this error because of a missing variable.

Can't insert the row into database

Why I can't insert into the database? What's wrong with my code?
<form action = "" method ="POST">
<center>
<b>Name</b><br><br>Quantity: <input type = "text" name = "name" style = "width: 155px"><br><br>
<b>Contact Number</b><br><br>Quantity: <input type = "text" name = "contact" style = "width: 155px" ><br><br>
<b>Address</b><br><br>Quantity: <input type = "text" name = "address" style = "width: 155px"><br><br>
<b>Spoon N1(₱25000.00)</b><br><br>Quantity: <input type = "text" name = "Squantity" style = "width: 155px" value = "0"><br><br>
<b>Tanabe Hypermedallion(₱15000.00)</b><br><br>Quantity: <input type = "text" name = "Tquantity" style = "width: 155px" value = "0"><br><br>
<b>Fujitsubo Legalis R(₱15000.00)</b><br><br>Quantity: <input type = "text" name = "Fquantity" style = "width: 155px" value = "0"><br><br>
<b>GCash Transaction No.</b><br>:
<input type = "text" name = "quantity" style = "width: 155px"><br><br>
<input type = "submit" value = "submit">
</center>
</form>
<?php
if(isset($_POST['submit']))
{
$name = empty($_POST['name']) ? die ("Input a name"): mysql_escape_string($_POST['name']);
$contact = empty($_POST['contact']) ? die ("Input a contact number"): mysql_escape_string($_POST['contact']);
$address = empty($_POST['address']) ? die ("Input a address"): mysql_escape_string($_POST['address']);
$spoon = empty($_POST['Squantity']) ? die ("Input a value"): mysql_escape_string($_POST['Squantity']);
$tanabe = empty($_POST['Tquantity']) ? die ("Input a value"): mysql_escape_string($_POST['Tquantity']);
$fujitsubo =empty($_POST['Fquantity']) ? die ("Input a value"): mysql_escape_string($_POST['Fquantity']);
$total = ($spoon * 25000) + ($tanabe * 15000) + ($fujitsubo * 15000);
$host = "localhost";
$user = "root";
$pass = "password";
$db = "eurocare";
$con = mysql_connect($host,$user,$pass,$db) or die ("Unable to connect");
$conn = mysql_select_db($db,$con);
$query = "INSERT INTO orders(name, contact, address, spoon, tanabe, fujitsubo) VALUES ('$name','$contact','$address','$spoon','$tanabe','$fujitsubo','$total')";
$result = mysql_query($query,$con) or die("Error in Query : $query ." .mysql_error());
exit;
mysql_close($con);
}
Using mysql_connect is deprecated, use mysqli instead.
I see you basically want to insert 7 elements, but declared only six...
INSERT INTO orders(name, contact, address, spoon, tanabe, fujitsubo) <-- ##!!SIX!!## VALUES ('$name','$contact','$address','$spoon','$tanabe','$fujitsubo','$total') <-- ##!!SEVEN!!##
Your submit button ie. HTML input element <input type="submit" ... ...> has to have the "name" attribute to be included in the $_POST array.
<input type = "submit" value = "submit" name="submit">
Without it if(isset($_POST['submit'])) would never resolve to true.

Categories