Session ID changes on saved to DB - php

I have this small problem on Session. Ill show you the codes below.
//checking session orderid if not created
$setSession = $_SESSION['neworderid'];
if (empty($setSession)) {
$neworderid = mt_rand(1000000000, 9999999999);
$_SESSION['neworderid'] = $neworderid;
}
//check if order_id exists in the database
$db->setQuery("SELECT * FROM mn_orderitems WHERE order_id =" . $_SESSION['neworderid']);
$query = $db->loadResult();
if (!empty($query)) {
//if exists, do nothing
echo 'Not Empty';
} else {
//if order id doesn't exist, save the new order item
$qry = "INSERT INTO mn_orderitems (order_id, product_id, orderitem_name, orderitem_quantity, orderitem_price, orderitem_final_price) VALUES
('" . $_SESSION['neworderid'] . "', '" . $item->product_id . "', '" . $item->orderitem_name . "', '" . $item->orderitem_quantity . "', '" . $item->orderitem_price . "', '" . $item->orderitem_final_price . "')";
$result = mysql_query($qry);
if (!$result) {
echo "Error";
} else {
echo "Saved";
}
echo 'Empty';
}
Problem:
"When I try to echo the $_SESSION['neworderid']; it outputs = 8152269414
But when it is being save to database the order_id changes to 2147483647".
This only happens in live server. No problem in my localhost Apache.

The problem you are having is not with the PHP script itself, but your database structure. In MySQL the biggest number you can store (declared as INT) is 2147483647. If you want to store bigger numbers, you'll have to either change the script to generate a lower number OR change the DB to use BIGINT.

Change first order_id's structure in phpMyAdmin from INT into BIGINT
/* checking session orderid if not created */
session_start();
if (empty($_SESSION['neworderid'])) {
$neworderid = mt_rand(1000000000, 9999999999);
$_SESSION['neworderid'] = $neworderid;
$setSession = $_SESSION['neworderid'];
}
else {
$setSession = $_SESSION['neworderid'];
}
/* check if order_id exists in the database and convert the code to mysqli */
/* have your connection store into $db variable */
$result=mysqli_query($db, "SELECT * FROM mn_orderitems WHERE order_id ='$setSession'");
if (mysqli_num_rows($result)!=0) {
/* If a record has been found, do nothing */
echo "Not Empty";
} else {
/* if order id doesn't exist, save the new order item */
$insert=mysqli_query($db,"INSERT INTO mn_orderitems (order_id, product_id, orderitem_name, orderitem_quantity, orderitem_price, orderitem_final_price)
VALUES ('$setSession', '$product_id', '$orderitem_name', '$orderitem_quantity', '$orderitem_price', '$orderitem_final_price')");
if($insert){
echo "Successfully Added item no. ".$setSession;
}
}

Related

How to get logged person's user_id from the database and match the user id session with the second table as the foreign key?

$sql = "INSERT INTO useraccounts (name, email, taman, password) VALUES ('" . $_POST['name'] . "', '" . $_POST['email'] . "', '" . $_POST['taman'] . "','" . $_POST['passsword'] . "')";
if ($db->query($sql)) {
$id = $db->insert_id;
$query = "";
$count = count($_POST['barang']);
for ($i = 0; $i < $count; $i++) {
$query = "INSERT INTO requestitem (barang, deskripsi, kategori, image, uID) VALUES ( '$barang', '$deskripsi', '$kategori','$newImageName',
'$id')";
}
if ($db->multi_query($query)) {
echo
"<script>
alert('Successfully Added!');
document.location.href = 'displayRequest.php';
</script>";
} else {
echo "Failed";
}
} else {
echo "Failed";
}
Here is my current code. I would like to seek for help on how can I fix this code in order to insert data in second table by using current user id session as its foreign key in that second table?
First thing in this code:
for($i=0; $i<$count;$i++){
$query = "INSERT INTO requestitem (barang, deskripsi, kategori, image, uID) VALUES ( '$barang', '$deskripsi', '$kategori','$newImageName',
'$id')";
}
You maybe wanted to use .= instead of just =. And use ; at the end of sql query.
+be carefull with inserting user data to sql. Escape it to prevent SQL injections!

increment the field with additions of new values

I have a phpscript which takes values (Manually entered) and inserts into the column in the database. Now I want to know how would I be adding new values to the existing values for the same card number entered.
if(isset($_POST['insert-btn'])){
#$cardnumber=$_POST['cardnumber'];
#$amount=$_POST['amount'];
if($cardnumber=="" || $amount==""){
echo '<script type="text/javascript">alert("Insert values in all fields")</script>';
}
else{
$query = "insert into Client_Details values('$cardnumber',$amount/2)";
$query_run=mysqli_query($con,$query);
if($query_run){
echo '<script type="text/javascript">alert("Values inserted successfully")</script>';
}
else{
echo '<script type="text/javascript">alert("Values not inserted successfully")</script>';
}
}
}
?>
For example , I have
card number: _________
Sale value: __________
Now for the same card number the sale value entered every different time should be added. If anybody can help me with that. It would be helpful.
Before you insert data into DB, check whether a record for the card number already exists in the DB.
If it exists, use UPDATE query else use INSERT query.
Try the below code:
<?php
if (isset($_POST['insert-btn']))
{
#$cardnumber = $_POST['cardnumber'];
#$amount = $_POST['amount'];
if ($cardnumber == "" || $amount == "")
{
echo '<script type="text/javascript">alert("Insert values in all fields")</script>';
}
else
{
$newQuery = mysqli_query($con, "SELECT * FROM Client_Details WHERE cardnumber='" . $cardnumber . "'");
if (mysqli_num_rows($newQuery) > 0)
{
$query = "UPDATE Client_Details SET amount = amount + '" . $amount . "' WHERE cardnumber = '" . $cardnumber . "'";
}
else
{
$query = "INSERT into Client_Details values('$cardnumber',$amount/2)";
}
$query_run = mysqli_query($con, $query);
if ($query_run)
{
echo '<script type="text/javascript">alert("Values inserted successfully")</script>';
}
else
{
echo '<script type="text/javascript">alert("Values not inserted successfully")</script>';
}
}
}
*Modify the table name and column names accordingly

Get row data after an Update query

I'm writing a very basic API that manages a list of existing unique keys. When the getKey() method is called, it either returns the key that has already been assigned or it finds one that is unused and assigns that.
During the latter, I have to call UPDATE on an existing row, marking it as assigned. After doing so, I am querying the same information again to get the row data, where I feel like this is fairly redundant. Although it works, I am trying to find the best practice for self improvement, where I would like to get any feedback on potentially better implementations.
<?php
require "Slim/Slim.php";
\Slim\Slim::registerAutoloader();
require "defines.php";
$GLOBALS['db'] = new mysqli(DATABASE_HOST, DATABASE_USER, DATABASE_PASS, DATABASE_NAME);
// SLIM INSTANCE
$app = new \Slim\Slim();
$app->get('/getKey/:dlc/:serviceId', function ($dlc, $serviceId)
{
$sql = "SELECT game_key FROM " . $dlc . " WHERE service_id = " . $serviceId . " LIMIT 1";
if ($result = $GLOBALS['db']->query($sql))
{
// Check if we already have a GAME_KEY assigned
if (mysqli_num_rows($result) >= 1)
{
echo "got an existing row!";
$row = mysqli_fetch_assoc($result);
echo $row["game_key"];
}
else
{
echo "no existing row, lets update one!";
$sql = "UPDATE " . $dlc . " SET service_id = $serviceId WHERE service_id = 0 LIMIT 1";
if ($GLOBALS['db']->query($sql))
{
$sql = "SELECT game_key FROM " . $dlc . " WHERE service_id = " . $serviceId;
if ($result2 = $GLOBALS['db']->query($sql))
{
$row = mysqli_fetch_assoc($result2);
echo $row["game_key"];
}
}
}
}
else
{
echo "Query Failed!";
}
});
// run the Slim app
$app->run();
?>
You can use max 2 statements:
// SELECT game_key matching $serviceId OR some with 0 if not found
$sql = "SELECT id, game_key, service_id FROM " . $dlc . " WHERE service_id = " . $serviceId . " OR service_id = 0 ORDER BY service_id DESC LIMIT 1";
if ($result = $GLOBALS['db']->query($sql))
{
$row = mysqli_fetch_assoc($result);
echo $row["game_key"];
// Check if it is new key
if($row["service_id"] == 0) {
$keyId = $row["id"]
$sql = "UPDATE $dlc SET service_id = $serviceId WHERE id= $keyId LIMIT 1";
... // continue to exec update query
}
}
I assume that you have "id" primary key column in your table

How to remove 5 characters from the end of every column in a table MySQLi

I'm trying to loop through every row in a table, and remove 5 characters from the end of one column. I have written the following code but it seems to remove 2 characters for some reason.
<?php
$connection = new mysqli('localhost', 'nawd_test', 'password', 'nawd_test');
if ($connection->connect_errno > 0) {
die ('Unable to connect to database [' . $connection->connect_error . ']');
}
$sql = "SELECT *
FROM test";
if (!$result = $connection->query($sql)) {
die ('There was an error running query[' . $connection->error . ']');
}
//Create an array to hold the values of id's already changed
$ids = [];
$newVals = [];
echo '<p>Fetching rows...</p>';
while ($row = $result->fetch_assoc()) {
//Check / Add the id
if (in_array($row['id'], $ids)) {
echo '<p style="red"><strong>Error: Script has repeated itself!</strong></p>';
break;
}
$ids[] = $row['id'];
$rowName = $row['name'];
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
$newVals[] = $newName;
}
//Now loop and update
$newValID = 0;
foreach ($ids as &$id) {
echo '<p>Updating row with ID ' . $id . '</p>';
mysqli_query($connection, "UPDATE test SET name ='" . $newVals[$newValID] . "' WHERE id=" . $id);
echo '<p>Column successfully changed "<em>' . $newVals[$newValID] . '</em>"</p>';
$newValID++;
}
echo '<p style="color: green;"><strong>Script complete!</strong></p>';
?>
Dont do this in php, you can do it with a single sql query:
UPDATE test SET name = LEFT(name, LENGTH(name) - 5)
Change
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
into
$newName = substr($rowName, 0, strlen($rowName) - 5);
With the way you're working, you could never predict how many characters that would have removed at the end.
Minimum 1, maximum the whole word.
Please read the documentation about rtrim and substr.
try this if you wanna doit inside the query:
update table1 set name=substr(name,-5,length(name))

Checking Table exists before inserting php sql

I am trying to check if a table exists before entering the data into it. I am trying mysql_query and getting errors that I should be using mysqli, but it does not seem to be working for me.
This is my code so far:
$AllData = $_POST["table"];
foreach ($AllData as $sigleData) {
$table = $sigleData['name'];
$columns = implode(", ", $sigleData['columns']);
$columnData = implode(" ',' ", $sigleData['data']);
// Insert into database tuple data
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
if ($dbConnectionT->query($sqlQuery) == TRUE) {
echo "database updated";
echo "</br>";
}
}
Try this way to check table exists or not using this custom function and then insert row to your db.
function check_table_exist($table){
global $dbConnection; // see here global connection variable
$sql = "SHOW tables LIKE '".$table."'";
$res = $dbConnection->query($sql);
return ($res->num_rows > 0);
}
#check first table exists or not
if(check_table_exists($table)){
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
//do other stuff........
}else{
echo "Table Not Exists";
die('Going Out');
}
Table name is accepted as POST parameter, seriously !! - bad practice.
You can do various check to table existence like
DESC tbl_name;
SHOW CREATE TABLE tbl_name;
SHOW TABLES like 'tbl_name';

Categories