I just started learning PHP and wanted to call SQL update query for all the values in the array. But I dont know to execute it in PHP.
<?php
$array = array("12345","23456","34567");
//now here how to call each value of arrayy
foreach ($array as $arr) {
$sql_points1 = "UPDATE user_earning SET points = points + '80' WHERE user_number = '//how to get value of number from array.'";
$result_points1 = $conn->query($sql_points1);
if ($result_points1 === TRUE) {
echo "Current points added ";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
In your Foreach loop, the value of the current array element is assigned to $arr, so u can use that in your query.
$sql_points1 = "UPDATE user_earning SET points = points + '80' WHERE user_number = '$arr'";
Please use below code:
<?php
$array = array("12345","23456","34567");
//now here how to call each value of arrayy
foreach ($array as $arr) {
$sql_points1 = "UPDATE user_earning SET points = points + '80' WHERE user_number = $arr";
$result_points1 = $conn->query($sql_points1);
if ($result_points1 === TRUE) {
echo "Current points added ";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
Related
I solved the problem with both the foreach loop stopping after the first iteration, as well as it not writing to the array by adding true to the json_decode. I was unaware that that changed it from object oriented to associated.
include '/var/www/html/api/apitoken.php';
include '/var/www/html/api/secrets.php';
$data = file_get_contents('/var/www/html/api/shOrders.json'); // put the contents of the file into a variable
$shOrders = json_decode($data, true);
$con = mysqli_connect("127.0.0.1",$user,$pass,"api") or die('Could not connect: ' . mysqli_error());
$a=0;
foreach($shOrders['varID'] AS $varID) {
$sql_statement= " SELECT invTrack AS invTrack, varID AS varID, varSKU AS varSku, revelSku AS revelSku, revelInvID AS revelInvID, p.prodID AS prodID, pr.ingredient AS ing, pr.main_product AS mainProduct, pr.product AS product, i.invID AS invC, pr.qty AS QTY
FROM shopifyProd sp
LEFT JOIN product p ON sp.revelSku = p.sku AND p.location = 1
LEFT JOIN prodRecipe pr ON p.prodID = pr.main_product
LEFT JOIN inventory i ON pr.product = i.prodID
WHERE varID =" . $varID . " ; ";
//connect to mysql db and process the statement
$result = mysqli_query($con,$sql_statement);
//var_dump($sql_statement . "<br><br>");
while($row = mysqli_fetch_assoc($result)) {
echo "varID: ";
print_r($row['varID']);
echo "<br>";
if($varID == $row['varID']) {
//set correct invID for product in revel
if (!$row['invC']) {
$revInvID = ( (int) $row['revelInvID']);
}else{
$revInvID = ( (int) $row['invC']);
}
//calculate qty to change in revel
if(!$row['QTY']) {
$changeQTY = $shOrders['soldQTY'][$a];
}else{
$changeQTY = ($row['QTY'] * $shOrders['soldQTY'][$a]);
}
echo $varID . " RESULTS! -- ";
print_r("varSku: " . $shOrders['varSku'][$a]);
echo ", ";
print_r("revelInvID: " . $row['revelInvID']);
echo ", ";
print_r("soldQTY: " . $shOrders['soldQTY'][$a]);
echo ", ";
print_r("ingredient: " . $row['ing']);
echo ", ";
print_r("Product: " . $row['product']);
echo ", ";
print_r("invC: " . $revInvID);
echo ", ";
print_r("changeQTY: " . $changeQTY);
echo "<br><br>";
$shOrders['revProdID'][$a] = ( (int) $row['product']);
$shOrders['revInvID'][$a] = ( (int) $revInvID);
$shOrders['changeQTY'][$a] = ( (float) $changeQTY);
if (!mysqli_query($con, $sql_statement)) {
print_r(mysqli_error_list($con));
echo "<br>";
mysqli_close($con);
}
}
}
$a++;
set_time_limit ( 30 );
}
echo "<pre>";
print_r($shOrders);
echo "</pre>";
var_dump out your query just before you run it, Are all the expected parameters there? Try running that in your local db tool (mysql workbench, phpmyadmin), does it do what you like?
var_dump out the variables at each step of the way and die (or alternatively use a debugger to step through the code 1 line at a time), to see what is happening.
It doesn't look like you've declared $varID above the query.
I think you need to move
foreach($shOrders->varID AS $varID) {
above the $sql_statement = ... line.
My Stored Procedure only works on the first iteration. My code:
// Display Event
$result = mysql_query("select ....",$connection_mercury);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$provider = $row['name'];
$details = mysql_query("CALL $my_schema_to_use.getRefId($provider);",$connection);
while($b_row = mysql_fetch_array($details))
{
$details_result = $b_row['age'] . " - " . $b_row['address'];
}
echo "<td>$details_result</td><td>$id</td>
}
Lets say the outer while loop does 2 loops as expected. But the 'CALL' only returns a value on the first loop every time. The $details variable always remains empty for any loop after the first one.
$details_result varible are overwritting with inner loop.
while($b_row = mysql_fetch_array($details))
{
$details_result = $b_row['age'] . " - " . $b_row['address'];
}
Code should be
while($b_row = mysql_fetch_array($details))
{
$details_result[] = $b_row['age'] . " - " . $b_row['address'];
}
This is cancel_order function,that also in it will call the increase_gameamount() function, i am trying to call increament_gameamount() function it works but when I try to call it from while loop nothing changes in database.
//cancel function
function cancel_order($ord) {
global $conn;
$bqty = 0;
$gqty = 0;
$res = array();
echo "entered cancel function " . $ord . "<br>";
$st = "select (B_qty+G_qty) newqt, B_GM_ID from tb_basket b, tb_game g
where b.B_GM_ID = g.G_ID
and B_O_ID='$ord' ";
$sql = $conn->prepare($st);
$sql->execute();
$sql->bind_result($newqt, $gid);
$i = 0;
while($row = $sql->fetch()) {
$res[$i][0] = $newqt;
$res[$i][1] = $gid;
$i++;
}
$j = 0;
$sql->free_result();
$sql->close();
while($j < sizeof($res)) {
echo $gd = $res[$j][0] . "<br>";
echo $qty = $res[$j][1] . "<br>";
increament_gameamount($gd, $qty);
$j++;
}
}
//increament function
function increament_gameamount($gameid, $new_qty) {
global $conn;
echo "entered increament_gameamount function";
echo $gameid;
echo $new_qty;
$varupdateqty = $conn->prepare("update tb_game set G_qty=? where G_ID=?");
$varupdateqty->bind_param("ss", $new_qty, $gameid);
$varupdateqty->execute();
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
As I stated in the comments I think you are failing on the WHERE of your query because
echo $gd=$res[$j][0]."<br>";
is making $gd a string like 125<br> and the DB cannot find that.
Also, this would cause an error but if the type of your column is int and you pass:
echo $qty=$res[$j][1]."<br>";
again you make $qty something like 1000<br> and that would fail again this would be an error the above for ID check would not.
UPDATE
Just realized I did not specifially state the resolution. Set the variables then echo them and you should be all good.
$gd=$res[$j][0];
$qty=$res[$j][1];
echo $gd . "<br>" . $qty . "<br>";
I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed.
$allstore = $_POST['store'];
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = $store;
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
//Stores to be shown
$allstore = ['s_M9' =>0 , 's_M10' =>1];
$query = (createSelect($allstore));
$result = mysql_query($query);
//rest of code...
As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] .
Now According to the function shown, if I create my own keys and values like this
$allstore = ['s_M9' =>0 , 's_M10' =>1];
the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually?
Thank You
Edit :
<?php
echo "<form action='somewhere.php' method='POST'>";
$query = "SELECT * from stores_list ORDER BY short Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}";
}
}
else{
//No Stores Available
echo "No Stores Found !";
}
echo "</td><input type='submit' value='Search'/></form>";
$allstore = [];
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys
}
}
$query = (createSelect($allstore));
$result = mysql_query($query);
And of course you have to take care of your createSelect function to avoid SQL Injections, please read here
I want to use single for each for two array.
array 1 : has path of images (path is dynamic as per user need)
array 2: has values description field of each image (description is dynamic as per user need)
I want to insert both array in sql table using only one sql statement.
<?php $sql="INSERT INTO posts(title,description,category,createdBy,pictureURL,CreatedAt) VALUE ('$title',
'$description','$category','$creatdby','Admin/PostImages/$finalpath',now());";
$result = mysqli_query($conn,$sql);
if($result)
{
$upload_directory = 'PostImages/';
$field_values_array = $_REQUEST['desc'];
$x=0;
foreach($field_values_array as $value1){
foreach ( $_FILES['photo']['name'] AS $key => $value ){
//Move file to server directory
if(move_uploaded_file($_FILES["photo"]["tmp_name"][$x], $upload_directory . $_FILES["photo"]["name"][$x])){
$finalpath=$upload_directory . $_FILES["photo"]["name"][$x];
}
if (isset($_SESSION['p_id'])){
$p_id = $_SESSION["p_id"];
}
$sql1="INSERT INTO `postimages`(`p_id`,`description`, `img_path`) VALUES ('$p_id','$value1','$finalpath')";
$result1 = mysqli_query($conn,$sql1);
$x++;
}
}
header("Location: uploadpost_test.php");
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
} ?>
I refactor and clean up your codes. Try this.
if(isset($_SESSION['p_id']))
{
$p_id = $_SESSION["p_id"];
}
$values = '';
$next = ',';
$len = count($field_values_array);
foreach($field_values_array as $x=>$value1)
{
if(move_uploaded_file($_FILES["photo"]["tmp_name"][$x], $upload_directory.$_FILES["photo"]["tmp_name"][$x]))
{
$tmp_name = $_FILES["photo"]["tmp_name"][$x];
$finalpath = $upload_directory.$tmp_name;
$next = $x >= $len-1 ? '' : $next;
$values .= "VALUES('$p_id','$value1','$finalpath')".$next;
}
}
$sql1="INSERT INTO `postimages`(`p_id`,`description`, `img_path`) $values";
$result1 = mysqli_query($conn,$sql1);