Updating MySQL Table with AJAX - php

I am trying to send a value for an item in a MySQL table and increment its "availability" column by one.
A press of a button executes the following onclick function:
function updateStuff() {
// Data validation for string variable val
// coordinating to one of the items in the SQL table
var xmlHttp = false;
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
xmlHttp = new XMLHttpRequest();
}
if(!xmlHttp)
alert("Error : Cannot create xmlHttp object");
else{
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4){
xmlHttp.open("GET","update.php?val=" + val, true);
xmlHttp.send();
}
else{
setTimeout(updateStuff,1000);
}
}
}
update.php looks like this:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$item = $_GET['val'];
echo 'You selected ' . $item;
$server = "localhost";
$user = "root";
$pass = "";
$datab = "checkout";
// Connect to database
$db = mysqli_connect($server, $user, $pass, $datab);
// Check connection
if (mysqli_connect_errno()){
echo "Could not connect to database: " . mysqli_connect_error();
}
$results = mysqli_query($db,"SELECT * FROM inventory WHERE item = " . $item);
$available = $results['available'] + 1;
$result = mysqli_query($db, "UPDATE inventory SET available = " . $available . " WHERE item = " + $item);
// Close connection
mysqli_close($db);
echo '</response>';
?>
I think this is generally correct, unfortunately I'm not getting a table update when I execute the code. I am 100% confident in the validation for the variable val, and fairly confident with updateStuff(), but I'm less sure if I'm handling the server-side stuff corecctly with putting $_GET inside of response tags.
EDIT: I have made the syntax correction given by asparatu, but the problem persists.

The update query is wrong.
$result = mysqli_query($db, "UPDATE inventory SET available = available + 1 WHERE item = " + $item);
Where are you getting the current number for available?
you need a select statement that queries the current item and get current available amount then you can add one to it.
$results = mysqli_query($db,"SELECT * FROM inventory WHERE item = " . $item);
$available = $results['available'] + 1;
$result = mysqli_query($db, "UPDATE inventory SET available = " . $available . " WHERE item = " . $item);
That should work..

try this to update query:
$result = "UPDATE inventory SET available = "' .$available. '" WHERE item = "' .$item. '"";
if (mysqli_query($db, $result)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($db);
}

Related

php get all values from database and return to xml field?

i need some help with my app . I have this code :
realtime.php
$jogador = Jogador::getSaldoJogadorByEmail($email);
$premio = Premio::getValorPremioByTipo($tipo);
$participante = Participantes::getATotalParticipantesFromPA1();
$doc = new DOMDocument("1.0");
$action = $doc->createElement('action');
$action = $doc->appendChild($action);
$jogador = $doc->createElement('jogador1', $jogador);
$jogador = $action->appendChild($jogador);
$premio = $doc->createElement('premio1', $premio);
$premio = $action->appendChild($premio);
$participante = $doc->createElement('participante1', $participante);
$participante = $action->appendChild($participante);
$output = $doc->saveXML();
header("Content-type: application/xml");
echo $output;
and i have this function that is only p+assing one value instead of passing all the content of the database :
static function getTotalParticipantesFromPA1(){
$db = new mysqli("localhost","******","****","participantes");
$query = "SELECT * FROM premioacumulado1";
$result = $db->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
if(mysqli_num_rows($result) > 0 ){
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$id = $row['id'];
$username = $row['username'];
$m = "ID: " . $id . " " . "User: " . $username . "\n";
return $m;
}
}else{
$db->close();
return NULL;
}
}
all other fields are working in realtime , but this one is only getting one value from the database ...
how to get all the values from the database?
Edited - 22-05-2022
static function getTotalParticipantesFromPA1(){
$db = new mysqli("localhost","*****","*****","participantes");
$query = "SELECT * FROM premioacumulado1";
$result = $db->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
if(mysqli_num_rows($result) > 0 ){
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$id = $row['id'];
$username = $row['username'];
$m = "ID: " . $id . " " . "User: " . $username . "\n";
}
return $m; // if i put it here it only returns the last value in the data base .
}else{
$db->close();
return NULL;
}
}
static function getTotalParticipantesFromPA1(){
$db = new mysqli("localhost","*****","*****","participantes");
$query = "SELECT * FROM premioacumulado1";
$result = $db->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
if(mysqli_num_rows($result) > 0 ){
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$id = $row['id'];
$username = $row['username'];
$m = "ID: " . $id . " " . "User: " . $username . "\n";
echo $m;// if i do a echo i get an error in the xml $participante variable(realtime.php) , maybe convert it here so it can take the result , but how ?
}
}else{
$db->close();
return NULL;
}
}
here is the script Js :
function getRealTime(){
//retrieve the DOM objects to place content
var domjogador1 = document.getElementById("saldo");
var dompremiovaloracu1 = document.getElementById("valorActualPremioAcu1");
var domparticipantes1 = document.getElementById("areaParticipantesAcu1");
//send the get request to retrieve the data
var request = new XMLHttpRequest();
request.open("GET", "realtimegame.php", true);
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
//parse the xml document to get each data element
var xmldoc = request.responseXML;
var xmljogador1 = xmldoc.getElementsByTagName("jogador1")[0];
var jogador1 = xmljogador1.childNodes[0].nodeValue;
var xmlpremio1 = xmldoc.getElementsByTagName("premio1")[0];
var premio1 = xmlpremio1.childNodes[0].nodeValue;
var xmlparticipante1 = xmldoc.getElementsByTagName("participante1")[0];
var participante1 = xmlparticipante1.childNodes[0].nodeValue;
domjogador1.innerHTML = jogador1;
dompremiovaloracu1.innerHTML = premio1;
domparticipantes1.innerHTML = participante1;
}
};
request.send();
}
here is the function that works , now with a more pretty result:
static function getBTotalParticipantesFromPA1(){
$db = new mysqli("localhost","root","","participantes");
$query = "SELECT * FROM premioacumulado1";
$result = $db->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
$s = "<br />";
$data1 = array();
if(mysqli_num_rows($result) > 0 ){
do{
$data1[] = $row['username'] . " " . $row['id'] . "
";
}while($row = $result->fetch_array(MYSQLI_ASSOC));
return json_encode($data1);
}else{
$db->close();
return NULL;
}
}
I still wanted to print out something a little more pretty for end user to see . with this i get the line break in each value , but i still wanted to remove the "," from the output ... if anyone has something that can be used better then this please post it , thanks .

How do I get all values to echo with mysqli_fetch_assoc?

I'm pretty new to php, so don't really know how to do much, but from what I've looked up, this should echo all values from the two fields.
<?php
$con = mysqli_connect('localhost', 'root', 'root', 'unityaccess');
if(mysqli_connect_errno())
{
echo "1: Connection failed"; //error code 1 = connection failed
exit();
}
$username = $_POST["name"];
$idcheckquery = "SELECT id FROM users WHERE username = '" . $username . "';";
$idcheck = mysqli_query($con, $idcheckquery) or die("7: ID check query failed"); //error code 8 = couldn't get user's id
$existingid = mysqli_fetch_assoc($idcheck);
$userid = $existingid["id"];
$itemfindquery = "SELECT itemid, equipped FROM inventory WHERE userid = '" . $userid ."';";
$itemfind = mysqli_query($con, $itemfindquery) or die("9: Couldn't find items");
while($row = $mysqli_fetch_assoc($itemfind)){
echo $row["itemid"] . ", " . $row["equipped"] . " ";
}
?>
I expect this to, when it is called in unity, to print a list of all the values in each list, but instead it doesn't echo anything.
The mysqli_fetch_assoc() function is being used as a variable ($). Just remove the dollar sign and it will work.
while($row = mysqli_fetch_assoc($itemfind)){
echo $row["itemid"] . ", " . $row["equipped"] . " ";
}
Also, try to use prepared statements to fight against SQL injections.

How to show average from mysql

How to show the average of a column in mysql?
Below is my code which i have tried so far :
<?php
if (isset($_GET["age"]));
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/includes/config.php");
// Input
$sql = "SELECT AVG(column_name) FROM table_name";
// Check age
if ($age > 99 or $age < 5) {
echo ("We only store data of people between the age of 5 and 99.");
if (!mysqli_query($conn, $sql)) {
die('Error: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
}
}
else {
echo ("We got it!");
}
// Close connection
((is_null($___mysqli_res = mysqli_close($conn))) ? false : $___mysqli_res);
die();
?>
But how to exactly define a variable to the result of the AVG with a maximum of 2 decimals?
I want to used and show it into another file (so I will include this one).
What I have right now
<?php
if (isset($_GET["age"]));
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/config.php");
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/opendb.php");
// My own created code
$sql = $conn->query("SELECT ROUND(AVG(price AS FLOAT), 2) FROM data WHERE age= '$age'");
$data = $sql->mysqli_fetch_assoc();
$avg_data = $data['price'];
echo $avg_data;
// This below is from an other post but don't know how it works and if it is good.
$ratings = $conn->query("SELECT AVG(price) avg_rating FROM data form_id = '" . $age . "'");
$data2 = $ratings->mysqli_fetch_assoc();
$avg_rating = $data2['avg_rating'];
echo $avg_rating;
die();
?>
Use Like This For Getting Average witth two decimal points.
$sql = "SELECT ROUND(AVG(column_name AS FLOAT), 2) FROM table_name";
How I fixed it:
<?php
if (isset($_GET["age"])) {
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/config.php");
$con=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT AVG(price) FROM data WHERE age= '$age'") or die("Error: " . mysqli_error($con));
while($row = mysqli_fetch_array($result)) {
echo $row['AVG(price)'];
echo number_format($row['AVG(price)'], 2);
}
die();
}
else {
echo 'Something went wrong, try again.';
}
?>
$sql = 'SELECT *, ROUND(AVG(column_name), 2) AS avg_value FROM table_name';
avg_value will store the rounded + average value and add * if need to get all the column.

Is there a limit on record updates for MySQL in PHP?

I wrote a PHP script to do some color conversions from Hexadecimal to RGB and HSL values and store them in a database. My current dataset is the entire Pantone Solid Coated color book which is 1341 colors. I have the Hexadecimal values already in there.
From there I accessed the database and took the Hex value and did the two conversions and then stored them back in the table.
I am getting no errors, but the process seems to stop at record 499 for the updates even though the echo of all the values I did for testing show the calculations being applied to all 1341 colors.
Here is the script I have so far:
// SQL Server Login Info Removed
$sql_connection = new mysqli($sql_server, $sql_username, $sql_password, $sql_database);
if ($sql_connection->connect_error) {
die("Connection Failed: " . $sql_connection->connect_error);
}
$query = "SELECT * FROM coated";
$result = $sql_connection->query($query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$colorname = $row["mapName"];
$hexvalue = $row["hex"];
if ($row["rgb"] == '') {
$rgbvalue = hex2rgb($hexvalue);
} else {
$rgbvalue = $row["rgb"];
}
if ($row["hsl"] == '') {
$hslvalue = hex2hsl($hexvalue);
} else {
$hslvalue = $row["hsl"];
}
//echo "Color: " . $row["mapName"] . " | " . $rgbvalue . " | " . $hslvalue . "<br>";
$wrt_query = "UPDATE coated SET hex='".$hexvalue."', rgb='".$rgbvalue."', hsl='".$hslvalue."' WHERE mapName='".$colorname."'";
if ($sql_connection->query($wrt_query) === true) {
echo "Record for " . $colorname . " updated <br>";
} else {
echo "Error updating record for " . $colorname . "<br>";
}
}
}
The data comes from a CSV file. Here is a excerpt:
pantone-Yellow-C,#fedd00
pantone-Yellow-012-C,#ffd700
pantone-Orange-021-C,#fe5000
pantone-Warm-Red-C,#f9423a
pantone-Red-032-C,#ef3340
pantone-Rubine-Red-C,#ce0058
pantone-Rhodamine-Red-C,#e10098
pantone-Purple-C,#bb29bb
pantone-Violet-C,#440099
pantone-Blue-072-C,#10069f
pantone-Reflex-Blue-C,#001489
pantone-Process-Blue-C,#0085ca
pantone-Green-C,#00ab84
pantone-Black-C,#2d2926
pantone-Yellow-0131-C,#f2f0a1
pantone-Red-0331-C,#fcaebb
pantone-Magenta-0521-C,#f1b2dc
pantone-Violet-0631-C,#bf9bde
pantone-Blue-0821-C,#74d1ea
pantone-Green-0921-C,#9de7d7
pantone-Black-0961-C,#9e978e
...
pantone-Black-2-C,#332f21
pantone-Black-3-C,#212721
pantone-Black-4-C,#31261d
pantone-Black-5-C,#3e2b2e
pantone-Black-6-C,#101820
pantone-Black-7-C,#3d3935
You might need to bump up your script time in php.ini, here I do it with a php function.
I think hex is more reliable as a key here, so I'm using that, since its always the same field length.
I've taken out its update since you dont change it.
Im also doing it with mysql if because I am sneaky.
Back up your db and give this a go.
set_time_limit(10000);
// SQL Server Login Info Removed
$sql_connection = new mysqli($sql_server, $sql_username, $sql_password, $sql_database);
if ($sql_connection->connect_error) {
die("Connection Failed: " . $sql_connection->connect_error);
}
$query = "SELECT * FROM coated";
$result = $sql_connection->query($query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$wrt_query =
"UPDATE coated SET
rgb=IF(rgb IS NULL or rgb='','".hex2rgb($row["hex"])."',rgb)',
hsl=IF(hsl IS NULL or hsl='','".hex2hsl($row["hex"])."',hsl)'
WHERE hex='".$row["hex"]."';";
if ($sql_connection->query($wrt_query) === true) {
echo "Record for " . $colorname . " updated <br>";
} else {
echo "Error updating record for " . $colorname . "<br>";
}
}
}

php simple html dom return array?

I'm trying to create an app using the simple HTML DOM php script, but im running into a wall currently with it - hope you can help.
The aim is to read product numbers from mySQL database, concat these numbers with a url constant and then parse this resulting website for a specific class. The result should then be printed to the screen.
My problem is that the script is returning only the first result from the function array, i have tried a few things, such as trying to call $prices->children[4], but nothing seems to help.
When i trigger the function get_prices_array() with a url, it brings back multiple results -> but when i return this inside my while loop it only brings back the first result in the array.
Heres my code, hope you can point me in the right direction!
Thanks!
<?php
include('simple_html_dom.php');
function get_prices_array($url) {
$x = file_get_html($url);
foreach ($x->find('span.price')as $dom) {
$y = $dom->outertext;
return $y;
}
$x->clear();
}
$con = mysqli_connect("localhost", "***", "***", "***");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$result = mysqli_query($con, "SELECT * FROM articles");
while ($row = mysqli_fetch_array($result)) {
$constant = '***';
$prices = get_prices_array($constant . $row["product_number"]);
echo $row["product_number"] . " - " . $prices . '<br />';
}
mysqli_close($con);
?>
// EDIT //
I changed the function get_prices_array() to loop through each span price class and add the result to an array, the array is then returned from the function. The first 5 results from the array are then stored to variables and added to the return string. Thanks for your help!
<?php
include('simple_html_dom.php');
function get_prices_array($url) {
$x = file_get_html($url);
$y = array();
foreach ($x->find('span.price')as $dom) {
$x = ($dom->outertext);
$y[] = $x;
}
return $y;
//$x->clear();
}
$con = mysqli_connect("localhost", "***", "***", "***");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$result = mysqli_query($con, "SELECT * FROM articles");
while ($row = mysqli_fetch_array($result)) {
$constant = '***';
$prices = get_prices_array($constant . $row["product_number"]);
$pos1 = $prices[0];
$pos2 = $prices[1];
$pos3 = $prices[2];
$pos4 = $prices[3];
$pos5 = $prices[4];
echo $row["product_number"] . " - " . $pos1 . " - " . $pos2 . " - " . $pos3 . " - " . $pos4 . " - " . $pos5 .'<br />';
}
mysqli_close($con);
?>
I think problem is because of return used in foreach loop of function get_prices_array($url).
it is executing foreach loop only once. There is no meaning of loop if you are returning without condition inside loop.

Categories