add rows with loop max value +1 - php

I'm trying to add rows to the database based on the input value.
i.e. If input as "5", query will insert 5 rows to database. (this part is working fine)
Now, I need the bed_number to be +1 to the existing max(bed_number) but i can't seems to get it to work.
If existing max(bed_number) returns 5, than the query should add "6,7,8,9,10, etc" as the bed_number for the 5 entries.
If existing max(bed_number) returns null, than it should add "1,2,3,4,5, etc"
Right now, the result always return 1,2,3,4,5... regardless of the max count.
What i have here now is:
global $conn;
if ($values["number_of_bed"])
{
$add1 = $values["number_of_bed"]+1;
$existingBed = "select Max(bed_number) from bed where bed =" '".$i."'" +1;
for ($i=1;$i<$add1;$i++)
{
$strInsert = "insert into bed (unit_id,bed_number) values ('".$values["unit_id"]."','".$existingBed."')";
db_exec($strInsert,$conn);
}
header("Location: bed_list.php");
// Exit and Redirect to the list page after updating database
exit();

//echo "Number of customers: " . $data["c"];
global $conn;
if ($values["bed_number"])
{
$add1 = $values["bed_number"]+1;
//for ($i=1;$i<$values["bed_number"];$i++)
for ($i=1;$i<$add1;$i++)
{
$sql = "select max(bed_number) as c from bed where unit_id =" . $values["unit_id"];
$rs = CustomQuery($sql);
$data = db_fetch_array($rs);
$strInsert = "insert into bed (unit_id,bed_number) values ('".$values["unit_id"]."','".$data["c"]."'+1)";
// add more fields from the add page to be inserted into database
db_exec($strInsert,$conn);
}
header("Location: bed_list.php");
// Exit and Redirect to the list page after updating database
exit();
}

Related

See which table has affected another table SQL-Server

I have created a program in which a user will enter what device they are using and will then perform a task to test their performance based on the device they are using. The user will be taken to a start page in which they will type what device they are using, select from a drop down what hand they are using and the screen width and height will be collected via Javascript along with a primary key called DeviceID. So far all this data is stored in my first table. The second table contains data relating to the user performance such as time etc.
The first table has a one-to-many relationship with the second table as for every 1 device there will be approximately be 100 results.
The part which I am struggling with however is being able to recognise which device entered has gotten which results (i.e. DeviceID 1 got these results, DeviceID 2 got those results etc) and how I can view this relationship.
Edit:
First PHP Page
<?php
include 'db.php';
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
if(isset($_POST['submit']))
{
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$phoneType = $_POST['phoneName'];
$HandUsed = $_POST['HandUsed'];
echo 'hello';
$sql = "INSERT INTO deviceInfo (screenWidth, phoneType, screenHeight, HandUsed)
VALUES ('$screenWidth','$phoneType', '$screenHeight', '$HandUsed')";
if (sqlsrv_query($conn, $sql)) {
// echo "New record has been added successfully !";
} else {
echo "Error: " . $sql . ":-" . sqlsrv_errors($conn);
}
sqlsrv_close($conn);
}
Second PHP Page
<?php
include 'db.php';
$Xpos = $_POST['Xpos'];
$Ypos = $_POST['Ypos'];
$StartID = $_POST['StartID'];
$Random = $_POST['RandomID'];
$Time = $_POST['timeTaken'];
$sql = "INSERT INTO UserResults6(Xpos, Ypos, StartID, RandomID, TimeTaken, DeviceID)
VALUES ('$Xpos', '$Ypos', '$StartID', '$Random', '$Time', SELECT DeviceID from deviceInfo)";
if (sqlsrv_query($conn, $sql)) {
echo "New record has been added successfully !";
} else {
echo "Error: " . $sql . ":-" . sqlsrv_errors($conn);
}
sqlsrv_close($conn);
?>
In the first page everything works as intended and I am given the information that I want along with an auto-incremented DeviceID. In the first page everything works up until the select statement to get the DeviceID. The outcome that I would be hoping for would be for the DeviceID to match with DeviceID from the prior table but I am currently unsure of how to go about achieving this.

how to update a single column of db without deleting its previous data?

i am updating a single column with many values using comma between them. they are working fine. but if update same column from other user the value inserted by previous users deleted. i want to keep values of previous user also with the insertion of new user value. and i also dont want to repeat the same value again because values i m using are unique ids..
// update student list
$venue = ($_GET['venue']);
$district = ($_GET['dis']);
if(isset($_POST['submit']))
//print_r ($_POST);
{
#$std_list=implode(',',$_POST['std_list']);
if(empty($std_list))
{
$error = 1;
$get_value = "Please select you event students.";
}
else
{
//$query = mysql_query("INSERT INTO events (std_list)
//VALUES('".$std_list."')") or die(mysql_error());
$query = mysql_query("UPDATE events SET std_list='".$std_list."' WHERE
id='".$district."' ") or die(mysql_error());
//echo "$msg";
echo "Students list submitted successfully";
}
}
if any query you can ask again. values i am inserting are integers only. Same integer cant be used by two different users.
try this?
$query = mysql_query("UPDATE events SET std_list = CONCAT( std_list, '".$std_list."') WHERE
id='".$district."' ") or die(mysql_error());

How to add total on cart and place order in cart with one click?

I am having some trouble with adding up the total in a cart. I need the cart to be able to add the total of the quantity of items then add a grand total in the order then finally click a Place Order button to be able to order everything inside the cart.
Currently I am able to change the quantity but I have to select the product ID and then choose a quantity, instead of this there should be a little box near each item in the cart where I can type in the quantity.
I then need a grand total in the bottom where all items are added up and a Place Order button when clicked all items in the cart should be ordered in one go.
Currently I have to click place order for each item to place a order so I have to go back and forward, which isnt the right way of doing it.
Please help me i'm still a learner.
Thanks in advance
I will supply the code.
<?php
//Start session
session_start();
$totalAll = 0;
//Include session details
require_once('auth.php');
//Include database connection details
require_once('connection/config.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//checks if id is set in the url
if(isset($_GET['id'])){
//retrive the first quantity from the quantities table
$quantities=mysql_query("SELECT * FROM quantities")
or die("Something is wrong ... \n" . mysql_error());
$row=mysql_fetch_assoc($quantities);
$quantity_value = $row['quantity_value'];
//get id value
$food_id = $_GET['id'];
//retrive food_price from food_details based on $food_id
$result=mysql_query("SELECT * FROM food_details WHERE food_id='$food_id'") or die("A problem has occured ... \n" . "Our team is working on it at the moment ... \n" . "Please check back after few hours.");
$food_row=mysql_fetch_assoc($result);
$food_price=$food_row['food_price'];
//get member_id from session
$member_id = $_SESSION['SESS_MEMBER_ID'];
//define default values for quantity(got from $row), total($food_price*$quantity_value), and flag_0
$quantity_id = $row['quantity_id'];
$total = $food_price*$quantity_value;
$flag_0 = 0;
//Create INSERT query
$qry = "INSERT INTO cart_details(member_id, food_id, quantity_id, total, flag) VALUES('$member_id','$food_id','$quantity_id','$total','$flag_0')";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: cart.php");
exit();
}else {
die("A problem has occured with the system " . mysql_error());
}
}
?>
Your code currently only gets ONE id from the url but in order to calculate the total for the whole cart you need all the ids in your cart. Usally they get saved to $_SESSION. You can view the inside of your session with this code: var_dump($_SESSION); It's also possible that the IDs are saved to the database to some kind of cart table. In your code I don't understand why you just get the first item from the quantities table. I'm pretty sure the table is somehow connected to the food table (I guess via food_id).
If you got the IDs from your session your code should look something like this (not testet because of sql statements):
<?php
$member_id = $_SESSION['SESS_MEMBER_ID']; //get member_id from session before the loop
$food_ids = array($id1, $id2, $id3); //you need all $food_id added to cart instead of just 1 from url, usally saved to $_SESSION
$grandTotal = 0;
foreach ($food_ids as $food_id) { //LOOP THROUGH IDs
//retrive quantity of food in cart from the quantities table
$quantities=mysql_query("SELECT * FROM quantities WHERE food_id='$food_id'") //there must be a connection between quantities and food so I added food_id="xxx"
or die("Something is wrong ... \n" . mysql_error());
$row=mysql_fetch_assoc($quantities);
$quantity_value = $row['quantity_value'];
//retrive food_price from food_details based on $food_id
$result=mysql_query("SELECT * FROM food_details WHERE food_id='$food_id'")
or die("A problem has occured ... \n" . "Our team is working on it at the moment ... \n" . "Please check back after few hours.");
$food_row=mysql_fetch_assoc($result);
$food_price=$food_row['food_price'];
//define default values for quantity(got from $row), total($food_price*$quantity_value), and flag_0
$quantity_id = $row['quantity_id'];
$total = $food_price*$quantity_value;
$grandTotal = $grandTotal + $total; //add total of this product to the $grandTotal from last time inside this loop
$flag_0 = 0;
//Create INSERT query
$qry = "INSERT INTO cart_details(member_id, food_id, quantity_id, total, flag) VALUES('$member_id','$food_id','$quantity_id','$total','$flag_0')";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: cart.php");
exit();
}else {
die("A problem has occured with the system " . mysql_error());
}
} /*Now you have $grandTotal calculated*/?>

Inserting into database, echo shows correct value, UPDATE multiplies it?

I want to update some entries in my database, basically I am counting the number of checkboxes that have been selected on the previous page and multiplying them with 25 then adding that value to the current value in the DB.
This is my code:
<?php
if($_POST['code_approve'])
{
for($i=0;$i<count($_POST['checkbox']);$i++)
{
$approval_id = $checkbox[$i];
$checkboxCount = count($_POST['checkbox']);
$countx25 = $checkboxCount * 25;
$sql = "UPDATE table SET status='approved', used='processed' WHERE id='$approval_id'";
$sql2 = "UPDATE members SET balance = balance+'$countx25'";
$result2 = mysql_query($sql2);
$result = mysql_query($sql);
}
if($result)
{
echo "$countx25";
}
}
?>
It seems, that for some reason it is multiplying $countx25 with the number of checkboxes before inserting it into MySQL. This if($result){echo "$countx25";}} always shows me the right value though.
If i select 1 it prints 25, 2 prints 50, 3 prints 75 and so on, but for the MySQL part, if i select 1 it adds 25 to current value, 2 adds 100, 3 adds 225 ?!
What's the error here ?
In your SQL query:
$sql2 = "UPDATE members SET balance = balance+'$countx25'";
You don't tell the database which row to update, so all rows are updated. While you test, you first test once, then again and again, so it might add to fields you don't expect it to. Probably this is your problem.
To specify which row to update, use a WHERE clause­Docs.
To prevent updating the same field more than once, execute the query only once.
As I stated in my comment. You are running this for each checkbox you get via $_POST. Why do you even use the for loop if you use count to count the checkboxes. Remove the for loop and it will work as you intend it to.
The for loop in your code is the problem. I guess here you are trying to use all checkboxes in the previous page, for your code you loop for all the checkboxes, so if there are 4 checkboxes, the for loop will run 4 times. So please identify what you want to do.
This is your code.
<?php
if($_POST['code_approve'])
{
for($i=0;$i<count($_POST['checkbox']);$i++)
{
$approval_id = $checkbox[$i];
$checkboxCount = count($_POST['checkbox']);
$countx25 = $checkboxCount * 25;
$sql = "UPDATE table SET status='approved', used='processed' WHERE id='$approval_id'";
$sql2 = "UPDATE members SET balance = balance+'$countx25'";
$result2 = mysql_query($sql2);
$result = mysql_query($sql);
}
if($result)
{
echo "$countx25";
}
}
?>

Keeping a counter

*Here is what I am trying to acheive: *
Basically I have a form where people can submit events to our database. In the CMS I have a page which displays a record of the number of events.
*Here is what I have: *
After the button is clicked, this script is called:
if($subject_type == 'Event') {
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
$querys = $this->tep_db_query($query);
$rows = $this->tep_db_fetch_array($querys);
extract($rows); //extract rows, so you don't need to use array
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
This works fine, however I cant seem to solve the next bit
This is the Problem
As you can see, it checks the database for the current month and adds it, this is providing that the sitename and that month are there, not a site and another month.
How would I get it to add the row in IF the sitename and month are not there?
I have been manually adding the months in now so that it works, and I am sure you can agree that's a ball ache.
Cheers peeps
if you want to check if site A + Month 11 exists do a select query against it and store the number of rows returned in a variable. ( $exists = mysql_num_rows("your query here"); )
then do an if statement against the $exists variable and proceed as you wish
if($exists) {
// update
} else {
// add
}
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$eventid = 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
}
}
this is what I have for the else statement there, however it will add one to the value if its there but will not add a new entry if its isnt.. ?
I don't see exactly how your method "checks the database for the current month and adds it "; I'll just assume that the tep_db_perform() method of your class handles this somehow.
(uhk! n00bed it; rest of the post was somehow chopped off?) Since you're already hitting the database with the select with the intent of using the data if a record is found, then you could use the resultset assigned to $rows as a means of checking if a record exists with SITENAME and Month.
See below:
if($subject_type == 'Event') {
// build query to check the database for sitename, month and year.
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
// Execute Query(wrapper for $result = mysql_query I guess?)
$querys = $this->tep_db_query($query);
// Get a resultset from database. --> you could merge this into one method with $this->tep_db_query
$rows = $this->tep_db_fetch_array($querys);
if(count($rows) > 0) {
extract($rows); //extract rows, so you don't need to use array --> I try to stay away from extract() as it makes for random variables being created.
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
} else {
// insert new record into database
// updated with code to execute insert SQL query.
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$result = $this->tep_db_query($query);
}
....
}
If I've misunderstood something, please let me know, happy to work through it with you.
Hope this helps. :)

Categories