I’m working on a PHP application integrated to shopify. Basically product information must be sync between the "shop" and application. Inside the products we have variants (similar to sub products). Shopify used to send webhooks with json data to report these changes. Every time I change/add/delete a variant, shopify send a "product update" webhook that changes only the json content. This is a example:
{
...
"variants": [{
"id": 279656846,
"position": 1,
"price": "80.00",
"product_id": 123022448,
"sku": "1000",
"option1": "30 cm",
"inventory_quantity": 10
},
{
"id": 291321287,
"position": 2,
"price": "15.00",
"product_id": 123022448,
"sku": "1003",
"option1": "15 cm",
"inventory_quantity": 23
}],
...
}
If I create a new variant it sends me a "product update" with current status, and has the new variant in json. Similarly, if I delete, it only send me a "product update" with current status, but without the deleted variant in json.
I created the following code that can treat properly the change/add case:
foreach ($jsonArr['variants'] as $rows) {
$variant = $rows['option1'];
$sku = $rows['sku'];
$salesPrice = $rows['price'];
$stockQty = $rows['inventory_quantity'];
$idVar = $rows['id'];
$dupchk = mysql_query("SELECT * FROM `variants` WHERE `idVar`='$idVar'",$con) or die (mysql_error());
$num_rows = mysql_num_rows($dupchk);
if ($num_rows > 0) {
$sql = "UPDATE `variants` SET `variant`='$variant',`sku`='$sku',`salesPrice`='$salesPrice',`stockQty`='$stockQty' WHERE `idVar`='$idVar'";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
}
else {
$sql = "INSERT INTO `variants`(`idVariant`, `idProduct`, `variant`, `sku`, `salesPrice`, `stockQty`, `comments`, `idVar`) VALUES ('','$idProduct','$variant','$sku','$salesPrice','$stockQty','','$idVar')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
}
}
The problem is that this code does not handle the delete variant case. I tried to do it but until now only create a "big confusing" code that could not work. Please, advise if you have any suggestion to a smart way to handle it.
To solve I used following code:
//Variable to count variant update or create
$var_count = 0;
foreach ($jsonArr['variants'] as $rows) {
$variant = $rows['option1'];
$sku = $rows['sku'];
$salesPrice = $rows['price'];
$stockQty = $rows['inventory_quantity'];
$idVar = $rows['id'];
$dupchk = mysql_query("SELECT * FROM `variants` WHERE `idVar`='$idVar'",$con) or die (mysql_error());
$num_rows = mysql_num_rows($dupchk);
if ($num_rows > 0) {
$sql = "UPDATE `variants` SET `variant`='$variant',`sku`='$sku',`salesPrice`='$salesPrice',`stockQty`='$stockQty' WHERE `idVar`='$idVar'";
$var_count++;
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
}
else {
$sql = "INSERT INTO `variants`(`idVariant`, `idProduct`, `variant`, `sku`, `salesPrice`, `stockQty`, `comments`, `idVar`) VALUES ('','$idProduct','$variant','$sku','$salesPrice','$stockQty','','$idVar')";
$var_count++;
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
}
}
//Start checking to erase variant if needed
$result = mysql_query("SELECT `idVar` FROM products NATURAL JOIN variants WHERE `idShopify`='$idShopify'",$con);
$num_rows = mysql_num_rows($result);
if ($num_rows>$var_count) {
while($row = mysql_fetch_array($result))
{
$clear = 0;
foreach ($jsonArr['variants'] as $rows) {
if ($rows['id']==$row['idVar']) {
$clear++;
}
}
if ($clear==0) {
$idVar = $row['idVar'];
$sql = "DELETE FROM `variants` WHERE `idVar`='$idVar'";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
}
}
}
This is not elegant but worked. Feel free to suggest code improvements.
Related
In my php script trying to execute the data from multiple tables in single json file with multidimensional array.
So i will explain with my code:
if($data){
$sql="select * from en_providers where providerEmailAddress='".$email."' and providerPW='".$password."'";
$result = mysqli_query($con,$sql) or die("Error in Selecting " . mysqli_error($connection));
if (mysqli_num_rows($result) > 0) {
$resultArray = array();
while ($row = mysqli_fetch_assoc($result)) {
$providerID = $row['providerID'];
$resultArray['providers'] = $row;
$sql1="select * from en_venues where providerID = $providerID ";
$result1 = mysqli_query($con,$sql1) or die("Error in Selecting " . mysqli_error($connection));
$i=0;
while ($row1['venue'][] = mysqli_fetch_assoc($result1)){
echo $venueID=$row1['venue'][$i++]['venueID'];
$resultArray['venues'] = $row1;
$sql2 = "select * from en_schedules as e ,en_persons as p where e.venueID = '".$venueID."'";
$result2 = mysqli_query($con,$sql2) or die("Error in Selecting " . mysqli_error($con));
while ($row2['Persons'][] = mysqli_fetch_assoc($result2)){
$resultArray['Persons'] = $row2;
}
}
}
echo json_encode($resultArray);
}
Ouput getting like
{
"providers": {
"providerID": "1",
"providerEmailAddress": "info#gdtennis.co.uk",
"providerPW": "xxx",
"providerName": "GDT Tennis ",
"providerActive": "yes",
"providerFeatured": "no",
},
"venues": {
"venue": {
"venueID": "8",
"providerID": "1",
"venueActive": "yes",
"venueName": "Wargrave LTC ",
}
}
"Persons": {
"Persons": [
{
"scheduleID": "1",
"venueID": "151",
"scheduleTitle": "Mini Tennis Red ",
"scheduleDay": "Monday",
},
{
"scheduleID": "1",
"venueID": "151",
"scheduleTitle": "Mini Tennis yellow ",
"scheduleDay": "Monday",
},
{
"scheduleID": "1",
"venueID": "152",
"scheduleTitle": "Mini Tennis orange ",
"scheduleDay": "sunday",
}
],
}
}
In the venues array i am getting only one array actuellly it has 7 array values. but its getting only one i dont know why like this.
please help me to solve the issue
you just made one mistake just change $row1['venue'] to $row1['venue'][]
$i=0;
while ($row1['venue'][] = mysqli_fetch_assoc($result1)){
$venueID=$row1['venue'][$i++]['venueID'];
}
You need to try this solution.
$sql1="select * from en_venues where providerID = $providerID ";
$result1 = mysqli_query($con,$sql1) or die("Error in Selecting " . mysqli_error($connection));
while ($row1['venue'][] = mysqli_fetch_assoc($result1)){
$venueID=$row1['venue']['venueID'];
$resultArray['venues'] = $row1;
$sql2 = "select * from en_schedules as e ,en_persons as p where e.venueID = '".$venueID."'";
$result2 = mysqli_query($con,$sql2) or die("Error in Selecting " . mysqli_error($con));
while ($row2['Persons'][] = mysqli_fetch_assoc($result2)){
$resultArray['Persons'] = $row2;
}
You can make array how you make it for persons.
my question is: how i can show only id 2 from this code ? (the code show all id)
this is a file.php json encode
<?php
header('Content-type: application/json');
$server = "";
$username = "";
$password = "";
$database = "";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT * FROM flo";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
relative json result
([
{
"id":"1",
"Marca":"puma",
},
{
"id":"2",
"Marca":"fila",
}
]);
thx a lot
In order to display id=2 (or any other) from JSON, it's necessary to search the id, like this (will display "fila") :
<?php
$data = '[ { "id":"1",
"Marca":"puma"
},
{ "id":"2",
"Marca":"fila"
},
{ "id":"3",
"Marca":"nike"
}
]';
$json = json_decode( $data );
foreach ( $json as $record ) // VISIT EACH RECORD.
if ( $record->id == "2" )
echo $record->Marca . "<br/><br/>";
?>
Notice how each field in the data becomes a property in JSON ("id" becomes $record->id).
I'm trying to check whether major, grade and university in candidates table, are empty, if so then insert in university...Else...
Is my syntax appropriate?
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
while($row5 = mysqli_fetch_array($result5)) {
$major = $row5['Major'];
$grade = $row5['Grade'];
$university = $row5['University'];
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`major`, `degree`, `univ`, `afnumber`) VALUES ('$major','$grade','$university','".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
else
{
Use the follwing code
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`major`, `degree`, `univ`, `afnumber`) VALUES ('$major','$grade','$university','".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
else
{
well you are saying that if major, grade and university are empty than insert those empty values in university but the question here is why you want to enter those values if they are empty, even if you want to do so along with inserting afnumber using "$_GET["af"]" variable than you can use following code..
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`afnumber`) VALUES ('".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
its quite short and fulfill the purpose but make sure you have checked null in database for major, grade and univ fields in university table .
iam using JQuery jTable and PHP for my Website.
While Loading Data from Database work perfectly! but when Update the Data: send POST to
edit the rows doesent update MySQL database, just jtable, but after reload the Page "load from mysql" the data is back to befor update.
Delete data work, only update don`t update
my js:
//Prepare jTable
$('#log').jtable({
title: 'Domains',
toolbar: {
hoverAnimation: true, //Enable/disable small animation on mouse hover to a toolbar item.
hoverAnimationDuration: 60, //Duration of the hover animation.
hoverAnimationEasing: undefined, //Easing of the hover animation. Uses jQuery's default animation ('swing') if set to undefined.
items: [] //Array of your custom toolbar items.
},
paging: true,
sorting: true,
pageSize : 10,
pageSizes : [ 2, 5, 10, 15, 20, 50, 75, 100, 200, 500 ],
defaultSorting: 'domain ASC',
actions: {
listAction: 'actions.php?action=list',
createAction: 'actions.php?action=create',
updateAction: 'actions.php?action=update',
// deleteAction: 'actions.php?action=delete'
},
messages: DeutschMessages,
fields: {
id_domain: {
key: true,
title: 'ID',
create: false,
edit: false,
list: true
},
domain: {
title: 'Domainname',
width: '30%'
},
exclude: {
title: 'Exclude',
defaultValue: 'www,ns,ftp,mail,mx,pop,smtp',
width: '40%'
},
dnsip: {
title: 'DNS Server',
width: '20%'
},
key: {
title: 'Key',
sorting: false,
list: false,
width: '20%'
},
enable_a: {
title: 'A',
options: ['1','0'],
sorting: false,
width: '20%'
},
enable_ns: {
title: 'NS',
options: ['1','0'],
sorting: false,
width: '20%'
},
enable_url: {
title: 'URL',
options: ['1','0'],
sorting: false,
width: '20%'
},
max: {
title: 'MAX',
defaultValue: '-1',
sorting: false,
width: '20%'
}
}
});
//Load person list from server
$('#log').jtable('load');
});
and the php script:
//Open database connection
$con = mysql_connect($mysql_host,$mysql_user,$mysql_pass);
mysql_select_db($mysql_db,$con);
//Getting records (listAction)
if($_GET["action"] == "list")
{
if (empty($_POST['search']))
{
$search = NULL;
$result = mysql_query("SELECT COUNT(*) AS RecordCount FROM domains;");
$row = mysql_fetch_array($result);
$recordCount = $row['RecordCount'];
$result = mysql_query("SELECT * FROM domains ORDER BY " . $_GET["jtSorting"] . " LIMIT " . $_GET["jtStartIndex"] . "," . $_GET["jtPageSize"] . ";");
}
else
{
$search = mysql_real_escape_string($_POST['search']);
$result = mysql_query("SELECT COUNT(*) AS RecordCount FROM domains WHERE id_domain LIKE '%".$search."%' or domain LIKE '%".$search."%' or exclude LIKE '%".$search."%' or dnsip LIKE '%".$search."%';");
$row = mysql_fetch_array($result);
$recordCount = $row['RecordCount'];
//Get records from database
$result = mysql_query("SELECT * FROM domains WHERE id_domain LIKE '%".$search."%' or domain LIKE '%".$search."%' or exclude LIKE '%".$search."%' or dnsip LIKE '%".$search."%' ORDER BY " . $_GET["jtSorting"] . " LIMIT " . $_GET["jtStartIndex"] . "," . $_GET["jtPageSize"] . ";");
$_SESSION["query"] = "SELECT * FROM domains WHERE id_domain LIKE '%".$search."%' or domain LIKE '%".$search."%' or exclude LIKE '%".$search."%' or dnsip LIKE '%".$search."%' ORDER BY " . $_GET["jtSorting"];
$_SESSION["contador"] = "SELECT COUNT(*) AS RecordCount FROM domains WHERE id_domain LIKE '%".$search."%' or domain LIKE '%".$search."%' or exclude LIKE '%".$search."%' or dnsip LIKE '%".$search."%'";
}
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
$jTableResult['TotalRecordCount'] = $recordCount;
print json_encode($jTableResult);
}
//Creating a new record (createAction)
else if($_GET["action"] == "create")
{
//Insert record into database
$result = mysql_query("INSERT INTO `domains`(`id_domain`, `domain`, `exclude`, `dnsip`, `key`, `enable_a`, `enable_ns`, `enable_url`, `max`) VALUES ('', '".$_POST["domain"]."','".$_POST["exclude"]."','".$_POST["dnsip"]."','".$_POST["key"]."','".$_POST["enable_a"]."','".$_POST["enable_ns"]."','".$_POST["enable_url"]."','".$_POST["max"]."');");
//Get last inserted record (to return to jTable)
$result = mysql_query("SELECT * FROM domains WHERE id_domain = last_insert_id();"); // WHERE id_domain = last_insert_id();"); // id_domain = LAST_INSERT_ID();");
$row = mysql_fetch_array($result);
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Record'] = $row;
print json_encode($jTableResult);
}
//Updating a record (updateAction)
else if($_GET["action"] == "update")
{
$id = $_REQUEST['id_domain'];
//Update record in database
$result = mysql_query("UPDATE domains SET domain = '" . addslashes($_POST["domain"]) . "', exclude = '" . addslashes($_POST["exclude"]) . "', dnsip = '" . addslashes($_POST["dnsip"]) . "', key = '" . addslashes($_POST["key"]) . "', enable_a = '" . addslashes($_POST["enable_a"]) . "', enable_ns = '" . addslashes($_POST["enable_ns"]) . "', enable_url = '" . addslashes($_POST["enable_url"]) . "', max = '" . addslashes($_POST["max"]) . "' WHERE id_domain = $id;");
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
print json_encode($jTableResult);
}
else if($_GET["action"] == "listname")
...
after hit Update:
Response is always "ok"
i can´t catch the error ./
any help ?
Have you seen this?
updateAction: 'actions.php?action=update',
// deleteAction: 'actions.php?action=delete'
should be:
updateAction: 'actions.php?action=update'
// deleteAction: 'actions.php?action=delete'
without the comma at the end of the first line (you removed the following row so this is the last one.
Furthermore: you should consider to switch to PDO for mysql safe site.
Last but not least: you are not handling errors in the insert query. Try something like:
if(mysql_query("INSERT INTO `domains`
(`id_domain`, `domain`, `exclude`, `dnsip`, `key`, `enable_a`, `enable_ns`, `enable_url`, `max`)
VALUES
('','".$_POST["domain"]."','".$_POST["exclude"]."','".$_POST["dnsip"]."','".$_POST["key"]."','".$_POST["enable_a"]."','".$_POST["enable_ns"]."','".$_POST["enable_url"]."','".$_POST["max"]."');")){ $jTableResult['Result'] = "OK";
}else{
$jTableResult['Result'] = "KO";
}
I am working on recieveing an item from another application with the use of $_POST and I am trying to see if that item already exists in the database. If it does, then $count increases by one. If it does not exist in the database, then it will added in with the use of INSERT INTO.
Here is my code:
<?php
date_default_timezone_set('Asia/Manila');
$today = date('m-d-Y');
echo $today;
$con= mysqli_connect("******","******","******")
or die ('Error: ' . mysql_error());
mysqli_select_db($con,"a3656574_opacmin");
$sql= "SELECT keyWord FROM searchedWords";
$result= mysqli_query($con,$sql);
if($result==$_POST[keyWord])
{
$upD="UPDATE searchedWords SET countr = countr + 1";
while (!mysqli_query($con,$upD))
{
die('Error: ' . mysqli_error($con));
}
}
else
{
$insertIn="INSERT INTO `searchedWords`( `keyWord`, `countr`) values ('$_POST[keyWord]',1)";
while (!mysqli_query($con,$insertIn))
{
die('Error: ' . mysqli_error($con));
}
}
?>
I don't know what's wrong. No items are sent to the database at all. Does anyone know how to fix it?
Change your code like this...
$result= mysqli_query($con,"SELECT keyWord FROM searchedWords");
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if($row['keyWord']==$_POST[keyWord])
{
$upD="UPDATE searchedWords SET countr = countr + 1";
while (!mysqli_query($con,$upD))
{
die('Error: ' . mysqli_error($con));
}
}
$result==$_POST['keyWord'] won't work becase $result is object there so...
After this line
$result= mysqli_query($con,$sql);
You have to fetch the data
$keyword = '';
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$keyword = $row["keyWord"];
}