So, I'm using a database to store ship data.
As I load data into the database, I am checking whether the ship already exists. Sometimes, more than one ship has the same name. This code tries to go through the array, pull out all the ships with the same name, and then ask, in turn if that is the right one- if not, then it's yet another with the same name.
$sql = "SELECT Ship_Primary_Key, ship_original_rate, Ship_Launch_Year from Ships WHERE Ship_Name = '" . $shipname . "'";
$result = $conn->query ($sql);
if ($result-> num_rows > 0) //Does the ship name already exist in the DB? {
$ships_in_db = mysqli_fetch_all ($result,MYSQLI_ASSOC);
foreach ($ships_in_db as $row) {
echo "new record is " . $shipname . " as a " . $shiprate . ". Records already include " . $shipname . ", launched " . $row["Ship_Launch_Year"] . " as a " . $row ['ship_original_ra
$yesno = trim(fread(STDIN,5));
if ($yesno == "y" || $yesno == "yes") {
//ship already exists in the DB. Get the Key
echo $shipname . " is not new to the database and the key is " . $row["Ship_Primary_Key"] . "\n";
$shipkey = $row["Ship_Primary_Key"];
break 1;
}
}
//if you get through the loop of ships without assigning a primary key, ship is new
if (empty($shipkey)) {
$shipkey = write_ship_to_DB($shipname,$shiprate,$launchyear,$launchname,$conn);
}
}
So the problem is, I know that I have at least three ships with the same name in the first set of data (that are different). The problem is, it only ever asks about the first one. When I put 'n', it just goes on, and never asks about the second ship with the same name that already exists.
I think it's a problem with the Foreach loop and the break statement.
I'd appreciate any help with this
I've figured out the problem.
Because of the loop- I wasn't resetting the "Ship_Id" variable, which meant that the second or nth time a ship with the same name came around, a new ship wasn't created.
Now I've solved that. So the problem isn't this code at all- it's other code.
Related
I split this string ($messageText) using a formula like this:
list($msgat, $message) = explode("!", "$messageText", 2);
selecting a row from my database:
with this:
$sql = "SELECT verse FROM ".$datatable." WHERE book LIKE '%".$message."'";
I need to come up with a way to make this: (which works, on a page echoing)
echo " " . $row["book"]. " " . $row["verse"]. "<br>";
something back into a single string: something like this I've been trying.
$answer = " . $row["verse"]. "
thus, I would be able to use the original but changed, variable elsewhere.
I have tried various methods, trying to concoct a solution...
$answer = $row["verse"] ;
etc etc... I am stumped... it is probably right before me I just can't find it.
$answer = " " . $row["book"]. " " . $row["verse"]; //this will store value into single variable answer
echo $answer; // use this if you want to display the result on the page.
this will definitely work if not show us the error so that we can resolve it.
So hey guys!
I currently have a code that gets data from a custom table called wp_refundrequests, and prints them as a table to the page. On the page the admin can either Accept, or Deny the request by pressing a button on the side of each order. Denying the request just deletes the request from the table, but accepting should delete it from the current table and insert the information to the next table called "accepted requests".
The wp_refundrequests table contains customer's order that they want to refund.
The code that gets the info and prints it:
global $wpdb;
$requests = $wpdb->get_results("SELECT * FROM wp_refundrequests", ARRAY_A);
foreach ($requests as $row) {
echo "<div class='requests'>" . "<li class='refunds'>" . "Palauttajan nimi: ".
$row['customer_name'] . "</br>" ."Palautettavat tuotteet: ".$row['product_name']."<br> "."Määrä: ".
$row['product_qty'] . " "
. "<br>Kommentti: " . $row['comment'] . "<br> " . "Hinta: " . $row['refund_total'] . "€ " .
"<br>" . "Päivämäärä: " . $row['request_date'] . " " .
"<a class='right' href='admin-page?deleteid=" . $row['request_id'] . "'>Deny</a></li>" .
"<li class='refundaccepts'><a href='admin-page?acceptid=" . $row['request_id']
. "'>Accept</a></li>" . "</div>";
$_SESSION['custname'] = $row['customer_name'];
$_SESSION['prodname'] = $row['product_name'];
}
With my current code, the "Accept" button deletes it, and inserts information in to the new table, BUT the information that is inserted is wrong. It seems like it wants to either insert the latest data that had been inserted in to the wp_refundrequests table to the wp_acceptedrequests, or it keeps the data from the latest refund request and tries to insert that instead because for example as seen here(Sorry for the bits of Finnish as well):
If I were to click the "Accept" button on the above, older one, the query would still insert it like this:
So it basically inserts the info from the latest refund_request insert and inserts that instead of the one selected. However the one that had been selected still gets deleted from the table.
Here's the code that is triggered when the user clicks on "Accept"
$custname = $_SESSION['custname'];
$prodname = $_SESSION['prodname'];
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
/* Query to do whatever here */
$wpdb->print_error();
$wpdb->insert("wp_acceptedrequests", [
"customer_name" => "$custname",
"name_product" => "$prodname",
"date" => date("Y/m/d/G:i:sa") ,
]);
$wpdb->print_error();
$wpdb->query("DELETE FROM wp_refundrequests WHERE request_id = $accept");
}
I have to say I have no idea why it doesn't want to insert the selected request, please comment if there's something confusing, I'll try to clear it up then.
Thanks in advance!
You redefine $_SESSION with in foreach loop so at the end of foreach it will equal to the last one, pass each row parameter to it is accept link like this
"<li class='refundaccepts'><a href='admin-page?acceptid=" . $row['request_id']."&custname=".$row['customer_name']."&prodname=".$row['product_name']."'>Accept</a></li></div>";
Then call it the same way you get $accept-ID
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
$custname = $_GET['custname'];
$prodname = $_GET['prodname'];
Note:Iuse my phone so make sure if it was a syntax error in the href part of the code
Please try like this and comment out the session variable.
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
$accepted_requests = $wpdb->get_results("SELECT * FROM wp_refundrequests WHERE id = $accept", ARRAY_A);
if( !empty($accepted_requests) ) {
$insert = $wpdb->insert("wp_acceptedrequests", $accepted_requests);
if($insert) {
$wpdb->query("DELETE FROM wp_refundrequests WHERE request_id = $accept");
}
}
}
eBay Platform Notifications recommends periodic polling of the GetOrders API to ensure each and every order is received.
In my case, I have Platform Notifications set-up to parse the XML file received and insert it into a MySQL database using PHP.
Now I am looking to, as recommended, "double pass" using GetOrders, which should essentially give me duplicates for each and every single row (or order).
My structure is rather straightforward. But I have a UNIQUE INDEX for OrderLineItemID which, to my understanding, is the unique identifier for each eBay Order.
Is there a better way to do this than I am currently doing?
//retrieve and escape variables for insertion//
$sql = "INSERT INTO eBayOrders (OrderLineItemID, SalesRecordNumber, BuyerUserID, BuyerEmail, Title, SKU, Quantity, TransactionPrice)
VALUES ('".$orderlineitemid."', '".$recordnumber."', '".$buyeruserid."', '".$buyeremail."', '".$title."', '".$sku."', '".$qty."', '".$transactionprice."')";
}
if ($connect->query($sql) === TRUE) {
echo "New Record Created Successfully";
} else {
echo "Error: " . $sql . "<br />" . $connect->error;
$connect->close();
die();
}
Because of my UNIQUE ON OrderLineItemID, when a duplicate order comes in, the query will result in an error, close the connection, and then exit the script.
I've thought about first checking to see (maybe using a SELECT statement) if the row exists, and then trying an insert, but I'm doing a foreach loop of up to 100 orders using the GetOrders API to run my SQL queries, and it seems like just allowing it to fall to error might be a quicker option, but I'm weary on if this can cause issues down the line.
In all, I'm not familiar with best practices for MySQL "double passes". Anyone have any insight on the best way to conduct this?
edit: here is my entire foreach loop:
foreach ($orders as $order) {
$i++;
$buyeruserid2 = $order->BuyerUserID;
$buyeruserid = mysqli_real_escape_string($connect, $buyeruserid2);
// $extendedorderid = $order->TransactionArray->Transaction->ExtendedOrderID;
$buyeremail2 = $order->TransactionArray->Transaction->Buyer->Email;
$buyeremail = mysqli_real_escape_string($connect, $buyeremail2);
$salesrecordnumber2 = $order->TransactionArray->Transaction->ShippingDetails->SellingManagerSalesRecordNumber;
$salesrecordnumber = mysqli_real_escape_string($connect, $salesrecordnumber2);
$orderlineitemid2 = $order->TransactionArray->Transaction->OrderLineItemID;
$orderlineitemid = mysqli_real_escape_string($connect, $orderlineitemid2);
$title2 = $order->TransactionArray->Transaction->Item->Title;
$title = mysqli_real_escape_string($connect, $title2);
$sku2 = $order->TransactionArray->Transaction->Item->SKU;
$sku = mysqli_real_escape_string($connect, $sku2);
$quantitypurchased2 = $order->TransactionArray->Transaction->QuantityPurchased;
$quantitypurchased = mysqli_real_escape_string($connect, $quantitypurchased2);
$transactionprice2 = $order->TransactionArray->Transaction->TransactionPrice;
$transactionprice = mysqli_real_escape_string($connect, $transactionprice2);
echo $i;
echo "\n";
echo "BuyerUserID: " . $buyeruserid . "\n";
echo "extendedorderid: " . $quantitypurchased . "\n";
echo "BuyerEmail: " . $buyeremail . "\n";
echo "SellingManagerSalesRecordNumber: " . $salesrecordnumber . "\n";
echo "OrderLineItemID: " . $orderlineitemid . "\n";
// echo "ExtendedOrderID: " . $transaction->ExtendedOrderID . "\n";
echo "Title: " . $title . "\n";
echo "SKU: " . $sku . "\n";
echo "QuantityPurchased: " . $quantitypurchased . "\n";
echo "TransactionPrice: " . $transactionprice . "\n";
echo "\n";
$sql = "INSERT INTO eBayOrders (OrderLineItemID, SalesRecordNumber, BuyerUserID, BuyerEmail, Title, SKU, Quantity, TransactionPrice)
VALUES ('".$orderlineitemid."', '".$recordnumber."', '".$buyeruserid."', '".$buyeremail."', '".$title."', '".$sku."', '".$qty."', '".$transactionprice."')";
if ($connect->query($sql) === TRUE) {
echo "New Record Created Successfully";
} else {
echo "Error: " . $sql . "<br />" . $connect->error;
$connect->close();
die();
}
}
To avoid an error when an INSERT fails due to a unique key constraint, we can use the IGNORE option on the INSERT statement.
INSERT IGNORE INTO eBayOrders ...
If you use the IGNORE modifier, errors that occur while executing the INSERT statement are ignored. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row is discarded and no error occurs. Ignored errors generate warnings instead.
But this also affects error conditions other than duplicate key exceptions.
As another option, we can use INSERT ... ON DUPLICATE KEY ...
Documentation available here:
Reference: https://dev.mysql.com/doc/refman/5.7/en/insert.html
I have a form on a html page which allows me to select multiple items. The name of the form is name="region[]
It posts to another page where I use this code:
The region(s) selected:
<?php
$values = $_POST['region'];
foreach ($values as $region){
echo $region;
}
?>
This will display the results of the form perfectly; if there is one value it will print the one value, but if there is more than one then it will print them all.
I need to use the results of this in a query:
<?php
$con=mysqli_connect("****","****","****","****");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT
GoogleBusinessData.BusName,
GoogleBusinessData.BusAddress,
PostcodeTbl.PostcodeFirstTown,
PostcodeTbl.PostcodeFirstArea,
PostcodeTbl.Region,
PostcodeTbl.Postcode,
PostcodeTbl.PostcodeFirstLetters,
PostcodeTbl.PostcodeFirstPart,
PostcodeTbl.Country,
GoogleBusinessData.BusPhone,
GoogleBusinessData.BusCats,
GoogleBusinessData.FaroukCat,
GoogleBusinessData.BusWebsite,
GoogleBusinessData.BusDescription,
GoogleBusinessData.BusGoogleBusinessID,
GoogleBusinessData.BusPageURL,
EmailTable.EmailNumberOfEmails,
EmailTable.EmailAddresses
FROM
GoogleBusinessData
INNER JOIN PostcodeTbl ON GoogleBusinessData.BusPostalCode = PostcodeTbl.Postcode
INNER JOIN EmailTable ON GoogleBusinessData.BusWebsite = EmailTable.EmailWebsite
WHERE EmailTable.EmailNumberOfEmails > 0 AND
GoogleBusinessData.FaroukCat = 'Wedding Planner'
GROUP BY
GoogleBusinessData.BusWebsite
ORDER BY
GoogleBusinessData.BusName ASC
LIMIT 0,20");
while($row = mysqli_fetch_array($result))
{
echo $row['BusName'] . " - " . $row['PostcodeFirstTown'] . " - " . $row['PostcodeFirstArea'] . " - " . $row['Region'] . " - " . $row['Postcode'];
echo "<br>";
}
mysqli_close($con);
?>
So I need to add the condition in the WHERE to only return the results if it contains one of the regions with the form. I tried the following with no joy:
WHERE PostcodeTbl.Region IN ('$region') AND
EmailTable.EmailNumberOfEmails > 0 AND
GoogleBusinessData.FaroukCat = 'Wedding Planner'
But this only returns the last selection (as if there were only one selected).
Can anyone help?
In your first script, you are looping through the items. Each item is put into the variable $region one by one. So after the loop, $region contains the last item. If you construct the where clause at that time, it explains why the query only returns the last item.
To fix this, you'll have to construct a variable (e.g. $regions) that contains a list of regions.
For instance:
$regions = "'" . implode($_POST['region'], "','") . "'";
... WHERE PostcodeTbl.Region IN ('$regions') AND ...
Note that this is potentially unsafe, since the input in $_POST is not validated, so it is better to loop through the array (like you did) and validate each item one by one while constructing the string in $regions. You can use mysqli_real_escape_string for that.
Alternatively, and arguably better, is to use the parameter binding capabilities of mysqli. This is a bit tricky with array variables, but the details on how to do that are already described in this question.
This is my code for the update:
$key = $skills[$ind];
echo "\t\t<td>" . $key . "</td>\n";
//explode using a comma as a delimiter
$data_n = explode(",", $word);
$score[$key][”Rank”] = $data_n[0];
$score[$key][”Level”] = $data_n[1];
$score[$key][”Exp”] = $data_n[2];
echo "\t\t<td>" .$data_n[0] . "</td>\n";
echo "\t\t<td>" .$data_n[1] . "</td>\n";
echo "\t\t<td>" .$data_n[2] . "</td>\n";
$result = mysql_query("UPDATE accounts SET $key ='$data_n[1]' WHERE username = '$user'")
or
die(mysql_error());
Basically, there's a string "key" that is the name of the thing I'm trying to update, but it's just not updating. I've changed "mysql_query" to "print" and it prints out exactly what it's supposed to:
UPDATE accounts SET Total ='1144' WHERE username = 'derekboy'
There aren't any errors. printing out $result shows that it's "True" that it sent the message to MySQL. Can anyone see the problem, because I've been looking for a whole day and still nothing.
All of my code is located here; thanks. You can see that I connect to a database at the very top of the script.
1) You does not seem to have connected to mysql. Does your code do mysql_connect and mysql_select_db prior to this ?
2) Try running the query in the PHPMyAdmin (or whatever MySQL client you use) to see if there's any error or not. Does the query runs fine there ?
3) Most probably, there is no username with value derekboy in your table.
I don't know PHP particularly well, but it seems that you are surrounding the variables with single quotes, in which variables aren't interpolated.
Try something like:
$result = mysql_query("UPDATE accounts SET " . $key . " ='" . $data_n[1] . "' WHERE username = '". $user" . "'") or die(mysql_error());