JS/PHP/MySQL Success but not Inserted - javascript

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.

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.

What is the most efficient way to get SQL table values?

I wrote some code a while back to retrieve a player's saved score when they logged into the website. It used AJAX, and looked a little something like this:
Javascript:
function getHighScore(user){
$.get("getScore.php?userName="+user,function(data){
console.log(data);
output = data;
});
}
PHP:
<?php
$username = strval($_GET['userName']);
$con = mysqli_connect('localhost','XXXX','XXXX','XXXX');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
} else {
$sql="SELECT * FROM users WHERE username = '".$username."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$wealth = $row['wealth'];
echo $wealth;
}
}
mysqli_close($con);
//return $wealth;
?>
I was faced with the fact today that I would have to grab a whole bunch of data from a database, so I had a look at the old high score code I wrote. I'll attach a screenshot of what the table looks like that I will be retrieving info from. Anyway, I need to grab info from 6 columns and 10 rows. I need to assign a PHP variable to the data from P1, P2, P3 etc on MON1; P1, P2, P3 etc on TUE1; so on and so forth until we reach P6 on FRI2. I'm really quite new to PHP, so what would be the best way to go around doing this?
I apologise if I worded the question strangely. Feel free to ask if you didn't understand something.
Thank you!
PS: Ignore the P#_WORK columns. I don't need to refer to them right now
https://ibb.co/gq8u5a
I'd suggest you use an object to store everything, using the "day" column as key, and as value the P* columns in another. Here's some code you can use right away:
<?php
$con = mysqli_connect('localhost','XXXX','XXXX','XXXX');
if(!$con) exit('Could not connect: ' . mysqli_error($con));
$username = $_GET['userName'];
$sql = "SELECT * FROM TABLE WHERE username = '%s'";
$results = $con->query(sprintf($sql, $con->escape_string($username))); // Always escape parameters to prevent SQL injection attacks
$data = new stdClass; // An empty object
while($result = $results->fetch_object()){
$day = $result->day; // Use the day as the key of the object
$data->{$day} = $result;
}
// Now we output the results below by accesing the data in a chain-like fashion by accesing the "data" object
echo $data->MON1->P1 . '<br>'; // will output "Geo E"
echo $data->FRI1->P4 . '<br>'; // will output "Maths"
echo $data->THU2->P6 . '<br>'; // will output "DT"
Be sure to replace "TABLE" in the SQL query with the actual table name, as that wasn't visible in the screenshot you attached.

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.

Storing a value changes in the DB

<?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.

Manipulating JSON data to create javascript array of lat/lngs in Google Maps API V3

I'm trying to use lat/lng values retrieved from MySQL to create an array of waypoints for use in the GMaps API. I have the code below but with my limited javascript knowledge am struggling to push this retrieved data into a javascript array to define as the waypoints data.
I've looked at a few online examples and so far I have managed to get a parsing script to retrieve the data with no problems and call this within the page I have the maps instantiated on:
makeRequest('parsedata.php', function(data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
The parsedata.php code:
<?php
include 'session.php';
$query = "SELECT itinerary_link.itineraryID, itinerary_link.coursesID, itinerary_courses.coursename,
courses.lat, courses.lng FROM itinerary_link LEFT JOIN
itinerary_courses ON itinerary_link.coursesID = itinerary_courses.coursesID LEFT JOIN
courses ON courses.coursename = itinerary_courses.coursename WHERE itineraryID=6 ORDER BY coursename";
$result = mysqli_query($dbc, $query);
$rows = array();
while ($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode( $rows );
?>
And sample output from this:
[{"itineraryID":"6","coursesID":"20","coursename":"Carnoustie Championship Course","lat":"56.497414","lng":"-2.720531"},{"itineraryID":"6","coursesID":"21","coursename":"Troon Old Course","lat":"55.534203","lng":"-4.642833"}]
Basically I can't work out how to manipulate this output to create the required javascript array of lat/lngs to feed in as the waypoints for a directions service instance I have running on the page.
As always, any pointers much appreciated. Cheers.
//create an array for the waypoints
var waypoints=[];
//only up to 8 waypoints are allowed without business-license
for(var i=0;i<8 && i<data.length;++i) {
//push a LatLng-object to the array
waypoints.push(new google.maps.LatLng(data[i].lat,data[i].lng));
}
//use the waypoints
//doSomethingWith(waypoints);

Categories

Resources