Fail to update the data in database - php

I try to update the data in the database, but when I run the code, there is no error message appear, looks like its a logical error but I still don't have any clue about what is happening with my code.
Here is the code
<?php
include("conn.php");
SESSION_START();
if($_SESSION["loggedin"]!="true"&& $_SESSION['login'] != '')
header("location:login.php");
$aid = $_SESSION["usr"];
$result = mysql_query("select r.CustomerID from customer c inner join results r on r.CustomerID = c.CustomerID where c.Username = '".$aid."' ");
if (false === $result) {
echo mysql_error();
}
$row = mysql_fetch_assoc($result);
?>
<?php
if (isset($_POST["submitbtn"]))
{
$bookid = $_POST["bookid"];
$LP = $_POST["LP"];
$budget = $_POST["budget"];
$smokep = $_POST["SmokeP"];
$spreq = $_POST["sp_req"];
$query = mysql_query("UPDATE `results` SET LP = '$LP', budget = '$budget', SmokeP = '$smokep', sp_req = '$spreq'
WHERE results.BookID = '".$bookid."' and results.CustomerID = '".$result."'");
if (false === $query)
{
echo mysql_error();
}
?>
<script type = "text/javascript">
alert("Amendment Saved!!");
</script>
<?php
}
?>
Is the error coming from the select query? Or the if statement for the submitbtn went wrong?

First of all you cant put session start here
You must put it on the first line after open php tag
Second
update res='$ new_value' where ...
Tell me if it's not usefull to try another solution

Related

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 to send multiple json response in php back to ajax

<?php
session_start();
$conn =new mysqli("localhost","root","","registration");
$userid=isset($_POST['userid'])?$_POST['userid']:'';
//$re['success']=false;
$sql="call regtask2('$userid')";
$res=mysqli_query($conn,$sql);
$array = array();
if($res) {
while($row = mysqli_fetch_assoc($res))
{
$array[]=$row ;
$re['success']=true;
$re['userObj']['firstname'] = $row['firstname'];
}
}
else {
$re['success']=false;
}
if(isset($_SESSION['username']))
{
$sem=isset($_POST['sem'])?$_POST['sem']:'';
$fname=isset($_POST['fname'])?$_POST['fname']:'';
$year=isset($_POST['date'])?$_POST['date']:'';
$query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");
$re = array();
while ($row = mysqli_fetch_assoc($query))
{
print_r($row);
//$options['userObj'][]=$row;
}
}
echo json_encode ($re);
return;
?>
This is my full PHP code in this I need two json responses,
1> when I refresh the page
$sql="call regtask2('$userid')";
This query has to work and pass the response to the ajax, then I am using click button. When I use click button this query has to work and pass the response
$query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");
I this is poosible?
3 options:
Just split your php code. On refresh, load script1.php and for your other ajax call, load script2.php.
You will need to set identifiers for your calls. In your ajax, add an "is_submit=true" to the query. In your php, check that value.
Assign your return value to $return and return that.
It's simple just add second query result to your previous json !, also consider adding some validation into user input to prevent sql injection
getting userid from $_POST is really bad idea
<?php
session_start();
$conn =new mysqli("localhost","root","","registration");
$userid=isset($_POST['userid'])?$_POST['userid']:'';
//$re['success']=false;
$sql="call regtask2('$userid')";
$res=mysqli_query($conn,$sql);
$array = array();
$re = array();
if($res) {
$re['success']=true;
while($row = mysqli_fetch_assoc($res))
{
$array[]=$row ;
$re['userObj']['firstname'] = $row['firstname'];
}
}
else {
$re['success']=false;
}
if(isset($_SESSION['username']))
{
$sem=isset($_POST['sem'])?$_POST['sem']:'';
$fname=isset($_POST['fname'])?$_POST['fname']:'';
$year=isset($_POST['date'])?$_POST['date']:'';
$query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");
while ($row = mysqli_fetch_assoc($query))
{
$re['userObj'][]=$row;
//$options['userObj'][]=$row;
}
}
echo json_encode ($re);
return;
?>

PHP Variable Error When Selecting From Table

I have a blog where I'm selecting the articles from a database using PHP. The problem is that becuase of my search terms I'm hitting an error. Here is my code:
<?php
if(isset($_GET["cat"])){
$cat = $_GET["cat"];
}else{
$cat = "all";
};
?>
<?php
if($cat == "all"){
$cat_var = "";
}else{
$cat_var = "WHERE cat = '$cat'";
}; // NOTE THIS LINE
?>
<?php
if(isset($_GET["issue"])){$issue = $_GET["issue"];}else{
$issue = "all";
};
?>
<?php
if($issue == "all"){
$issue_var = "";
$limit = 4;
}
else{
$issue_var = "AND issue = '$issue'"; // NOTE THIS LINE
$limit = 200;
};
?>
<?php
$count_posts_sql = "SELECT id FROM articles $cat_var $issue_var"; // NOTE THIS LINE
$count_posts_res = mysqli_query($con, $count_posts_sql);
$num_init_posts = mysqli_num_rows($count_posts_res);
//If None, Then Exit
if($num_init_posts == 0){
header("Location: /home");
exit();
}
...
?>
So my url would be http://website.com/articles/all/2015-10, which is what I want. However $cat_var & $issue_var is causing the error because it's selecting:
SELECT * FROM articles AND issue = '2015-10' // NO WHERE STATEMEMT IS SHOWN
How do I overcome this error?
You could get this going by sticking a WHERE 1=1 in
$count_posts_sql = "SELECT id FROM articles WHERE 1=1 $cat_var $issue_var"; // NOTE THIS LINE
This is because you start off with an AND value = 1 without starting the WHERE clause, which creates an invalid query.
Then take the WHERE out of this line and replacing it with an AND:
$cat_var = "AND cat = '$cat'";
You can initialize your where query string like this:
$where = 'WHERE 1 = 1 ';
and for there after you can concatenate depending on your inputs.

Disable updating data when database is empty

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.

If MySQL Result Empty display a confirm box

I'm using some crazy mixture of PHP/JavaScript/HTML/MySQL
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
// Display a confirm box saying "Not everyone has entered a bid, continue?"
}
// If confirmed yes run more queries
// Else nothing
What is the best way to have this confirm box display, before completing the rest of the queries?
if($row != NULL) {
?>
<script>alert("not everyone has submitted their bid.");</script>
<?php
}
or
<?php
function jsalert($alert_message){
echo "<script type='text/javascript'>alert('".$alert_message."');</script>";
}
if($row!=null){
jsalert("Not everyone has submitted their bid.");
}
?>
You can't do this in 1 continuous block, as all of the PHP will execute before the confirm (due to server vs. client).
You will need to break these into 2 separate steps and have the client mediate between them:
part1.php:
<?php
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row != NULL) { ?>
<form id="confirmed" action="part2.php" method="post">
<noscript>
<label>Not everyone has entered a bid, continue?</label>
<input type="submit" value="Yes">
</noscript>
</form>
<script type="text/javascript">
if (confirm("Not everyone has entered a bid, continue?")) {
document.getElementById('confirmed').submit();
}
</script>
<?
} else {
include_once('part2.php');
}
?>
part2.php:
<?php
// assume confirmed. execute other queries.
?>
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
// more queries here
} else {
echo "<script>alert('Empty result');</script>";
}
Play with this code and you will get it to work eventually. I know you are not looking for just alertbox , instead you are looking for something like "yes or no" informational box. So check this out.
<?php
?>
<html>
<head>
<script type="text/javascript">
function displayBOX(){
var name=confirm("Not everyone has entered a bid, continue?")
if (name==true){
//document.write("Do your process here..")
window.location="processContinuing.php";
}else{
//document.write("Stop all process...")
window.location="stoppingProcesses.php";
}
}
</script>
</head>
<?php
$query = "SELECT * faculty SET submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
echo "<script>displayBox();</script>";
}
?>

Categories