Storing a value changes in the DB - javascript

<?php
$id = rand(10000,99999);
$shorturl = base_convert($id,20,36);
echo $shorturl;
$db->query("INSERT INTO maps (id, url, user_id, locationData, userData) values ( null, '$shorturl', null, '$locationData','$userData')");
Using the above PHP I have been trying generate a unique shorturl which gets stored into a Database and then gets sent to javascript to tell the client side the values echoed.
In an example I tested the above code and in Javascript it console.logged lyhc but when I checked the Database it had the following 6c796863
The database row is set up like url varchar(255) utf8_bin
Am I doing something wrong here?

Your JS code must be taking your output in a different type.
I'm using this function to generate random strings:
function createRandomCode($length='30'){
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$code= '';
while ($i++ < $length){
$code = $code. substr($chars, rand() % 33, 1);
}
return $code;
}
It might be helpful.

Related

send data from php array in javascript forEach loop to url of ajax call

I'm trying to loop through the results of a mysql query in php, the output of the query is an array similar to [10201,10202]. I want to take the results and loop it to the variable named id in my javascript function and loop it through the url of my ajax call. The goal is to take the id and use it in a sql query on another page to change the date of the id in our database.
mysql query:
<?php
// sql query for # print all open orders function
$sql = "SELECT Order_PID
FROM `Order`
WHERE SHIPDATE IS NULL
AND Address1 IS NOT NULL;";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)) {
$order[] = $row['Order_PID'];
}
?>
javascript function:
I'm trying to use a forEach function to iterate through the results of the array.
$('button#printOpenOrders').on('click', function(e) {
if(confirm("Are you sure you want to print all open orders and mark them as pending?")) {
e.preventDefault();
// prints all open orders
window.open("/resources/scripts/allOpenPDF.php");
var arr = $order;
arr.forEach(function(id) { // <====this function
$.ajax({
url: "/resources/scripts/pending-order.php?id=" + id, // <===this variable
datatype : "string",
success : function(data) {
location.reload(true);
}
})
})
}
});
and if it helps here is my callback script
<?php
// login validation
session_start();
if (!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] != true) {
$url = $_SERVER['DOCUMENT_ROOT'].'/index.php';
header("Location: ../../index.php");
}
// establish connection to database
include $_SERVER['DOCUMENT_ROOT'].'/resources/scripts/dbconnect.php';
$conn = openConnection();
// capture id
$id = $_GET['id'];
$pendingDate = date_create_from_format("m/d/Y", "07/26/1996");
$pendingDate = date_format($pendingDate, "Y-m-d H:i:s");
$sql = $conn->prepare("UPDATE `Order`
SET SHIPDATE = ?
WHERE Order_PID = ?");
$sql->bind_param("si", $pendingDate, $id);
$sql->execute();
echo "success";
closeConnection($conn);
?>
If parts of my code don't make sense, I'm new to this and I am using my currently limited knowledge to frankenstein all of this together. Any nudges in the right direction would be super helpful.
You can output $order variable contents, but you need to use PHP and also you must encode it using json format, so this could actually work:
var arr = <?PHP echo json_encode($order); ?>;
But it is error-prone, the syntax is not really nice to read, and if that variable somehow becomes in the format you are not expecting it could lead to another JavaScript syntax error.
But the best way in my opinion would be to make an AJAX request and get those order IDS, and after that you could create another AJAX request that would send all those Order IDS,
so you wouldn't need .forEach stuff and your logic of handling multiple orders need to be modified in order to accommodate for these changes.
But since you already have those IDS in PHP I mean stored in $order variable, you could just encode it and send it all the ids at once in a single request.

How to get last insert id from mysql database in php?

I want to get last insert id from my table cart in my else statement after the insert. But I am not getting the id.
Please check my code and suggest what am I doing wrong:
// Check to see if the cart COOKIE exists
if ($cart_id != '') {
// Here I want to update but not getting $cart_id, so everytime insert query fire in else statement
}else{
$items_json = json_encode($item);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ");
$cart_id = $db->insert_id; // Here is the problem
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}
Your suggestions would be welcome.
Instead of:
$db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ");
$cart_id = $db->insert_id; // Here is the problem
Use this, directly from the documentation:
$query = "INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ";
mysqli_query($db, $query);
$cart_id = mysqli_insert_id($db);
Get the identity column value AFTER the insert:
create table student (
id int primary key not null auto_increment,
name varchar(20)
);
insert into student (name) values ('John');
select ##identity; -- returns 1
insert into student (name) values ('Peter');
select ##identity; -- returns 2
Or get the next auto incremental value before insert:
$query = $db->query("SHOW TABLE STATUS LIKE 'cart'");
$next = $query->fetch(PDO::FETCH_ASSOC);
echo $next['Auto_increment'];

Return multiple results with AJAX from sql query in php

Hello I am realizing simple AJAX request and would like to be able to store the results from the SQL SELECT query into 3 different ajax variables.
Where 2 of them will store one variable and the other one have to store foreach results.
Let's say my AJAX request is the following:
$.post('includes/check_number.php', {'date':date, 'userid':userid}, function(data) {
$("#time-result").html(data.result01);
$("#time-sum-result").html(data.result02);
Where I will have 2 results result01 and result02
In the current state of my script inside the mysql select request what is returning like data is the following:
$stmt = $con->prepare( $sql );
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
foreach($stmt as $row) {
echo "<tr>
<td>".$row['clientname']."</td>
<td>".$row['taskname']."</td>
<td>".$row['department']."</td>
<td>".$row['note']."</td>
<td>".$row['caseid']."</td>
<td>".$row['time']."</td>
</tr>";
}
I would like to put the result of the forreach as it is inside the echo, where it will contains various iterations and then for result02 for example would like to put only one row of the same query for example like: $row['date']
In this case
data.result01 - will have all the code of the <tr></tr>
data.result02 - will have only one variable which is date.
Question is how to dump the foreach into result01 and in the same time to put in result02 only one row from the same query. $stmt
Export all your data first then use it with jquery ?
Something like :
PHP :
foreach($stmt as $row) {
$arr_out[] = $row;
}
echo json_encode($arr_out);
exit();
JQUERY :
var result1 = "";
$.post('includes/check_number.php', {'date':date, 'userid':userid}, function(data) {
$.each(data, function(key, item) {
result1 += "<tr><td>"+item.clientname+"</td>[...]<td>"+item.time+"</td></tr>";
result2 = item.date;
});
$("#time-result").html(result1);
}
I didn't test this code, hope it will help you.

JS/PHP/MySQL Success but not Inserted

I have a array containing objects and I want to store these objects into my MySQL DB. At the beginning it worked quite fine, but suddenly it stopped working even though it did not make any changes to the code or the DB.
The array of object looks as follows: var geocoded = [{zip: 1234, place: "XY", country: "XY", lat: "123.123", lng: "123.123"}, ...];
I use the following JS code to iterate over the array and post each object to the DB. kiter is the iterator I use and is defined as geocoded.length - 1
function postPlaces(data, kiter) {
if (kiter >= 0) {
$.post("api/placessave.php",
data[kiter],
function(data, status){
kiter--;
postPlaces(geocoded, kiter);
console.log(data + '.............' + status);
}
);
} else {
//statusUpdate(id);
}
}
placessave.php looks as follows:
<?php
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','*****');
define('DB','****');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$zip = $_POST['zip'];
$place = $_POST['place'];
$country = $_POST['country'];
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$sql = "insert ignore into places (zip, place, country, lat, lng) values ($zip, '$place', '$country', '$lat', '$lng')";
if(mysqli_query($con, $sql)){
echo "success";
}
mysqli_close($con);
?>
I use INSERT IGNORE because duplicates may exist but an update is not needed.
The interesting part is, that everything works quite nice I also get a Success on every query but nothing is stored to the DB.
Insert Query you have to change like this. You have Missed Quotes around the values
Replace
$sql = "insert ignore into places (zip, place, country, lat, lng) values ($zip, '$place', '$country', '$lat', '$lng')";
With
$sql = "insert ignore into places (zip, place, country, lat, lng) values ('".$zip."', '".$place."', '".$country."', '".$lat."', '".$lng."')";
I found the solution myself. The problem was in the data I wanted to store. I found that there was a place name which contained a '. Therefore the query did not work. After removing this, everything works fine.
just change ($zip, in the query to ('$zip',
zip is probably string and you are not passing it as string in the query. Moreover, this code is vulnerable to SQL injection. Please read about it to avoid insecurities.

PHP Query Returning the Same Data Even Though It Changes

I am trying to loop through data to make a chat system.
I have made a php function:
function getLatestMessageTime() {
$handler = new PDO('mysql:host=localhost;dbname=*****', '******', '*******');
// Set the query \\
$query = $handler->query('SELECT `time` FROM `messages`');
// Loop through the data \\
$latestTime = 0;
while ($row = $query->fetch()) {
if ($row['time'] > $latestTime) {
$latestTime = $row['time'];
};
};
// Return the latest message time \\
Return $latestTime;
}
And I set my looping jQuery code:
var latestTime = <?php echo getLatestMessageTime(); ?>;
latestTimeLoop();
function latestTimeLoop() {
if (latestTime < <?php echo getLatestMessageTime(); ?>) {
$("#container").load('ajaxLoad.php?time='+latestTime);
};
document.log(latestTime + " - " + <?php echo getLatestMessageTime(); ?>);
setTimeout(latestTimeLoop, 200);
}
But when I change the time in phpMyAdmin to be much higher than the rest of the data, it doesn't update in my console.logs. It seems like my query isn't occuring more than once within my function, it only grabs the data once instead of requesting it each time my javascript code loops.
Is there any way to reset the query each time to it grabs new info each loop?
View Full Code
use ORDER BY in your query and also limit the query to one.
$query = $handler->query('SELECT `time` FROM `messages` ORDER BY `time` DESC LIMIT 1');
Only last record details is needed to get the latest message time. thats why i said to use limit and modify php code according to it.

Categories

Resources