Insert the next highest value in the database using php - php

Imagine I have a data in the database named warehouse and a whID for the warehouse number. In my add.php I have a form where when you click the submit button, it will add whID data higher than the whID number in the database without using auto increment. I'ved tried a few code for this but nothing works.
this is my code in add.php:
<form action="sidenav/function.php" method="post">
<button type="submit" name="submit" class="button">Add</button>
</form>
This is my code for the function of form in add.php:
if (!isset($_POST['submit'])) {
$insert = $conn->prepare("INSERT INTO warehouse (whID) VALUES (?)");
$insert->bind_param('i', $whNumber);
if ($insert->execute()) {
header('Location: ../warehouseList.php');
die();
}
Sorry for my bad English, I hope you understand my question. Thank you!

If you don't want to use auto-increment just get the highest id from database and increment it yourself.
Quick and dirty example:
$stmt = $conn->prepare("SELECT MAX(whID) as id FROM warehouse LIMIT 1");
$stmt->execute();
$row = $stmt->fetch();
$id = $row["id"] + 1;
Anyway I recommend you to use auto-increment on the id. That's a scenario for what it's created for.

Related

Why aren't the values from my form inserting into the database?

I have the following form:
<form id ="classadderform" action="formsubmit.php" method="POST">
<input type ="checkbox" name="note" value = "Note1"></input>
<input type="submit" value="Click Me" style="width:300px;">
</form>
Upon submit, the code redirects to formsubmit.php. Part of the code there is the following:
$db = new mysqli("sql...byethost8.com", "b8_163//....(database info));
$id = $_SESSION['id'];
.......
if(isset($_POST['note'])){
if($id){
$db->query("UPDATE answers SET WordLevel = 'Difficult' WHERE user_id=$id"); //<<<UPDATES SUCCESSFULLY
$notevalue=$_POST['note'];
$db->query("INSERT INTO answers (user_id, ValueColumn) VALUES ($id,'$notevalue')"); //<<<<<DOESN'T UPDATE
The WordLevel column updates successfully, but the value of the input named note does not insert into the column titled ValueColumn. This was working in my code a few days ago but it somehow stopped working. I tried different iterations of single quotes around $id and $notevalue but nothing seems to resolve the issue.
Any help would be much appreciated!
Execute and clear before the second query.
O you can try concating queries together using semicolon
$db->query("FIRST QUERY ; SECOND QUERY");
If you dont need the output of first query.
PDO multiple query
mysqli multiple query
might also help real_query

Run SQL Query with button click

Edit 3: I figured I should try to word, not only my issue but also my end goal better... so here it goes. I need data to be returned to the user by their input. What they put into the form, will return specific data from the database or nothing at all. The database I'm using is information on field reps. When the user enters into the form, they will be looking for specific information. The number they will be asked for will be the repID number. Now... the problem I am having is taking the number that is put into the form, and calling that specific data from the database. The user will not be able to see other data, not associated with other repID's.
Okay, I'm pretty sure I'm not supposed to just delete my entire initial post, but I'm still searching for an answer. Now, I would assume it should be relatively simple, however it has turned out to more taxing than I had originally thought. Perhaps I am not explaining my needs clear enough, I do tend to have that issue a lot.
Here it goes... How to Run sql Query with button click 2.0:
I have a database written in sql and stored on a server. The table I will be accessing is called dataRep and houses Rep Data. This data is user input via form submission. Upon coming to the website there is an option to "View Rep Information" by submitting the Rep's ID that was given. That Rep ID will be the auto increment repID from the table. Upon clicking the button, it opens a new window that should display the rep's data. It does not, however.
Here is the html the user will see:
<div class="pop_box">
<a class="rms-button" href="#popup1">Enter Rep Number Here</a> </div>
<div id="popup1" class="overlay">
<div class="popup">
<a class="close" href="#">×</a>
<div align="center"><br>
<br>
<p>Enter rep number in box below. Submission will open new window.</p>
<form method="get" action="/data/repPrepare.php" target="_blank" >
<input type="text" id="repSelect" name="repSelect" placeholder="Enter Rep Number Given Here" />
<button type="submit" class="newbutton">VIEW</button>
</form>
</div>
</div>
...changed the php a little, but now I get this error:
"Warning: mysqli_query() expects at least 2 parameters, 1 given on line 21
Unable to prepare statement: Query was empty"
<?php
$host = 'mhhost';
$user = 'myuser';
$pass = 'mypass';
$db = 'mydatabase';
$con = mysqli_connect($host,$user,$pass, $db);
//-------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$query = mysqli_query("SELECT * FROM dataRep WHERE repID = ?"); //query
$stmt = mysqli_prepare($con, $query)
or die("Unable to prepare statement: " . $con->error);
$stmt->bind_param("i", $_GET["repSelect"]);
$stmt->execute();
$array = mysqli_fetch_row($result); //fetch result
//-------------------------------------------------------------------------
// 3) echo result as json
//-------------------------------------------------------------------------
echo json_encode($array);
?>
I would like to apologize in advance if I'm totally messing up the procedure for the forum, its just I am truly stuck and have been dealing with this issue for two weeks. Once again, I would appreciate any assistance that can be provided. I just need the php to pull the data tied the repID that the user puts in the box (repSelect).
try like this. You have to print variables bind in bind_result().So
<?php
$stmt = $mysqli->prepare("SELECT repID, RepName, RepBio, RepCerts FROM dataRep WHERE repID = ?");
$stmt->bind_param('i', $_GET['repSelect']);
$stmt->execute();
$stmt->bind_result($repID, $repName,$repBio,$repCerts);
while($stmt->fetch()){
echo $repName;//now it prints RepName
};
$stmt->close();
?>

PHP refreshes the page before executing the query

I'm creating a webpage that loads a random product from one table (the "Products" table) from my database every time the page reloads. The logged in user (the user must be logged in) can choose to add that product to their personal favorites or not (stored in the "Favorites" table). Every time the user clicks the corresponding button to add that product to their favorites the webpage reloads and shows another new random item. The problem is that the webpage probably reloads before the query is executed, so the 'new' item is added to their favorites instead. Does anyone know how I can solve this? This is what I got so far:
HTML
<form method="get">
<button type="submit" name="like">
<img class="add-to-favorites" src="image.png">
</button>
</form>
PHP
header("Cache-Control: no-cache, must-revalidate");
session_start();
include_once 'dbconnect.php';
$user_id = ($_SESSION['user']);
$sSQLQuery = "SELECT product_id FROM Products ORDER BY RAND()";
$aResult = mysql_query($sSQLQuery);
$aRow = mysql_fetch_array($aResult, MYSQL_ASSOC);
$productid = $aRow['product_id'];
if(isset($_GET['like'])){
$SQL = "INSERT INTO Favorites(user_id,product_id)
VALUES('$user_id','$aRow[product_id]')";
$result = mysql_query($SQL);
}
Well, actually your PHP code only gets a random item and then saves it if the user clicked like. You should output the product ID on the form like this:
<form method="get">
<input type="hidden" name="current_product_id" value="<?php echo $productid; ?>">
<button type="submit" name="like">
<img class="add-to-favorites" src="image.png">
</button>
</form>
Where <?php echo $productid; ?> has the ID of the new random product.
Your PHP should go in this order and with these values:
if(isset($_GET['like'])){
$SQL = "INSERT INTO Favorites (user_id,product_id) VALUES ('$user_id','$_GET[current_product_id]')";
$result = mysql_query($SQL);
}
$sSQLQuery = "SELECT product_id FROM Products ORDER BY RAND()";
$aResult = mysql_query($sSQLQuery);
$aRow = mysql_fetch_array($aResult, MYSQL_ASSOC);
$productid = $aRow['product_id'];
So now, if you click on like, the $_GET['current_product_id'] will have the current product and then I output the new random product ID in the hidden input so that the next item works too!
Also: important, consider using mysqli_* functions instead of mysql_* functions because these last ones are deprecated :)
Your problem is that when the page refreshed, you first get new data from the Database and then save the old data - which is replaced by the new data.
Obviously you need to transfer the old product-id in the GET-Parameters. There are many options to do this, for example creating a hidden field.
echo "<input type=\"hidden\" name=\"oldProductId\" value=\"$productid\">
You can then access it when the page reloads with
$_GET['oldProductId']
and write it to the favorites-table.
Firstly, PDO... Always :P.
But to answer your question, you need to send the product_id along with $_GET['like'], so you know which product they selected. Since you're randomly selecting one from the database on every load.
In its current state, that is your best option.
But please consider moving to PDO especially since you mention logged in users and products.
How can I prevent SQL injection in PHP?
*Link credits to Sean (comment)

get ID of current inserted ID [duplicate]

This question already has answers here:
How can I make sure that PDO's lastInsertId() is not that of another simultaneous insert?
(2 answers)
Closed 7 years ago.
When you go to my website, i have a homepage with a button: Start enquete.
When you click that button, you will see the enquete.
In the meantime, when you clicked that button. A ID has been inserted in the database.
Index.php:
<form method="POST">
<input type="hidden" name="x">
<input type="submit" value="Go to enquete">
</form>
<?php
if(isset($_POST['x'])){
$test = $database->insert_user_id();
//header('Location: enquete/page1.php');
}
And the function:
function insert_user_id(){
$sql = "INSERT INTO user (user_id) VALUES (DEFAULT)";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $this->pdo->('user_id');
}
the return $this->pdo->('user_id'); is something i'm testing with!
Now my question is. How do i return the last inserted id from the table user.
I need to show it on the next page. (See //header).
I can't do this with a other query like: SELECT MAX ID or GetLastInsertId.
This becuase, when some one else also starts the enquete, he will have an other id all of the sudden.
How do i let the person keep the correct id.
Use PDO::lastInsertId
$this->pdo->lastInsertId();
Try this. Manual PDO::lastInsertId
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
You can easily do this by a Get method.
But you can also do this by slightly adjusting your code.
<form method="POST">
<input type="hidden" name="x">
<input type="submit" value="Go to enquete">
</form>
<?php
if(isset($_POST['x'])){
$id = $_POST['X'];
$test = $database->insert_user_id($id);
//header('Location: enquete/page1.php');
}
and change ur function to
function insert_user_id($id){
$sql = "INSERT INTO user (user_id) VALUES ('".$id. "')";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $this->pdo->('user_id');
}
Edit: i failed.
Check this link out http://php.net/manual/en/function.mysql-insert-id.php
If i understand you correctly you want the id of the row you just inserted into the database, and redirect the user to that one?
Index.php
if(isset($_POST['x'])){
$enqueteId = $database->insert_user_id();
header('Location: enquete/page1.php?id=' . $enqueteId);
}
Function:
function insert_user_id(){
$sql = "INSERT INTO user (user_id) VALUES (DEFAULT)";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $this->pdo->lastInsertId();
}
You can make use of PHP mysqli_insert_id() Function which returns the last inserted id of table
For more info go through the link below
http://www.w3schools.com/php/func_mysqli_insert_id.asp

php select to get a variable and then apply if else on it

I have a car rental system I am working on. When a user rents a car, the system should first check if the number of available cars is greater than 0, if yes, then make the adjustment "AVAILABLE = AVAILABLE+1" (in the MySQL table which keeps track of cars), which means, rent the car to the user. Also, I am trying to record which car went to which user. So I have another database table called rentalrecords which takes in the values of the Username of the logged in user, and ID of the car rented. Now, the problem is, my 'IF-ELSE' part is not executing as desired.
<div id="stylized" class="myform">
<form id="form" name="form" method="POST" action="renting.php" >
<h1>Rent a Car</h1>
<label>Car ID
<span class="small">eg. Enter 1 for Mer1</span>
</label>
<input type="text" name="ID" id="ID" />
<input type="submit" style="margin:30px 100px;" name="submit" value="Check-Out">
<div class="spacer"></div>
</form>
</div>
Now,the action of this form, which is renting.php, is as follows:
<?php
session_start();
if(!session_is_registered(theUSERNAME)){
header("location:customer_login.php");
}
mysql_CONNECT("xx", "xx", "xx") OR DIE("Unable to connect");
mysql_SELECT_DB("xx") OR DIE("Unable to select database");
$ID = $_POST['ID'];
$result = mysql_query("SELECT AVAILABLE FROM car WHERE ID='$ID'");
if(mysql_fetch_array($result)>0)
{
$query="UPDATE car SET AVAILABLE=AVAILABLE-1 WHERE ID='$ID'";
mysql_query($query);
$query = "insert into rentalrecords (USERNAME,ID,RENTED_ON) values ('$_SESSION[theUSERNAME]','$_POST[ID]',CURDATE())";
$result = mysql_query($query);
header("location: list_Clogged.php");
}
else
{
echo "<script>alert('The car you chose is currently unavailable!'); location.href='rent.php';</script>";
}
?>
Even though I have available=0, it still is NOT executing the else part and no matter what, it always executes the IF part. The ID and AVAILABLE are the attributes of my MySQL table called 'car' and the in rental records table i just want to insert these values. I am aware that the script is vulnerable to injection at the moment, but first I want to get things working! Any immediate help would be much appreciated.
You're trying to count a resource...
if(mysql_fetch_array($result)>0)
You need to obtain the results and then count an item within those results:
$res = mysql_fetch_assoc($result);
if($res[0]['AVAILABLE'] > 0)
Note $res[0] means first row of the results. You can also use mysql_fetch_row to obtain a single result.
Keep in mind, mysql_ functions shouldn't be used at all. Look into switching to mysqli or PDO.
Also, you need to sanitize input. You're just blindly accepting $_POST['ID']
The mysql_fetch_array function doesn't do what you think it does; it returns an array, not a single value.

Categories