Disable updating data when database is empty - php

I am having a problem when I want to echo "The stock is less than what you want". The problem is the user still can update the cart when the stock in my database less that what the user wants. It should show an error "The stock is less than what you want".
This is my code.
<?php session_start();
require("config.php");
$user = $_SESSION['userlogin'];
$cek = mysql_query("SELECT * FROM transaksitbl WHERE username = '$user' AND status ='0'") or die(mysql_error());
$result = mysql_num_rows($cek);
$data = mysql_fetch_array($cek);
if ($result > 0)
{
$faktur =$data['notransaksi'];
for ($i=1; $i<=$_POST['n']; $i++)
{
$idp = $_POST['id'.$i];
$cari2 = mysql_query("SELECT * FROM barangtbl WHERE id='$idp'") or die(mysql_error());
$row2 = mysql_fetch_array($cari2);
$har = $row2['harga'];
$stock = $row2['stock'];
if($_POST['n'] <= $row2['stock'])
{
echo "The stock is less than what you want";
}
if ($cari2)
{
$jmlubah = $_POST['jumlah'.$i];
$beratnew = $jmlubah*$row2['berat'];
$totubah = $jmlubah*$har;
$query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah
WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
}
}
}
header ("location:shopping_cart.php");
?>

If i understood you properly the
if($cari2){}
function is executing?
All you are checking there is if the $cari2 variable is true.
Simply make a else statement out of the if($cari2){} statement so that if the stock is less than you wan't the second if statement won't get executed.
So, like this:
if($_POST['n'] <= $row2['stock']){
echo "The stock is less than you want";
}
else {
if($scari2){
$jmlubah = $_POST['jumlah'.$i];
$beratnew = $jmlubah*$row2['berat'];
$totubah = $jmlubah*$har;
$query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah
WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
} else {
die('Woop, there seems to be a problem with the $scari2 variable. The value is:' . $scari2);
} // END OF INNER ELSE
} // END OF ELSE
And one more thing NEVER forget to use the mysql_real_escape_string() function on a variable before submiting it's value to the database.

Related

how to avoid duplicate data with php

How do I avoid duplicate data when we enter the same data again? instead, I want to issue a warning:
sorry your username has been used
I'm using php script, I have done it to overcome duplicate data but the results have unexpected errors.
This is my code, please correct it if you wish. thanks
<?php
if (isset($_POST['submit'])) {
$npm_siswa = $_POST['npm_siswa'];
$nama_siswa = $_POST['nama_siswa'];
$bidangst_siswa = $_POST['bidangst_siswa'];
$ipk_siswa = $_POST['ipk_siswa'];
$query ="INSERT INTO class(npm_siswa, nama_siswa, bidangst_siswa, ipk_siswa) VALUES('$npm_siswa','$nama_siswa','$bidangst_siswa','$ipk_siswa')";
$insert_data = mysqli_query($con, $query);
$goto = header('location: input_data.php');
if (headers_sent($goto) == true) {
exit();
}
}
$checking = "SELECT * FROM class WHERE npm_siswa ='$npm_siswa'";
$process = mysqli_query($con, $checking) or die(mysqli_error());
while($row_filter = mysqli_fetch_assoc($process)) {
$kelasId = $row_filter['kelasId'];
$npm_siswa = $row_filter['npm_siswa'];
$nama_siswa = $row_filter['nama_siswa'];
$bidangst_siswa = $row_filter['bidangst_siswa'];
$ipk_siswa = $row_filter['ipk_siswa'];
}
if (mysqli_num_rows($process) > 0) {
echo "maaf nama anda sudah digunakan";
} else {
$data = "INSERT INTO class(npm_siswa, nama_siswa, bidangst_siswa, ipk_siswa) VALUES('$npm_siswa','$nama_siswa','$bidangst_siswa','$ipk_siswa')";
$check = mysqli_query($con, $data);
}
?>
The easy way is to first select rows from mysql using a select statement, and then check if the array is empty.
$checking = "SELECT * FROM class WHERE npm_siswa ='$npm_siswa'";
$process = mysqli_query($con, $checking) or die(mysqli_error());
if(empty($process)) {
echo "maaf nama anda sudah digunakan";
} else {
$data = "INSERT INTO class(npm_siswa, nama_siswa, bidangst_siswa, ipk_siswa) VALUES('$npm_siswa','$nama_siswa','$bidangst_siswa','$ipk_siswa')";
$check = mysqli_query($con, $data);
}
Another solution: make sure that it is the DBMS that controls the uniqueness, with a UNIQUE constraint. Then test your mysqli_query's return value to handle the error.
$process = mysqli_query($con, $checking);
if (!$process)
{
// Handle your error
}
Pros : Only one query
Cons : The error is not necessarily due to the UNIQUE constraint

php 5.3 page not compatible/working on BlueHost servers which have php 4.3?

I have the following teachers.php page, developed by a freelancer. He says it works on his localhost and he is using php 5.3, but the only reason it doesn't work when we upload it to our servers, and BlueHost has v.4.3 is because of the older version.
I am awaiting a response on how he can resolve this, assuming he will say he can, but would be interested in any responses/suggestions/solutions.
What is causing the error (what lines of code) and what are the best solutions to get around this?
the page in question does some teacher tracking:
The start of the code in the page is as follows:
<?php
require_once("scripts/connect_db.php");
session_start();
if(!isset($_SESSION['teacher'])) header('Location: teacher_login.php');;
$result="";
if (isset($_POST["logout"])) {
session_destroy();
header('Location:index.php');
}
$err = "";
if (isset($_POST["add_class"]) && !empty($_POST['class_names']) && $_SESSION['teacher']) {
$class_name = mysqli_real_escape_string($con,$_POST['class_names']);
$school_pin = $_SESSION['teacher_school_pin'];
$teacher_username = $_SESSION['teacher_username'];
$teacher_id = $_SESSION['teacher_id'];
$query = mysqli_query($con,"INSERT INTO classes (teacher_username, teacher_id,school_pin, class_name)
VALUES('$teacher_username','$teacher_id', '$school_pin', '$class_name')");
}
if (isset($_POST["track_button"])) {
$var = mysqli_real_escape_string($con,$_POST['user_name']);
$quiz = #mysqli_real_escape_string($con,$_POST['quiz']);
$school_pin = mysqli_real_escape_string($con,$_POST['school_pin']);
$class_name = #mysqli_real_escape_string($con,$_POST['class_name']);
$top = #mysqli_real_escape_string($con,$_POST['top']);
$array_one = comma_separated_to_array($var);
$query = array();
if($quiz != "non"){
array_push($query," quiz_id=".$quiz." ");
}
if(count($array_one) != 0){
array_push($query," username IN ('".implode("','",$array_one)."') ");
}
if(!empty($class_name)){
if($class_name !== "all"){
array_push($query," class_name='".$class_name."' ");
}
}
if(!empty($school_pin)){
array_push($query," school_pin='".$school_pin."' ");
}
if($quiz == "non"){
$result = mysqli_query($con,"SELECT DISTINCT username FROM quiz_takers WHERE ".implode(" AND ",$query)." ORDER BY percentage DESC LIMIT ".$top);
if(!$result)$err = "Enter Your student data to Track, Please!";
}else{
$result = mysqli_query($con,"SELECT * FROM quiz_takers WHERE ".implode(" AND ",$query)." ORDER BY percentage DESC LIMIT ".$top);
if(!$result)$err = "Enter Your student data to Track, Please!";
}
if(#mysqli_num_rows($result) == 0){
$err = "No Result Found!";
}
}
$all_classes = mysqli_query($con,"SELECT class_name FROM classes WHERE teacher_username='".$_SESSION['teacher_username']."'");

How can I insert a value to DB by matching variable in url?

I have a two forms from one form. I can sucessfully store the data to database.when that form submitted user will directed to the second form. I am passing variable $uniqueid in the url from first form to second form. But, when I tried stored the data of the second form into the database that relevant to the same user its not stored.
I want to store mobile number of the user from second page.databse column also mobile number.
This is my code
<?php
include_once 'dbconnect.php';
$a = $_GET['uniquekey'];
if(isset($_POST['btn-signup']))
{
$mobilenumber = $_POST['mobilenumber'];
$xxx = mysql_query("SELECT * FROM who WHERE uniquekey = '$a'")or die(mysql_error());
$yyy = mysql_fetch_row($xxx);
if(mysql_num_rows($xxx) > 0) {
$aaa = mysql_query("INSERT INTO who(mobilenumber) VALUES('$mobilenumber')");
}
else{
echo 'wrong';
}
}
?>
$xxx = mysql_query("SELECT * FROM who WHERE uniquekey = '$a'")or die(mysql_error());
$yyy = mysql_fetch_row($xxx);
if(mysql_num_rows($xxx) > 0) {
$aaa = mysql_query("UPDATE who setmobilenumber='$mobilenumber' where uniquekey = '$a' ");
}
else{
echo 'wrong';
}
Here you can use update query for update user mobile number.
include_once 'dbconnect.php';
$a = $_GET['uniquekey'];
if(isset($_POST['btn-signup']))
{
$mobilenumber = $_POST['mobilenumber'];
$xxx = mysql_query("SELECT * FROM who WHERE uniquekey = '$a'")or die(mysql_error());
$yyy = mysql_fetch_row($xxx);
if($yy>0)
{
$update="update who set mobilenumber=$mobilenumber where uniquekey='$a'";
$query=mysql_query($update);
}
else
{
echo "wrong";
}
}

how can i display sql query in php? CLOSED

<?php
include 'config.php'; //connect to db
if(isset($_REQUEST["pwd"]) && isset($_REQUEST["name"])) {
$password = $_REQUEST['pwd']; //pass from previous page
$name = $_REQUEST['name']; //pass from previous page
$checkUserPass = mysql_query("SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'", $conn); //check if the user exist
if(mysql_num_rows($checkUserPass) == 1) {
$personnelId = mysql_query("SELECT PersonnelID FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'", $conn); //query user id
while($row = mysql_fetch_assoc($personnelId)) {
echo $row['PersonnelD']; // print user id
}
mysql_close($conn);
//echo "<br/><br/>";
//echo "<script>alert('Logged In.')</script>";
//header("Refresh: 1; url=profile/profile.php?id="'.$id.');
//header('Refresh: 1; url=test.php?id=$personnelId');
} else {
echo "<br/><br/>";
echo "<script>alert('Wrong Password.')</script>";
header('Refresh: 1; url=personnelselect.php');
}
}
?>
i cannot echo the $row['PersonnelD'] the page shows blank. i cannot understand where did i go wrong. this page quesion have been solved
Looks like you have mistake in code:
echo $row['PersonnelD'];
shouldn't it be following?
echo $row['PersonnelID'];
check the mysql_fetch_assoc() function may be its parameter is empty so it can't enter the while loop
Try to debug and check the values came in the variables using var_dump() function. Ex: var_dump($row); in while loop.
In both your querys, you have
"SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'"
It should be:
"SELECT * FROM validPersonnel WHERE Passkey = '".$password."' and Name = '".$name."';"
PHP doesn't recognize the $var unless you close the quotes. The period adds the $var to the string.

PHP Validating Submit

I'm working on a project where a user can click on an item. If the user clicked at it before , then when he tries to click at it again it shouldn't work or INSERT value on the DB. When I click the first item(I'm displaying the items straight from database by id) it inserts into DB and then when I click at it again it works(gives me the error code) doesn't insert into DB. All other items when I click at them , even if I click for the second, third, fourth time all of it inserts into DB. Please help guys. Thanks
<?php
session_start();
$date = date("Y-m-d H:i:s");
include("php/connect.php");
$query = "SELECT * FROM test ORDER BY `id` ASC LIMIT 3";
$result = mysql_query($query);
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$submit = mysql_real_escape_string($_POST["submit"]);
$tests = $_POST["test"];
// If the user submitted the form.
// Do the updating on the database.
if (!empty($submit)) {
if (count($tests) > 0) {
foreach ($tests as $test_id => $test_value) {
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
if ($match == $test_id) {
echo "You have already bet.";
} else {
switch ($test_value) {
case 1:
mysql_query("UPDATE test SET win = win + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 'X':
mysql_query("UPDATE test SET draw = draw + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 2:
mysql_query("UPDATE test SET lose = lose + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
default:
}
}
}
}
}
echo "<h2>Seria A</h2><hr/>
<br/>Welcome,".$username."! <a href='php/logout.php'><b>LogOut</b></a><br/>";
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
echo "<br/>",$id,") " ,$home, " - ", $away;
echo "
<form action='seria.php' method='post'>
<select name='test[$id]'>
<option value=\"\">Parashiko</option>
<option value='1'>1</option>
<option value='X'>X</option>
<option value='2'>2</option>
</select>
<input type='submit' name='submit' value='Submit'/>
<br/>
</form>
<br/>";
echo "Totali ", $sum = $win+$lose+$draw, "<br/><hr/>";
}
} else {
$error = "<div id='hello'>Duhet te besh Log In qe te vendosesh parashikime ndeshjesh<br/><a href='php/login.php'>Kycu Ketu</a></div>";
}
?>
Your problem is here :
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
You are not checking it correctly. You have to check if the entry in match_select exists for the user_id and the match_id concerned. Otherwise, $match would always be equal to the match_id field of the last inserted row in your database :
$match = "SELECT *
FROM `match_select`
WHERE `user_id` = '<your_id>'
AND `match_id` = '$test_id'";
$matchResult = mysql_query($match)or die(mysql_error());
if(mysql_num_rows($matchResult)) {
echo "You have already bet.";
}
By the way, consider using PDO or mysqli for manipulating database. mysql_ functions are deprecated :
http://www.php.net/manual/fr/function.mysql-query.php
validate insertion of record by looking up on the table if the data already exists.
Simplest way for example is to
$query = "SELECT * FROM match_select WHERE user_id = '$user_id'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// do not insert
}
else
{
// do something here..
}
In your form you have <select name='test[$id]'> (one for each item), then when you submit the form you are getting $tests = $_POST["test"]; You don't need to specify the index in the form and can simply do <select name='test[]'>, you can eventually add a hidden field with the id with <input type="hidden" value="$id"/>. The second part is the verification wich is not good at the moment; you can simply check if the itemalready exist in the database with a query

Categories