I have a phpscript which takes values (Manually entered) and inserts into the column in the database. Now I want to know how would I be adding new values to the existing values for the same card number entered.
if(isset($_POST['insert-btn'])){
#$cardnumber=$_POST['cardnumber'];
#$amount=$_POST['amount'];
if($cardnumber=="" || $amount==""){
echo '<script type="text/javascript">alert("Insert values in all fields")</script>';
}
else{
$query = "insert into Client_Details values('$cardnumber',$amount/2)";
$query_run=mysqli_query($con,$query);
if($query_run){
echo '<script type="text/javascript">alert("Values inserted successfully")</script>';
}
else{
echo '<script type="text/javascript">alert("Values not inserted successfully")</script>';
}
}
}
?>
For example , I have
card number: _________
Sale value: __________
Now for the same card number the sale value entered every different time should be added. If anybody can help me with that. It would be helpful.
Before you insert data into DB, check whether a record for the card number already exists in the DB.
If it exists, use UPDATE query else use INSERT query.
Try the below code:
<?php
if (isset($_POST['insert-btn']))
{
#$cardnumber = $_POST['cardnumber'];
#$amount = $_POST['amount'];
if ($cardnumber == "" || $amount == "")
{
echo '<script type="text/javascript">alert("Insert values in all fields")</script>';
}
else
{
$newQuery = mysqli_query($con, "SELECT * FROM Client_Details WHERE cardnumber='" . $cardnumber . "'");
if (mysqli_num_rows($newQuery) > 0)
{
$query = "UPDATE Client_Details SET amount = amount + '" . $amount . "' WHERE cardnumber = '" . $cardnumber . "'";
}
else
{
$query = "INSERT into Client_Details values('$cardnumber',$amount/2)";
}
$query_run = mysqli_query($con, $query);
if ($query_run)
{
echo '<script type="text/javascript">alert("Values inserted successfully")</script>';
}
else
{
echo '<script type="text/javascript">alert("Values not inserted successfully")</script>';
}
}
}
*Modify the table name and column names accordingly
Related
I have two table in MySql, which are table 1 and table 2. As I want to link table 1 to 2 via userID. However, the funciton I have come out is not working.
MySQl tables are below:
In my case, userId will be the foreign key to link these 2 tables.
However, my functions are not working.
This is my function below:
function insert() {
function adduserdetails($con, $accountId, $name, $contact) {
$query = "insert into userdetails(accountId,name,contact)
values('$accountId','$name','$contact')";
//echo "{$sqlString}";
$insertResult = mysqli_query($con, $query);
if ($insertResult) {
echo " Applicant Detail Added !<br />";
echo "<a href='index.php'>Back to Home</a>";
} else {
echo " Error !";
echo "{$query}";
//header('Location: post.php');
}
}
}
if ($con->query($query) === TRUE) {
$last_id = $con->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $query . "<br>" . $con->error;
}
function adduseremployment($con,$last_id,$occupationMain,$comapny){
$query1 = "insert into useremployment(userId,Occupation,company)
values('$last_id',$occupationMain','$comapny')";
//echo "{$sqlString}";
$insertResult = mysqli_query($con, $query1);
if($insertResult){
echo " Applicant Detail Added !<br />";
echo "<a href='index.php'>Back to Home</a>";
}
else {
echo " Error !";
echo "{$query1}";
//header('Location: post.php');
}
}
You have vertical table.
Check below code,
Be remember to prepare statement.
<?php
function addUser(){
// parent table.
$queryParent = ''; // Your userdetails table insert query
$insertResult = mysqli_query($con, $queryParent);
$userId = mysqli_insert_id($con); // This is your last inserted userId.
// child table.
$queryChild = ''; // Your useremployment table insert query with userId.
$insertResult = mysqli_query($con, $queryChild);
}
?>
your Query is wrong, please check this,
$query1 = "insert into useremployment(userId,occupation,company)
values('$last_id',$occupationMain','$comapny')";
you have to store record on userId as a refrence not to "accountID".
hope it helps,
In second insert you are using wrong column name (userID and not accountID)
$query1 = "insert into useremployment(userID,Occupation,company)
^^^^^^ here
values('$last_id',$occupationMain','$comapny')";
and in function signature and body you have comapny (could be you want company)
mysqli_insert_id takes one parameter, the connection to the database.
But I have two INSERTs in my PHP code, both using the same connection which is defined in my dbConnect.php. How can I distinguish between the two ?
I am looking for the AUTO INCREMENT value in this query :
$sql = "INSERT INTO category VALUES(NULL,'{$category}', '$user_id')";
If I put this code as the second query below, then it works, probably because mysqli_insert_id is taking the latest value in the code, but I'd prefer to be able to specify the value I'm looking for, rather than doing it in this haphazard sort of way.
So, how do I specify the table for my query with mysqli_insert_id?
<?php require('dbConnect.php');
session_start();
$username = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
// Create new record in the db, if the 'Add New Record' button is clicked
if (isset($_POST['create'])) {
$category = ($_POST['category']);
$name = ($_POST['name']);
$phonenumber = ($_POST['phonenumber']);
$address = ($_POST['address']);
$comment = ($_POST['comment']);
$sql = "INSERT INTO category VALUES(NULL,'{$category}', '$user_id')";
$sql2 = "INSERT INTO review VALUES(NULL,'$user_id', '$user_id', '{$name}','{$phonenumber}','{$address}', '{$comment}')";
if ($con->query($sql) === TRUE) {
if ($con->query($sql2) === TRUE) {
echo "New record created successfully";
echo mysqli_insert_id($con);
}} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
}
$con->close();
?>
From the PHP main documentation on mysqli_insert_id()
Return Values:
The value of the AUTO_INCREMENT field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.
Basically in order to get both id's, you have to ask for the auto_increment from the database twice.
$sql = "INSERT INTO category VALUES(NULL,'{$category}', '$user_id')";
$sql2 = "INSERT INTO review VALUES(NULL,'$user_id', '$user_id', '{$name}','{$phonenumber}','{$address}', '{$comment}')";
$id1 = 0;
$id2 = 0;
if ($con->query($sql) === TRUE) {
$id1 = mysqli_insert_id($con);
if ($con->query($sql2) === TRUE) {
$id2 = mysqli_insert_id($con);
echo "New record created successfully";
echo "ID1 is $id1 and ID2 is $id2";
}
}
Since the function returns only the id form the latest query, you could try something like this:
if ($con->query($sql) === TRUE) {
$id = mysqli_insert_id($con);
if ($con->query($sql2) === TRUE) {
echo "New record created successfully";
echo $id;
}
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
Something like this?
if ($con->query($sql) === TRUE) {
$first_id = mysqli_insert_id($con);
if ($con->query($sql2) === TRUE) {
$second_id = mysqli_insert_id($con);
echo "New record created successfully";
echo "First: " . $first_id . " Second: " . $second_id;
}
}
I want to select the data and then store it's information inside of a variable. I feel this is very simple but I can't seem to get it to do it. When I run the below code the result is blank.
Thanks for any help.
$sql = "SELECT `$dateName` FROM `$user` WHERE hour=1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$x = $row["`$dateName`"];
echo $x;
}
}
Here is my Create Table code:
/* CREATE TABLE FOR NEW USER */
$sql = "CREATE TABLE `$newUser` (
hour INT(6) NOT NULL
)";
/* CHECK CREATION */
if ($conn->query($sql) === TRUE) {
} else {
echo "Error creating table: " . $conn->error . ".<br><br>";
}
/* ADD TABLE FOR TODAYS DATE */
$sql = "ALTER TABLE `$user`
ADD `$dateName` text";
if ($conn->query($sql) === TRUE) {
echo "Todays Date entered!";
} else {
echo "Date already Exists" . "<br><br>";
}
$x will always be empty because of the ` you're adding to the key when you access $row:
$x = $row["`$dateName`"];
^ ^ remove ticks (You can also remove ")
I'm trying to check whether major, grade and university in candidates table, are empty, if so then insert in university...Else...
Is my syntax appropriate?
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
while($row5 = mysqli_fetch_array($result5)) {
$major = $row5['Major'];
$grade = $row5['Grade'];
$university = $row5['University'];
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`major`, `degree`, `univ`, `afnumber`) VALUES ('$major','$grade','$university','".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
else
{
Use the follwing code
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`major`, `degree`, `univ`, `afnumber`) VALUES ('$major','$grade','$university','".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
else
{
well you are saying that if major, grade and university are empty than insert those empty values in university but the question here is why you want to enter those values if they are empty, even if you want to do so along with inserting afnumber using "$_GET["af"]" variable than you can use following code..
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`afnumber`) VALUES ('".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
its quite short and fulfill the purpose but make sure you have checked null in database for major, grade and univ fields in university table .
I have this small problem on Session. Ill show you the codes below.
//checking session orderid if not created
$setSession = $_SESSION['neworderid'];
if (empty($setSession)) {
$neworderid = mt_rand(1000000000, 9999999999);
$_SESSION['neworderid'] = $neworderid;
}
//check if order_id exists in the database
$db->setQuery("SELECT * FROM mn_orderitems WHERE order_id =" . $_SESSION['neworderid']);
$query = $db->loadResult();
if (!empty($query)) {
//if exists, do nothing
echo 'Not Empty';
} else {
//if order id doesn't exist, save the new order item
$qry = "INSERT INTO mn_orderitems (order_id, product_id, orderitem_name, orderitem_quantity, orderitem_price, orderitem_final_price) VALUES
('" . $_SESSION['neworderid'] . "', '" . $item->product_id . "', '" . $item->orderitem_name . "', '" . $item->orderitem_quantity . "', '" . $item->orderitem_price . "', '" . $item->orderitem_final_price . "')";
$result = mysql_query($qry);
if (!$result) {
echo "Error";
} else {
echo "Saved";
}
echo 'Empty';
}
Problem:
"When I try to echo the $_SESSION['neworderid']; it outputs = 8152269414
But when it is being save to database the order_id changes to 2147483647".
This only happens in live server. No problem in my localhost Apache.
The problem you are having is not with the PHP script itself, but your database structure. In MySQL the biggest number you can store (declared as INT) is 2147483647. If you want to store bigger numbers, you'll have to either change the script to generate a lower number OR change the DB to use BIGINT.
Change first order_id's structure in phpMyAdmin from INT into BIGINT
/* checking session orderid if not created */
session_start();
if (empty($_SESSION['neworderid'])) {
$neworderid = mt_rand(1000000000, 9999999999);
$_SESSION['neworderid'] = $neworderid;
$setSession = $_SESSION['neworderid'];
}
else {
$setSession = $_SESSION['neworderid'];
}
/* check if order_id exists in the database and convert the code to mysqli */
/* have your connection store into $db variable */
$result=mysqli_query($db, "SELECT * FROM mn_orderitems WHERE order_id ='$setSession'");
if (mysqli_num_rows($result)!=0) {
/* If a record has been found, do nothing */
echo "Not Empty";
} else {
/* if order id doesn't exist, save the new order item */
$insert=mysqli_query($db,"INSERT INTO mn_orderitems (order_id, product_id, orderitem_name, orderitem_quantity, orderitem_price, orderitem_final_price)
VALUES ('$setSession', '$product_id', '$orderitem_name', '$orderitem_quantity', '$orderitem_price', '$orderitem_final_price')");
if($insert){
echo "Successfully Added item no. ".$setSession;
}
}