Insert to database into two tables - php

This code really made me confused.
The first and second time I ran it, it worked perfectly but after that it stopped working
Let me explain it:
I work with 2 tables.
The first table I insert to it the current date, current time and the id of the user the id I take it from the session.
Which I believe works fine.
My problem is in the second table the error I get is the error i typed in the " print " after the second insert.
this is my code :
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['con_id'])) {
header("location: login.html");
exit();
}
$DB_USER ='root';
$DB_PASSWORD='';
$DB_DATABASE='';
$con= mysql_connect($DB_HOST ,$DB_USER , $DB_PASSWORD);
if (!$con) {
die('Failed to connect to server :'.mysql_error());
}
$db=mysql_select_db($DB_DATABASE);
if (!$db) {
die("unable to select database");
}
//first table
$qry="insert into shipment values('',NOW(),CURTIME(),'".$_SESSION['con_id']."');";
$resultop=mysql_query($qry);
//to take the id frome last insert because i need it in the second insert
$SNo=mysql_insert_id();
if ($resultop) {
$options=$_POST['op'];//this is the name of the check boxe's
if (empty($options)) {
header("location: manage_itemsE.php");}
// this is the second table .. my reaaal problem
$qun=$_POST['Quantit'];
$size =count($options);
for ($i =0; $i<$size; $i++) {
$qqry="insert into shipmentquantity values('".$options[$i]."','".$SNo."','".$qun[$i]."');"; // $options is array of the id's which i took from the checkbox's in the html ... $qun is array of the values i took form html ... i sure this is right ;)
$resultqun=mysql_query($qqry);
}
if ($resultqun) {
header("location: shipment_order.php");
}
else print "error in the Quantity";
}
else print "error in the shipmet";

Just add some debug statements to find out what is going wrong. Something like -
$resultqun = mysql_query($qqry) or print mysql_error();
You need to do some reading about SQL injection as this script is vulnerable. Checkout these pages on the use of prepared statements - PDO::prepare and mysqli::prepare
UPDATE - here is an example using PDO to interact with your db -
<?php
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['con_id'])) {
header("location: login.html");
exit();
}
$DB_USER ='root';
$DB_PASSWORD='';
$DB_DATABASE='';
$db = new PDO("mysql:dbname=$DB_DATABASE;host=127.0.0.1", $DB_USER, $DB_PASSWORD);
//first table
$qry = "INSERT INTO shipment VALUES(NULL, CURRENT_DATE, CURRENT_TIME, ?)";
$stmt = $db->prepare($qry);
$resultop = $stmt->execute(array($_SESSION['con_id']));
if(!$resultop){
print $stmt->errorInfo();
} else {
$SNo = $db->lastInsertId();
$options = $_POST['op'];//this is the name of the check boxe's
if (empty($options)) {
header("location: manage_itemsE.php");
exit;
}
// this is the second table .. my reaaal problem
$qun = $_POST['Quantit'];
$size = count($options);
$stmt = $db->prepare("INSERT INTO shipmentquantity VALUES(?, ?, ?)");
for($i = 0; $i < $size; $i++) {
$resultqun = $stmt->execute(array($options[$i], $SNo, $qun[$i]));
}
if($resultqun) {
header("location: shipment_order.php");
} else {
print $stmt->errorInfo();
}
}

What is your primary key for the 'shipmentquantity' table? It looks like you are trying to enter two values of '3' for the primary key and that's where it's going awry.
DESCRIBE `shipmentquanitity`

Related

How to update status in database if status is empty without submitting a form in php?

How to update a status from database if status is empty in using php? I have this condition in php. I have this if condition that decides if $getstatus is empty it will update from database to Avail. I tried refreshing the page after querying the database. But it will not update in database. Is there anyway to update this without using form submit in php?
<?php
session_start();
include "includes/connection.php";
// Display all parking slots
$sql = $connection->prepare('SELECT * FROM parkingslot where parkingslotid = 1');
$sql->execute(); // execute query
$result = $sql->get_result(); // fetch result
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getstatus = $row["status"];
echo $getstatus;
}
}
if (empty($getstatus)) {
$sql = $connection->prepare("UPDATE parkingslot SET status = 'Avail' where parkingslotid = 1 ");
}
?>
Codes in connection for connecting to database
connection.php
<?php
$server = "localhost";
$username = "root";
$password = "";
// create connection
$connection = mysqli_connect($server,$username,$password);
// check connection
if(!$connection)
{
die("No connection found." . mysqli_connect_error());
}
else {
// select a database
$select_db = mysqli_select_db($connection,'smartparkingsystem');
if(!$select_db)
{
$sql = 'CREATE DATABASE sample';
// create database if no db found
if(mysqli_query($connection,$sql)) {
echo "Database Created";
}
else {
echo "Database not found" . mysqli_connect_error() . '\n';
}
}
else {
// Database already existed
// do nothing...
}
}
?>
If I understand your goal of: For row(s) whereparkingslotid=1 - Update status to 'Avail' but only if status is not currently set, this might help:
<?php
session_start();
include "includes/connection.php";
$connection->prepare("UPDATE `parkingslot` SET `status`=? WHERE `parkingslotid`=? AND (`status` IS NULL OR `status`=?)");
$connection->bind_param("sis", $status, $parkingslotid, $empty_str);
$status = 'Avail';
$parkingslotid = 1;
$empty_str = '';
$connection->execute();
echo $connection->affected_rows.' rows affected';
$connection->close();
?>
This saves a bit of processing by not checking with PHP first.
You can use this query:
"UPDATE parkingslot SET status = 'Avail' where status IS NULL OR status = '' "
Edited:
#lumonald gave the right anwser in the comment. You're not executing your second SQL statement.

store MySQL SELECT result in php variable using Prepared statements

I am trying to user prepared statements to find a user record and store the users ID in a php variable to use later on. I would like to echo the variable contents. How do I check the result using Prepared statements?
My CODE:
if ((isset($_POST['overrideUsername'])) and (isset($_POST['overridePassword'])) and (isset($_POST['overrideUniqueID']))) {
$overridePasswordInput = $_POST['overridePassword'];
$overrideUsernameInput = $_POST['overrideUsername'];
$roleID = '154';
$overrideUniqueID = $_POST['overrideUniqueID'];
//Not sure how to properly compare stored passwords vs password given by user...
$overridePassword = mysqli_real_escape_string($overridePasswordInput);
$overrideUsername = mysqli_real_escape_string($overrideUsernameInput);
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql1 = "SELECT users.id FROM users WHERE (users.login = ?) AND (users.password = ?)";
$stmt1 = $conn->prepare($sql1);
$stmt1->bind_param('ss', $overrideUsername, $overridePassword);
$stmt1->execute();
$stmt1->bind_result($userID);
$stmt1->get_result();
if ($stmt1->get_result()) {
echo $userID;
} else {
echo 'User credentials incorrect. Please try again';
}
$stmt1->close();
//Close the Database connection.
$conn->close();
}//End If statement
Further more, this is the pre-existing code the original programmer used to authenticate users into the program:
if(!defined("noStartup")){
$scriptname = basename($_SERVER["PHP_SELF"]);
$phpbmsSession = new phpbmsSession;
//Testing for API login
if(strpos($scriptname,"api_")!==false){
if(isset($_POST["phpbmsusername"]) && isset($_POST["phpbmspassword"])){
$phpbmsSession->loadDBSettings();
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
include_once("common_functions.php");
$phpbmsSession->loadSettings($sqlEncoding);
$phpbms = new phpbms($db);
if(!$phpbmsSession->verifyAPILogin($_POST["phpbmsusername"],$_POST["phpbmspassword"],ENCRYPTION_SEED))
$error = new appError(-700,"","Login credentials incorrect",true,true,true,"json");
} else
$error= new appError(-710,"","No login credentials passed",true,true,true,"json");
} else {
$phpbmsSession->loadDBSettings($sqlEncoding);
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
$phpbmsSession->loadSettings($sqlEncoding);
include_once("common_functions.php");
$phpbms = new phpbms($db);
if(!isset($noSession))
$phpbmsSession->startSession();
if (!isset($_SESSION["userinfo"]) && $scriptname != "index.php") {
if(isset($loginNoKick)){
if(!isset($loginNoDisplayError))
exit();
} else{
goURL(APP_PATH."index.php");
}
}
}
$db->stopOnError=true;
}//end if
And the verifying function:
function verifyAPIlogin($user,$pass){
$thereturn=false;
$this->db->stopOnError = false;
$querystatement = "SELECT id, firstname, lastname, email, phone, department, employeenumber, admin, usertype
FROM users
WHERE login!=\"Scheduler\" AND login=\"".mysql_real_escape_string($user)."\"
AND password=ENCODE(\"".mysql_real_escape_string($pass)."\",\"".mysql_real_escape_string(ENCRYPTION_SEED)."\")
AND revoked=0 AND portalaccess=1";
$queryresult = $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-720,"","Error retrieving user record",true,true,true,"json");
return false;
}
if($this->db->numRows($queryresult)){
//We found a record that matches in the database
// populate the session and go in
$_SESSION["userinfo"]=$this->db->fetchArray($queryresult);
$querystatement="UPDATE users SET modifieddate=modifieddate, lastlogin=Now() WHERE id = ".$_SESSION["userinfo"]["id"];
$queryresult=# $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-730,"","Error Updating User Login Time",true,true,true,"json");
} else
$thereturn=true;
}
return $thereturn;
}
}//end loginSession class
NOTE: I have already tested that my $_POST() values are successfully coming through to my script.
EDIT:: added more code to give a better overall picture of what I'm attempting to do. Any shared tuturials on password encryption/authenticating users would be greatly appreciated.
Thank you!
As I mentioned in the comment, PHP now has a couple built in methods to handle encryption and decryption of passwords that you might find helps solve your problem:
password_hash and
password_verify

PHP SQL Query Fails to Execute

<?php
$db = new mysqli("localhost", "HIDDEN", "HIDDEN", "HIDDEN");
if ($db->connect_error) {
die("Failed to connect.");
}
if (isset($_POST["title"]) && isset($_POST["description"]) && isset($_POST["url"])) {
$title = $db->real_escape_string($_POST["title"]);
$description = $db->real_escape_string($_POST["description"]);
$url = $db->real_escape_string($_POST["url"]);
$sql = "INSERT INTO video (name, description, submission_date)
VALUES ('{$title}', '{$description}', CURDATE());
INSERT INTO video_source (video_id, url)
VALUES (LAST_INSERT_ID(), '{$url}');";
if ($db->query($sql) === TRUE) {
echo "Successfully added.";
} else {
echo "Query failed.<br><br>Data: {$title} {$description} {$url}";
}
} else {
echo "Data not set.";
}
$db->close();?>
Outputs "Query failed." with the data I entered. Replacing variables such as title with constants still has the same problem. I tried the query in PHPMyAdmin and it worked fine (with constants).
It seems to be unhappy with setting the value of video_id.
Anytime you're running multiple queries with MySQLi you should use multi_query():
$db->multi_query($sql)
In addition, LAST_INSERT_ID() in your second query is not returning any sort of value. If you're looking for the last inserted value of the 1st query you have to return that prior to running the second query.

Update query not working using PDO

I tried updating my data like so but it doesn't work
<?php
require("config.inc.php");//this piece of code us for authentication and it works fine.
if(!empty($_POST))
{
/**
the values below in the POST are valid not empty values
**/
$shell = $_POST['shell'];
$reporter = $_POST['reporter'];
//query
$query = "UPDATE `shellingdb`
SET `likes` = `likes` + 1
WHERE `shell` = :shell AND `reporter` = :reporter";
try {
$query_params = array(':shell' => $_POST['shell'], ':reporter' => $_POST['reporter']);//Updates likes
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$affected = $stmt->rowCount();//counts the number of affected rows during the update query
if($affected > 0)
{
$response["success"] = 1;
$response["message"] = "Updated! this number of rows were affected".$affected;
echo json_encode($response);
}else
{
$response["success"] = 2;
$response["message"] = "Not Updated! huh!".$affected;
echo json_encode($response);
}
}
catch (Exception $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!".$ex->getMessage();
die(json_encode($response));
}
}
?>
the config.inc.php
<?php
// These variables define the connection information for your MySQL database
$username = "xmnj3jh0jhtheu_14265914";
$password = "jhikjskjiavethew";
$host = "sqlkjnlkkjlk101.x3kuhiu0lkj.us";
$dbname = "x3lnklj0u_1426jbkb5914_gbabbjkhjajhlert";
// UTF-8 is a character encoding scheme that allows you to conveniently store
// a wide varienty of special characters, like � or �, in your database.
// By passing the following $options array to the database connection code we
// are telling the MySQL server that we want to communicate with it using UTF-8
// See Wikipedia for more information on UTF-8:
// http://en.wikipedia.org/wiki/UTF-8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// A try/catch statement is a common method of error handling in object oriented code.
// First, PHP executes the code within the try block. If at any time it encounters an
// error while executing that code, it stops immediately and jumps down to the
// catch block. For more detailed information on exceptions and try/catch blocks:
// http://us2.php.net/manual/en/language.exceptions.php
try
{
// This statement opens a connection to your database using the PDO library
// PDO is designed to provide a flexible interface between PHP and many
// different types of database servers. For more information on PDO:
// http://us2.php.net/manual/en/class.pdo.php
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
// If an error occurs while opening a connection to your database, it will
// be trapped here. The script will output an error and stop executing.
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code
// (like your database username and password).
die("Failed to connect to the database: " . $ex->getMessage());
}
// This statement configures PDO to throw an exception when it encounters
// an error. This allows us to use try/catch blocks to trap database errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This statement configures PDO to return database rows from your database using an associative
// array. This means the array will have string indexes, where the string value
// represents the name of the column in your database.
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// This block of code is used to undo magic quotes. Magic quotes are a terrible
// feature that was removed from PHP as of PHP 5.4. However, older installations
// of PHP may still have magic quotes enabled and this code is necessary to
// prevent them from causing problems. For more information on magic quotes:
// http://php.net/manual/en/security.magicquotes.php
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.
?>
don't know what's wrong and it gives no error it goes into the else statement, meaning the values were not updated. i tried the same code in sqlfiddle and it works but not in my PhpMyAdmin.
I know the updated value is supposed to be passed into the $query_params but am incrementing the value of likes each time it is run, and am not sure how to do that in the $query_params unless i use a seperate query to get the numberof likes and then increament it but that could be costly.
Query without PDO still it does not work this time it give update unsuccessful
<?php
$username = "x3jbhiukhkj0u426jbhjnbvh591mbhb4";
$password = "savjiuejbiuhilkmthljiew";
$host = "sqlnjhbjhnkjjjhbj";
$dbname = "x3hjbh0ukjioiuhgbjhvhgvh";
$shell = "Rustig";
$reporter = "davies";
//query
$query = "UPDATE `shellingdb`
SET `favs` = 1
WHERE `shell` = 'Rustig'";
$link = mysql_connect($host, $username, $password);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}else
{
echo 'Connected successfully';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected)
{
die ('Can\'t use foo : ' . mysql_error());
}else
{
echo 'Connected to database successfully';
if(empty($_POST))
{
$retval = mysql_query( $query, $link )or die(mysql_error($link));;
if(! $retval )
{
die('Could not query database: ' . mysql_error());
}else
{
if(mysql_affected_rows() > 0)
{
echo "Updated data successfully\n";
}else
{
//echo "shell=".$shell." reporter=".$reporter';
echo "Updated data Unsuccessfully\n";
}
}
}
}
}
mysql_close($link);
?>
The below is the output of the PDOStatement::debugDumpParams(); for the first php syntax
SQL: [124] UPDATE shellingdb SET likes = likes + 1 WHERE shell = :shell AND reporter >= :reporter Params: 2 Key: Name: [6] :shell paramno=-1 name=[6] ":shell" is_param=1 param_type=2 Key: Name: [9] :reporter paramno=-1 name=[9] ":reporter" is_param=1 param_type=2
I used bindParam. bindParam is a method on PDOStatement.
Try:
<?php
require("config.inc.php");//this piece of code us for authentication and it works fine.
if(isset($_POST))
{
/**
the values below in the POST are valid not empty values
**/
$shell = $_POST['shell'];
$reporter = $_POST['reporter'];
//query
$query = "UPDATE `shellingdb`
SET `likes` = `likes` + 1
WHERE `shell` = :shell AND `reporter` = :reporter";
try {
$stmt = $db->prepare($query);
$stmt->bindParam(":shell", $shell);
$stmt->bindParam(":reporter", $reporter);
$stmt->execute();
$affected = $stmt->rowCount();//counts the number of affected rows during the update query
if($affected > 0)
{
$response["success"] = 1;
$response["message"] = "Updated! this number of rows were affected".$affected;
echo json_encode($response);
}else
{
$response["success"] = 2;
$response["message"] = "Not Updated! huh!".$affected;
echo json_encode($response);
}
}
catch (Exception $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!".$ex->getMessage();
die(json_encode($response));
}
}
?>
some how, after long hours of try and error(Brut Forcing) this finally worked
$query = "UPDATE `shellingdb` SET `likes`=`likes`+1 WHERE `shell` = :shell AND `reporter` = :reporter";
Thanks all those who tried to help. :)

Refresh PHP page once only when called

I have a php which would check for certain value if it exists in a mysql database. If the value does not exists, it would simply add the value and refresh the page once to load the page again and now it has a value in the database, would go ahead to add other values. How do I refresh page just once when it is called ?
<?php
$sname = "W3 schools C# tutorials";//$_POST["sitename"];
$stype = "C#";//$_POST["sitetype"];
$saddy = "www.w3schools.com";//$_POST["siteaddress"];
$scomm = "W3 schools C# tutorials";//$_POST["sitecomment"];
$conn = mysql_connect("localhost","root","password");
if(!$conn){
die("Could not connect: ".mysql_error());
} else {
mysql_select_db("bookmarks",$conn);
$rs = mysql_query("select TypeId from bookmarktypes where TypeName = '$stype'");
$row = mysql_fetch_array($rs);
if($row > 0 ){
//Data found, continue to add...
} else {
//No data... insert a valid one
$rs = mysql_query("insert into bookmarktypes (TypeName) values ('$stype')");
if (!$rs){
die('Error: ' . mysql_error());
} else {
//echo "inserted new type data...";
}
//echo "</html>";
}
}
mysql_close($conn);
//Refresh page once
?>
There's the comment to refresh page below after mysql close command.
Refresh it right after insert with
header('Location: url here');
exit;
Btw, read a little about sql injections
Also - mysql_close() is pointless there.
if(check=1)
{
echo "\"<meta http-equiv=\"refresh\" content=\"2;url=http://yourwebsite.com/\">\"\n";
}
if you need to print the data that you just have entered try this
header('Location: YourShowDataPage.php?id='.$_POST['id_dataEntered'])
mi apologizes if is wrong , im a begginer

Categories