Jump to content

Search the Community

Showing results for tags 'php'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. I need to create the unique SKU (Stock Keeping Unit) name for each products mixed with product.id,product.name,product.category and product.brand. There is no problem to do it, i.e.: SKU for a product with id=13, name=Bio Clean green and category=INSECTS KILLERS brand=HARPIC becomes : BI-IKHA0013 This is how I tried: $inm = "Bio Clean green500ml"; $cnm = "INSECTS KILLERS"; $bnm = "HARPIC "; echo SKU_gen($inm, $cnm,$bnm,20).'<br>'; function SKU_gen($pname, $cat=null, $brand=null, $id = null, $l = 2){ $results = ''; // empty string $str1 = array_shift(explode(' ',$pname)); $str1 = strtoupper(substr($str1, 0, $l)); $str2 = array_shift(explode(' ',$cat)); $str2 = strtoupper(substr($str2, 0, $l)); $str3 = array_shift(explode(' ',$brand)); $str3 = strtoupper(substr($str3, 0, $l)); $id = str_pad($id , 4, 0, STR_PAD_LEFT); $results .= "{$str1}-{$str2}{$str3}{$id}"; return $results; } But this function is not working as expected when category of brand values become NULL.
  2. I have an index.php file which includes my form and code to move the user's uploaded file to s3. My HTML form calls a js function sendEmails() which makes an AJAX request to another php script dbSystem() to validate the emails input and add it to a database. Everything is working except that the php code in my index.php file (at the very bottom) does not execute. It's supposed to execute when the user uploads a file and presses submit but it doesn't go into the if statement. I tried putting the $fileName = basename($_FILES["fileName"]["name"]) statement before the if statement but I get an undefined index error. I put my a comment in my code to show which if statement I am talking about. This is my HTML code in index.php: <form action="javascript:void(0)" method="POST" id="files" enctype="multipart/form-data"> <label class="col-md-4 col-form-label text-md-right">Select File: <span class="text-danger">*</span></label> <input type="file" id="userFile" name="fileName" style="cursor: pointer; max-width: 170px;" onchange="enableBtn()"> <label class="col-md-4 col-form-label text-md-right">Authorized Users: <span class="text-danger">*</span></label> <input placeholder="Enter e-mail(s) here..." id="req" autocomplete="off"/> <button id="submitBtn" name="submitBtn" class="<?php echo SUBMIT_BUTTON_STYLE; ?>" onclick="return sendEmails()" disabled>Submit</button> </form> This is my php code in index.php: <?php $conn = new mysqli($servername, $username, $password, $db); $sql = "SELECT sender_id, sender_email, receiver_emails, receiver_ids, file_name from filedrop_logs"; $result = mysqli_query($conn, $sql); if ($result) { echo "<div class='outputDiv'>"; echo "<table id='sharedOthers'>"; echo "<thead><tr class='headings'>"; echo "<th class='files'>Files</th>"; echo "<th class='users'>Users</th>"; echo "</tr></thead>"; while ($row = mysqli_fetch_assoc($result)) { $receiverEmails = $row['receiver_emails']; $fileName = $row['file_name']; echo "<tbody id='bodyOthers'>"; echo "<tr id='rowOthers'>"; echo "<td>$fileName<br>"; $objects = getListofObjects('FileDrop'); foreach ($objects as $object) { $file = $object['Key']; $splits = explode('/', $file); if (end($splits) !== '') { $presignedUrl = getPresignedUrlForPrivateFile($object['Key'], '+20 minutes'); $link = '<a href="'.$presignedUrl.'">Download</a>'; echo $link; } } echo "&nbsp;&nbsp;&nbsp;&nbsp;<a href=''>Delete</a></td>"; echo "<td>$receiverEmails</td>"; echo "</tr></tbody>"; } echo "</table></div>"; } ?> <?php //the if statement below doesn't execute if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES["fileName"])) { $fileName = basename($_FILES["fileName"]["name"]); $error = $_FILES["fileName"]["error"]; $tmpName = $_FILES["fileName"]["tmp_name"]; if (isset(fileName) && $fileName != '' && $tmpName != '' && sys_get_temp_dir()) { $separator = DIRECTORY_SEPARATOR; $newDir = sys_get_temp_dir() . $separator . "FileDrop" . microtime(true); if (!file_exists($newDir)) { mkdir($newDir, 0777, true); // creates temp FileDrop directory $tempFilePath = $newDir . $separator . $fileName; // creates temp file inside FileDrop directory if (move_uploaded_file($tmpName, $tempFilePath)) { // moves file to tmp folder $s3FileName = "FileDrop" . substr($newDir, 4) . $separator . $fileName; $result = putFileToS3($s3FileName, $tempFilePath, 'public-read'); deleteDir($newDir); } } } } ?> This is my js code in case you want to see it: function sendEmails() { var fileData = $('#userFile').prop('files')[0]; var formData = new FormData(); formData.append('tags', JSON.stringify(tags)); formData.append('fileName', fileData); $.ajax({ type: "POST", url: "../FileDrop/dbSystem.php", processData: false, contentType: false, data: formData, success: function(result) { result = JSON.parse(result); if (result.validity === "valid emails") { location.reload(); resetInputs(); //IMPORTANT $(".outputDiv").show(); } else { var tagsBrackets = result.emails.toString().replace(/[\[\]']+/g,''); var tagsQuotes = tagsBrackets.replace(/['"]+/g, ''); var tagsInvalid = tagsQuotes.replace(/,/g, ", "); $('#alertModal').modal({show:true}); document.getElementById('invalid').textContent = tagsInvalid; } } }); return false; } I've been stuck on this for so long, so I'd really appreciate the help!!
  3. Data from category table: +-------------+-----------+---------------------+-------------+ | category_id | parent_id | name | description | +-------------+-----------+---------------------+-------------+ | 1 | NULL | Products | NULL | | 2 | 1 | Computers | NULL | | 3 | 2 | Laptops | NULL | | 4 | 2 | Desktop Computers | NULL | | 5 | 2 | Tab PCs | NULL | | 6 | 2 | CRT Monitors | NULL | | 7 | 2 | LCD Monitors | NULL | | 8 | 2 | LED Monitors | NULL | | 9 | 1 | Mobile Phones | NULL | | 10 | 9 | LG Phone | NULL | | 11 | 9 | Anroid Phone | NULL | | 12 | 9 | Windows Mobile | NULL | | 13 | 9 | iPad | NULL | | 14 | 9 | Samsung Galaxy | NULL | | 15 | 1 | Digital Cameras | NULL | | 16 | 1 | Printers and Toners | NULL | | 17 | 14 | Galaxy S Series | NULL | | 18 | 14 | Galaxy Note Series | NULL | | 19 | 14 | Galaxy Z Fold2 5G | NULL | | 20 | 17 | Phone 1 | NULL | | 21 | 17 | Phone 2 | NULL | +-------------+-----------+---------------------+-------------+ Just think, I hava an array of category ids for delete like this: ids = [9,17,20]; Now I want to delete the category related to the above array and update the relevant child category. According to this example, the parent_id of the category_id 10,11,12,13,14 should be 1 The parent_id in category 21 should be updated to 14. In another case, suppose I delete category 9, 18 then all the relevant sub and sub sub categories should be updated as parant category. I hope somebody may help me out. Thank you
  4. I am trying to get rows from MYSQL table (attachment) based on: Select last five rows where status_id = 1 Select last two rows where status_id = 2 *I did use UNION with two SELECT queries to get whole data as one array. Now on PHP side... I have first block for rows having status_id 1 so if there are rows having status_id 1 then PHP should display the data otherwise if there is no row having status_id 1 then PHP should print NO DATA only once. I have second block for rows having status_id 2 so if there are rows having status_id 2 then PHP should display the data otherwise if there is no row having status_id 2 then PHP should print NO DATA only once. I did use foreach loop then within loop i did use if condition to check status_id of rows. it works fine when i omit NO DATA part but when i add it. the result shows both rows and NO DATA in first block when there are one or more rows having status_id 1 but no row having status_id 2 Which made me believe that i was doing it the wrong way. Please guide me *PS: I know its PHP section the thread should be related to PHP problem but... is it right to use UNION in query? or should i post a new thread in relevant section for guidance?
  5. I am having trouble adding sub-topics to my home made blog system running under PHP-Fusion CMS with PHPver7.4.16 with cgi/fcgi interface and MySQL5.7.34-log. Here are 2 images: Here is the module that produces the output. <?php echo "<div class='col-sm-12'>\n"; echo "<table width='100%' border='0'><tr><td><span class='hdspan2'><b>".$locale['gb_810']."</b></span></td></tr></table>\n"; echo "<table align='center' width='80%' border='0'>\n"; $result = dbquery("SELECT * FROM ".DB_GRIMS_BLOG_TOPICS." ORDER BY topic_order ASC"); if (dbrows($result)) { $cnt = 0; while($data = dbarray($result)) { $id = $data['topic_id']; $title = $data['topic_title']; $sub = $data['topic_sub']; $result1 = dbquery("SELECT * FROM ".DB_GRIMS_BLOG_POST." WHERE topic_id='$id'"); $num_rows = dbrows($result1); if ($sub == '1') { echo "<tr><td width='15'></td><td><a class='lnk-side' href='".BASEDIR."grims_blog/topics_page.php?topic_id=".$id."'>$title</a><span style='font-size:11px;color:white;'>&nbsp;[$num_rows posts]</span></td></tr>\n"; } else { echo "<tr><td colspan='2'><a class='lnk-side' href='".BASEDIR."grims_blog/topics_page.php?topic_id=".$id."'>$title</a><span style='font-size:11px;color:white;'>&nbsp;[$num_rows posts]</span></td></tr>\n"; } } $cnt++; } echo "</table><p></div>\n"; ?> The topic_order field is a new field I added to get the desired output but it's not standard procedure and is in fact not really workable in a live setting because I would have to use php_myadmin to modify it everytime I added or deleted a topic or sub-topic. So the bottom line is that I can't figure out anyway to code the script to always show the sub-topic right under the associated main topic and all in order. If I add a sub-topic to one of the upper main topics it shows up at the bottom; hence the addition of the topic_order field. So right now it's basically a mess and I can't figure out how to code everything to work correctly. I have searched the forums here as well as several other sites and cannot get any clues.
  6. After several attempts, I now have data displayed on my index.php page, but the data is from all rows. Luckily I have two rows. The page also has a menu - with two links. What I would like help with is: How to display index.php with just the data for it - i.e. home page data. How to display data if either the ‘home’ or ‘copyright’ links are clicked. I understand you can use $_GET[‘id’], and isset(), but I don’t know how to do that. I include the full html page code: <?php // database connection require_once('admin/databasecon.php'); ?> <!DOCTYPE html> <html> <?php include 'includes/headsection.php'; ?> <body> <?php // displaying data $table = "pages"; // table $sqli = "SELECT * FROM $table ORDER BY id ASC"; $result = $conn->query($sqli); ?> <!-- topMenu --> <table id="topMenu"> <tr> <td><h1 class="siteName">Scarab Beetle</h1></td> <?php if ($result = mysqli_query($conn, $sqli)) { while($row = $result->fetch_assoc()) { echo "<td class='navItem'>" . "<a href=index.php>" . $row["menuheader"] . "</a>" . "</td>"; } } ?> </tr> </table> <!-- topMenu end --> <!-- timeline menu --> Menu goes here <!-- timeline menu end --> <!-- page title --> <?php if ($result = mysqli_query($conn, $sqli)) { while($row = $result->fetch_assoc()) { echo "<h1 class='centered'>" . $row["pageheader"] . "</h1>"; } } ?> <hr> <!-- page content --> <?php if ($result = mysqli_query($conn, $sqli)) { while($row = $result->fetch_assoc()) { echo $row["pagetext"]; } } ?> <hr> <div class="clear"></div> <!-- footer content --> <?php include 'includes/footersection.php'; ?> <!-- footer content end --> </body> </html> Any help to achieve what I want will be appreciated. Thank you.
  7. Hi Everyone I am having a few issues with my website. I have developed in on my xampp local host and it works ok but when I upload the files and try to renew a membership using stripe I get the following messages. Warning: session_start(): Cannot start session when headers already sent in /customers/a/d/f/mywebsite.co.uk/httpd.www/mywebsite/inc/settings.php on line 2 Warning: Cannot modify header information - headers already sent by (output started at /customers/a/d/f/mywebsite.co.uk/httpd.www/mywebsite/procedures/payments/charge.php:1) in /customers/a/d/f/mywebsite.co.uk/httpd.www/mywebsite/procedures/payments/charge.php on line 141 I have some includes that appear on every page. This is the bootstrap.php file. This file holds the settings.php which connects to my database and other function files. In this settings page I call the session_start() php function and then connect to my database. I call the bootstrap.php file on every page to there for call the session_start() on every page. I am using sessions alot so is this the right thing to do? I have attached the renew_membership payment page which holds the form. The user fills out the payment page and the form data gets sent to a script called charge.php which uses the stripe objects to make the payment. I then want to do a redirect to the paymentSuccess.php page to output to the user that the payment was made successfully. This is where the issues arrise. I have split the charge file into 3 screen shots so it is more readable. Hope someone can help me. Thanks a lot David
  8. I am trying to populate a custom field called "Customer Type" current user role. The custom field is displayed on my checkout page. I tried the below in my functions.php of my child theme and thought it would work but it does nothing. Can anyone tell me what I might be doing wrong? $user = wp_get_current_user(); function onboarding_update_fields( $fields = array() ) { $fields['customertype'] = $user; return $fields; } add_filter( 'woocommerce_checkout_fields', 'onboarding_update_fields' );
  9. I'd love to use anonymous placeholders on my ecommerce site project. I am writing half with php and half with golang. On the three examples below, when run, gives the following exception, " Error: Call to a member function execute() on string. " I tried it with a decimal too. Thanks in advance. $stmt = $dbo->prepare = ("SELECT * FROM products WHERE ProductName = ?"); //this one calls exception $stmt->execute(); $stmt = $dbo->prepare = ("SELECT * FROM products WHERE ProductName = ?"); //this one calls exception $stmt->bindParam(1, $productID, PDO::PARAM_INT); $stmt->execute(); $stmt = $dbo->prepare = ("SELECT * FROM products WHERE ProductName = ?"); //this one calls exception $stmt->bindValue(1, $productID, PDO::PARAM_INT); $stmt->execute(); Here is the rest of the code : <?php $filename = ""; $keyword1 = $_GET['keyword']; $titleOfSelectedDropDown = $_GET['val1']; $fileID = ""; $imageID = "a"; $displayID = ""; $keyword1 = "test"; $titleOfSelectedDropDown = "cc"; $host = 'localhost'; $user = 'root'; $pass = ''; $database = 'ecommerce'; $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false ); $gKeyword1 = ""; $gKeyword2 = ""; $gKeyword3 = ""; $key1ID = ""; $key2ID = ""; $key3ID = ""; $string1 = "<center><h1><u>Search Results</u><h1></center></p>"; $dbo = new PDO("mysql:host=$host;dbname=$database", $user, $pass, $options); $stmt = $dbo->prepare = ("SELECT * FROM products WHERE ProductName = ?"); $test = "1"; $stmt->execute([ $test ]);
  10. Hi all, I am trying to get data from MySQL to display in a html table in TCPDF but it is only displaying the ID. $accom = '<h3>Accommodation:</h3> <table cellpadding="1" cellspacing="1" border="1" style="text-align:center;"> <tr> <th><strong>Organisation</strong></th> <th><strong>Contact</strong></th> <th><strong>Phone</strong></th> </tr> <tbody> <tr>'. $id = $_GET['id']; $location = $row['location']; $sql = "SELECT * FROM tours WHERE id = $id"; $result = $con->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { '<td>'.$location.'</td> <td>David</td> <td>0412345678</td> </tbody>'; } } '</tr> </table>'; Anyone got any ideas?
  11. Hello! I found this code from github. https://github.com/gburtini/Learning-Library-for-PHP and I want to know if its possible to add variables to it and what changes needed to be done to the whole script. My first guess is the variables are $xs and $ys I want replace them and add two more. The whole code is here: <?php require_once 'function.php'; function ll_nn_predict($xs, $ys, $row, $k) { $distances = ll_nearestNeighbors($xs, $row); $distances = array_slice($distances, 0, $k); $predictions = array(); foreach($distances as $neighbor=>$distance) { $predictions[$ys[$neighbor]]++; } asort($predictions); return $predictions; } function ll_nearestNeighbors($xs, $row) { $testPoint = $xs[$row]; $distances = _ll_distances_to_point($xs, $testPoint); return $distances; } function _ll_distances_to_point($xs, $x) { $distances = array(); foreach($xs as $index=>$xi) { $distances[$index] = ll_euclidean_distance($xi, $x); } asort($distances); array_shift($distances); return $distances; } and the function.php that is required is this: <?php function ll_transpose($rows) { $columns = array(); for($i=0;$i<count($rows);$i++) { for($k = 0; $k<count($rows[$i]); $k++) { $columns[$k][$i] = $rows[$i][$k]; } } return $columns; } function ll_mean($array) { return array_sum($array)/($array); } function ll_variance($array) { $mean = ll_mean($array); $sum_difference = 0; $n = count($array); for($i=0; $i<$n; $i++) { $sum_difference += pow(($array[$i] - $mean),2); } $variance = $sum_difference / $n; return $variance; } function ll_euclidean_distance($a, $b) { if(count($a) != count($b)) return false; $distance = 0; for($i=0;$i<count($a);$i++) { $distance += pow($a[$i] - $b[$i], 2); } return sqrt($distance); } I just want to know where is the variables in those 2 scripts and add more as I'm not well versed in using PHP. Thank you!
  12. The $a variable contains the news text. The $link variable contains a link to the page with the full text of this news. Need to write the abbreviated text of the news in the $b variable according to the rules: - crop up to 180 characters - assign an ellipsis - make the last 2 words and ellipsis a link to the full text of the news.
  13. Hi everyone. Please help me please. I'm just learning PHP. There was a task, I completed it, but they sent a response that it needs to be modified. You need to make changes: "When saving data, you need to take into account the keys of the new data and the data stored in the database(file), if the value with the key in the database(file) already exists, then you need to replace its value with a new one." and "The FileBox and DbBox classes should be implemented in such a way that you can not create more than one instance of each of the classes." Googled and came across what i need to apply the singleton pattern. <?php interface Box { public function setData($key, $value); public function getData($key); public function save(); public function load(); } abstract class BoxAbstract implements Box { protected $data = []; public function setData($key, $value) { $this->data[$key] = $value; } public function getData($key) { return $this->data[$key] ?? null; } public abstract function save(); public abstract function load(); } class FileBox extends BoxAbstract { private $file; public function __construct($file) { $this->file = $file; } public function save() { file_put_contents($this->file, serialize($this->data)); } public function load() { $this->data = unserialize(file_get_contents($this->file)); } } class DbBox extends BoxAbstract { private $pdo; public function __construct(\PDO $pdo) { $this->pdo = $pdo; } public function save() { $this->pdo->beginTransaction(); $this->pdo->query('DELETE FROM box')->execute(); $stmt = $this->pdo->prepare("INSERT INTO box (key, value) VALUES (:key, :value)"); foreach ($this->data as $key => $value) { $stmt->bindValue(':key', $key); $stmt->bindValue(':value', serialize($value)); $stmt->execute(); } $this->pdo->commit(); } public function load() { $stmt = $this->pdo->query('SELECT key, value FROM box_items'); $data = []; while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $data[$row['key']] = unserialize($row['value']); } $this->data = $data; } }
  14. Hi everyone. I'm very new into self learning programming. Presently I'm trying to develop a simple basic Robot that would only Place a Market Order every seconds and it will cancel the Order every followed seconds. Using the following library: https://docs.b2bx.exchange/en/_docs/api-reference.html#private-api It would place Trade Order at a ( Price = ex.com api * Binance api Aggregate Trades Price) I have already wrote the api to call for xe.com exchange rate with php <?php $auth = base64_encode("username:password"); $context = stream_context_create([ "http" => [ "header" => "Authorization: Basic $auth" ] ]); $homepage = file_get_contents("https://xecdapi.xe.com/v1/convert_from?to=NGN&amount=1.195", false, $context ); $json = json_decode($homepage, TRUE); foreach ($json as $k=>$to){ echo $k; // etc }; ?> And also for the Binance Aggregate Price in JavaScript <script> var burl = "https://api3.binance.com"; var query = '/api/v3/aggTrades'; query += '?symbol=BTCUSDT'; var url = burl + query; var ourRequest = new XMLHttpRequest(); ourRequest.open('GET',url,true); ourRequest.onload = function(){ console.log(ourRequest.responseText); } ourRequest.send(); </script> My problem is how to handle these two api responds and also the functions to use them to place a trade and cancel it. Please help me out. Thanks in advance on any help.
  15. Hello everyone. I'm just learning programming. I have a class: class DbBox extends BoxAbstract { public function save() { } public function load() { } } This class has two methods, Load and Save. How to format them correctly so that they can save data to a file?
  16. Hi guys, I really hope this will make sense. I am creating a dynamic field on a button click for Pickup Location. That works fine and submitting the form to the database works fine. However, instead of one entry, each time I submit the form with multiple Pickup Locations, it creates multiple separate database entries. Here is the PHP for submitting: if(isset($_POST['new']) && $_POST['new']==1){ $pickups = ''; foreach($_POST['pickups'] as $cnt => $pickups) $pickups .= ',' .$pickups; $locations = count($_POST["pickups"]); if ($locations > 0) { for ($i=0; $i < $locations; $i++) { if (trim($_POST['pickups'] != '')) { $name = mysqli_real_escape_string($con, $_POST['name']); $price = mysqli_real_escape_string($con, $_POST['price']); //$origin = $_POST['origin']; $pickups = $_POST["pickups"][$i]; $destination = mysqli_real_escape_string($con, $_POST['destination']); $dep_date = mysqli_real_escape_string($con, $_POST['dep_date']); $ret_date = mysqli_real_escape_string($con, $_POST['ret_date']); $fleet_number = mysqli_real_escape_string($con, $_POST['fleet_number']); $driver = mysqli_real_escape_string($con, $_POST['driver']); $itinerary = mysqli_real_escape_string($con, $_POST['itinerary']); $submittedby = mysqli_real_escape_string($con, $_SESSION["username"]); $trn_date = mysqli_real_escape_string($con, date("Y-m-d H:i:s")); $query="insert into tours (`name`, `price`, `pickups`, `destination`, `dep_date`, `ret_date`, `fleet_number`, `driver`, `itinerary`, `submittedby`, `trn_date`)values ('$name', '$price', '$pickups', '$destination', '$dep_date', '$ret_date', '$fleet_number', '$driver', '$itinerary', '$submittedby', '$trn_date')"; mysqli_query($con,$query) or die(mysqli_error($con)); if(mysqli_affected_rows($con)== 1 ){ $message = '<i class="fa fa-check"></i> - Record Inserted Successfully'; } } } } } Here is the HTML form: <form role="form" method="post" name="add_tour" id="add_tour" action""> <input type="hidden" name="new" value="1" /> <div class="modal-body"> <div class="row form-group"> <div class="col-6"> <div class="form-group"><label for="name" class=" form-control-label">Name</label><input type="text" id="name" name="name" placeholder="Tour Name" class="form-control"> </div> </div> <div class="col-6"> <div class="form-group"><label for="price" class=" form-control-label">Price</label><input type="text" id="price" name="price" placeholder="0.00" class="form-control"> </div> </div> </div> <div class="row form-group"> <div class="col-6"> <div class="form-group origin" id="pickupsfield"><label for="pickups" class=" form-control-label">Pickup Location</label><input type="text" id="pickups" name="pickups[]" placeholder="Start Typing..." class="form-control"></div> <button type="button" class="btn btn-success add-field" id="add" name="add">Add New Location &nbsp; <span style="font-size:16px; font-weight:bold;">+ </span> </button> </div> <div class="col-6"> <div class="form-group"><label for="destination" class=" form-control-label">Destination</label><input type="text" id="destination" name="destination" placeholder="Start Typing..." class="form-control"></div> </div> </div> <div class="row form-group"> <div class="col-6"> <div class="form-group"><label for="dep_date" class=" form-control-label">Departure Date</label><input type="date" id="dep_date" name="dep_date" placeholder="" class="form-control"></div> </div> <div class="col-6"> <div class="form-group"><label for="ret_date" class=" form-control-label">Return Date</label><input type="date" id="ret_date" name="ret_date" placeholder="" class="form-control"></div> </div> </div> <div class="row form-group"> <div class="col-6"> <div class="form-group"><label for="fleet_number" class=" form-control-label">Fleet Number</label> <select class="form-control" id="fleet_number" name="fleet_number"> <option value="Select">== Select Fleet Number ==</option> <?php $sql = "SELECT fleet_number FROM fleet"; $result = $con->query($sql); while(list($fleet_number) = mysqli_fetch_row($result)){ $option = '<option value="'.$fleet_number.'">'.$fleet_number.'</option>'; echo ($option); } ?> </select> </div> </div> <div class="col-6"> <?php ?> <div class="form-group"><label for="driver" class=" form-control-label">Driver</label> <select class="form-control" id="driver" name="driver"> <option value="Select">== Select Driver ==</option> <?php $sql = "SELECT name FROM drivers"; $result = $con->query($sql); while(list($driver) = mysqli_fetch_row($result)){ $option = '<option value="'.$driver.'">'.$driver.'</option>'; echo ($option); } ?> </select> </div> </div> </div> <div class="form-group"><label for="itinerary" class=" form-control-label">Itinerary</label> <textarea class="form-control" id="itinerary" name="itinerary"></textarea> </div> <div class="modal-footer"> <button type="reset" class="btn btn-warning">Clear Form</button> <button type="submit" name="submit" id="submit" class="btn btn-primary">Confirm</button> </div> </form> And the Javascript for adding the new fields: <script> $(document).ready(function(){ var i = 1; $("#add").click(function(){ i++; $('#pickupsfield').append('<div id="row'+i+'"><input type="text" name="pickups[]" placeholder="Enter pickup" class="form-control"/></div><div><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></div>'); }); $(document).on('click', '.btn_remove', function(){ var button_id = $(this).attr("id"); $('#row'+button_id+'').remove(); }); $("#submit").on('click',function(){ var formdata = $("#add_tour").serialize(); $.ajax({ url :"", type :"POST", data :formdata, cache :false, success:function(result){ alert(result); $("#add_tour")[0].reset(); } }); }); }); </script> Anyone have any idea where I am going wrong? Before you say it, Yes, I know, Use Prepared statements 😷
  17. Hi all, Hope to find you all good. I have the following, which creates a php file. This works fine and without error. However, once created, the content of the page, which is got from the Database, is not showing. <?php include_once('includes/header.php'); if(isset($_POST['new']) && $_POST['new']==1){ if(isset($_POST['submit'])){ $trn_date = mysqli_real_escape_string($con, date("Y-m-d H:i:s")); $name = mysqli_real_escape_string($con, $_POST['name']); $description = mysqli_real_escape_string($con, $_POST['description']); $body = mysqli_real_escape_string($con, $_POST['body']); $submittedby = mysqli_real_escape_string($con, $_SESSION["username"]); $sql = "SELECT * FROM pages WHERE name='$name'"; $res = mysqli_query($con, $sql); if (mysqli_num_rows($res) > 0) { $message = '<i class="fa fa-times text-danger"> - A Page already exists with that name!</i>'; }else{ $ins_query="insert into pages (`trn_date`,`name`,`description`, `body`, `submittedby`)values ('$trn_date','$name','$description', '$body', '$submittedby')"; mysqli_query($con,$ins_query) or die(mysqli_error($con)); if(mysqli_affected_rows($con)== 1 ){ // Name of the template file. $template_file = 'template.php'; // Root folder if working in subdirectory. Name is up to you ut must match with server's folder. $base_path = '/protour/'; // Path to the directory where you store the "template.php" file. $template_path = 'includes/'; // Path to the directory where php will store the auto-generated couple's pages. $page_path = '../'; // Posted data. $row['name'] = str_replace(' ', '', $_POST['name']); $row['description'] = str_replace(' ', '', $_POST['description']); $row['body'] = $_POST['body']; // Data array (Should match with data above's order). $placeholders = array('{name}', '{description}', '{body}'); // Get the template.php as a string. $template = file_get_contents($template_path.$template_file); // Fills the template. $new_file = str_replace($placeholders, $row, $template); // Generates couple's URL and makes it frendly and lowercase. $page_url = str_replace(' ', '', strtolower($row['name'].'.php')); // Save file into page directory. $fp = fopen($page_path.$page_url, 'w'); fwrite($fp, $new_file); fclose($fp); // Set the variables to pass them to success page. $_SESSION['page_url'] = $page_url; // If working in root directory. $_SESSION['page_path'] = str_replace('.', '', $page_path); // If working in a sub directory. $_SESSION['page_path'] = substr_replace($base_path, '', -1).str_replace('.', '',$page_path); $message = '<i class="fa fa-check"></i> - Page Created Successfully'; } } } } ?> <!-- Header--> <div class="breadcrumbs"> <div class="col-sm-4"> <div class="page-header float-left"> <div class="page-title"> <h1>Pages</h1> </div> </div> </div> <div class="col-sm-8"> </div> </div> <div class="content mt-3"> <div class="animated fadeIn"> <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-header"><strong>Add </strong><small>Page <?php if($message = isset($message) ? $message : ''){ printf($message); } ?></small></div> <div class="card-body card-block"> <form role="form" method="post" action""> <input type="hidden" name="new" value="1" /> <div class="modal-body"> <div class="form-group"><label for="name" class=" form-control-label">Page Name</label><input type="text" id="name" name="name" placeholder="name" class="form-control"> </div> <div class="form-group"><label for="description" class=" form-control-label">Description</label><input maxlength="100" type="text" id="description" name="description" placeholder="descriptioon" class="form-control"></div> <div class="form-group"><label for="body" class=" form-control-label">Body</label> <textarea class="form-control" id="body" name="body" placeholder="body"></textarea> </div> <div class="modal-footer"> <button type="submit" name="submit" id="submit" class="btn btn-primary">Confirm</button> </div> </form> </div> </div> </div><!-- .animated --> </div><!-- .content --> </div><!-- /#right-panel --> <!-- Right Panel --> <script src="assets/js/vendor/jquery-2.1.4.min.js"></script> <script src="assets/js/popper.min.js"></script> <script src="assets/js/plugins.js"></script> <script src="assets/js/main.js"></script> <script src="assets/js/bing.js"></script> <script src="assets/js/lib/data-table/datatables.min.js"></script> <script src="assets/js/lib/data-table/dataTables.bootstrap.min.js"></script> <script src="assets/js/lib/data-table/dataTables.buttons.min.js"></script> <script src="assets/js/lib/data-table/buttons.bootstrap.min.js"></script> <script src="assets/js/lib/data-table/jszip.min.js"></script> <script src="assets/js/lib/data-table/pdfmake.min.js"></script> <script src="assets/js/lib/data-table/vfs_fonts.js"></script> <script src="assets/js/lib/data-table/buttons.html5.min.js"></script> <script src="assets/js/lib/data-table/buttons.print.min.js"></script> <script src="assets/js/lib/data-table/buttons.colVis.min.js"></script> <script src="assets/js/lib/data-table/datatables-init.js"></script> <script src="https://cdn.tiny.cloud/1/sw6bkvhzd3ev4xl3u9yx3tzrux4nthssiwgsog74altv1o65/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script> <script> tinymce.init({ selector: 'textarea', plugins: 'advlist autolink lists link image charmap print preview hr anchor pagebreak', toolbar_mode: 'floating', }); </script> <script type="text/javascript"> $(document).ready(function() { $('#customer-table').DataTable(); } ); </script> </body> </html> My guess is the placeholder section is not working. // Posted data. $row['name'] = str_replace(' ', '', $_POST['name']); $row['description'] = str_replace(' ', '', $_POST['description']); $row['body'] = $_POST['body']; // Data array (Should match with data above's order). $placeholders = array('{name}', '{description}', '{body}'); Here is template.php <?php include_once('includes/header.php'); require_once('admin/includes/config.php'); if(isset($_POST['new']) && $_POST['new']==1){ $trn_date = mysqli_real_escape_string($con, date("Y-m-d H:i:s")); $name = mysqli_real_escape_string($con, $_POST['name']); $email = mysqli_real_escape_string($con, $_POST['email']); $pickup = mysqli_real_escape_string($con, $_POST['pickup']); $dropoff = mysqli_real_escape_string($con, $_POST['dropoff']); $dep_date = mysqli_real_escape_string($con, $_POST['dep_date']); $ret_date = mysqli_real_escape_string($con, $_POST['ret_date']); $dep_time = mysqli_real_escape_string($con, $_POST['dep_time']); $pax_numbers = mysqli_real_escape_string($con, $_POST['pax_numbers']); $ins_query="insert into quotes (`trn_date`,`name`,`email`, `pickup`, `dropoff`, `dep_date`, `ret_date`, `dep_time`, `pax_numbers`) values ('$trn_date','$name','$email', '$pickup', '$dropoff', '$dep_date', '$ret_date', '$dep_time', '$pax_numbers')"; mysqli_query($con,$ins_query) or die(mysqli_error($con)); if(mysqli_affected_rows($con)== 1 ){ $message = "Thank you. We will be in touch soon."; } } $sql = "SELECT * FROM slide"; $result = $con->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { ?> <div class="hero-wrap" style='background-image: url("admin/uploads/<?php echo $row['image']; ?>")' data-stellar-background-ratio="0.5"> <div class="overlay"></div> <div class="container"> <div class="row no-gutters slider-text justify-content-start align-items-center"> <div class="col-lg-6 col-md-6 ftco-animate d-flex align-items-end"> <div class="text"> <p style="font-size: 18px;"><?php echo $row['slide_text']; ?></p> <a href="<?php echo $row['youtube']; ?>" class="icon-wrap popup-vimeo d-flex align-items-center mt-4"> <div class="icon d-flex align-items-center justify-content-center"> <span class="ion-ios-play"></span> </div> <div class="heading-title ml-5"> <span>Play Our Short Video</span> </div> </a> </div> </div> <div class="col-lg-2 col"></div> <div class="col-lg-4 col-md-6 mt-0 mt-md-5 d-flex"> <form method="post" action="" role="form" class="request-form ftco-animate"> <input type="hidden" name="new" value="1" /> <h2>Get A Quote</h2> <div class="d-flex"> <div class="form-group mr-2"> <label for="name" class="label">Name</label> <input class="form-control" type="text" id="name" name="name" placeholder="Your Name" /> </div> <div class="form-group ml-2"> <label for="email" class="label">Email</label> <input class="form-control" type="email" id="email" name="email" placeholder="Your Email" /> </div> </div> <div class="form-group"> <label for="searchBox" class="label">Pick-Up Location</label> <input class="form-control" type="text" id="searchBox" name="pickup" placeholder="Start Typing..." /> </div> <div class="form-group"> <label for="searchBoxAlt" class="label">Drop-Off Location</label> <input type="text" class="form-control" id="searchBoxAlt" name="dropoff" placeholder="Start Typing..." /> </div> <div class="d-flex"> <div class="form-group mr-2"> <label for="" class="label">Departure Date</label> <input type="text" class="form-control" id="book_pick_date" name="dep_date" placeholder="Date"> </div> <div class="form-group ml-2"> <label for="" class="label">Return Date</label> <input type="text" class="form-control" id="book_off_date" name="ret_date" placeholder="Date"> </div> </div> <div class="d-flex"> <div class="form-group mr-2"> <label for="" class="label">Pick-Up Time</label> <input type="text" class="form-control" id="time_pick" name="dep_time" placeholder="Time"> </div> <div class="form-group ml-2"> <label for"" class="label">Passenger Numbers</label> <input type="number" class="form-control" id="pax_numbers" name="pax_numbers" placeholder="Amount" /> </div> </div> <div class="form-group"> <button type="submit" class="btn btn-primary py-3 px-4">Request Quote</button> <p><?php if($message = isset($message) ? $message : ''){ printf($message); } ?></p> </div> </form> </div> </div> </div> </div> <?php } } ?> <script type="text/javascript" src="https://www.bing.com/api/maps/mapcontrol?key=AqIY0ivSCCdBIe3-EKGuox9cwBFw2wWRWIErZi1iy57EfD67PoiSra9wl_wu48de&callback=bingMapsReady" async defer></script> <?php if(isset($_GET['id'])){ $id = mysqli_real_escape_string($con, $_GET['id'] ?? DEFAULT_ID); $sql = "SELECT * FROM pages WHERE id = $id"; $result = $con->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_array()) { ?> <!-- HOW IT WORKS --> <section class="ftco-section ftco-no-pt ftco-no-pb"> <div class="container"> <div class="row no-gutters"> <div class="col-md-12 wrap-about py-md-5 ftco-animate"> <div class="heading-section mb-5 pl-md-5"> <span class="subheading"><?php echo $row['description']; ?> </span> <h2 class="heading"><?php echo $row['name']; ?></h2> <?php echo $row['body']; ?> </div> </div> </div> </div> </section> <?php } } } ?> <!-- FOOTER --> <?php include_once('includes/footer.php'); ?> Please note that this is just a project and will not be going live. It's for learning purposes and I am aware there are some vulnerabilities within parts of the code. Any assistance with the above issues though would really be appreciated. Thanks and have a ripper evening.
  18. Is there any function in php lib that does the following $a = 1238; $n = 48; // 1*2*3*8 or I will have to create one for my script? (I want to do it for both client and server sides based on request sent by user. I actually want it in php that is why i asked it here, but if the solution (as function) is available in javascript (not jQuery) please share or guide me.)
  19. I have 11 news then i want to display like first column need only one news second column need 5 news third column need the rest of 5 news I tried this but no luck, it shows first column and second column and the rest outside column $rows = array( 'Title1', 'Title2', 'Title3', 'Title4', 'Title5', 'Title6', 'Title7', 'Title8', 'Title9', 'Title10', 'Title11', ); $total_rows = count($rows); $total_cols = $total_rows - 1;// remove first one for the first column $left_column = ceil($total_cols / 2); $right_column = $total_cols - $left_column; $i = 0; foreach ($rows as $row) { $i++; if ($i == 1) { $class = "primary_post"; echo "<div class='col-md-4 main'>"; } elseif ($i <= $left_column) { $class = "other_post"; echo "<div class='col-md-4 left'>"; } elseif ($i == $right_column) { $class = "other_post"; echo "<div class='col-md-4 right'>"; } else { $class = "other_post"; } echo "<div class='card {$class}'>$i</div>"; if ($i == 1 || $i == $left_column || $i == $right_column) { echo "</div>"; } else { echo ""; } } echo "</div>";
  20. Hi, this query runs fine when I run it from PHPMyAdmin: UPDATE `tran_term_taxonomy` SET `description` = (SELECT keyword from `good_keywords` ORDER BY RAND() LIMIT 1,1) WHERE `tran_term_taxonomy`.`taxonomy` = 'post_tag' AND `tran_term_taxonomy`.`description` = "" LIMIT 1 However, when I run the same query in a PHP file on my server, the page doesn't load at all. The message I get is: www.somesite.com is currently unable to handle this request. HTTP ERROR 500. This is my PHP code: <?php include("/database/connection/path/db_connect.php"); $result4 = mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE `tran_term_taxonomy` SET `description` = (SELECT keyword from `good_keywords` ORDER BY RAND() LIMIT 1,1) WHERE `tran_term_taxonomy`.`taxonomy` = 'post_tag' AND `tran_term_taxonomy`.`description` = "" LIMIT 1"); echo $result4; ?> So how do I make this query work please? Thanks for your guidance.
  21. I've been working on JSON and have found a way to send variables from the PHP to the JavaScript using AJAX and no JQuery. For an ecommerce site does it make more sense to send the variables : description, title, cost, etc. to the JavaScript page, or would it make more sense to echo the html on the PHP page? The idea, right now, is a product page for editing and deleting product. Thanks, Josh
  22. I am generating a csv dynamically and getting it downloaded from php but after download the csv only contain the data from database not the heading or the column name of the database. example: my table contain "users" as column name and it has 4 rows like "ram" "sam" "hari" "sita". then after download of csv, the csv is showing only ram, sam, hari sita not the column name users. How to do that? because it is difficult to know who the ram sam are,, are they any vegetables or users
  23. If yall have a moment go read my introductions. The short version is that I lost a lot of my memory due to a fall I had in 2014 while working for the big blue retail store with one or two registers open! haha. I am not allowed to talk about it so maybe you will know who I am referring too. Anyhow before that I was pretty knowledgeable and was doing great at fixing things as they came up. Now unfortunately while working on something my mind sometimes slips and I forget what I was working on and cant solve issues. The last couple of days has been a struggle for me. I have a error showing up and I know its got to be a stupidly simple fix I am overlooking or overthinking and I cant figure it out. The first issue I resolved. It was a typo. But this one is out to corrupt my brain even more, every time I go to think about it my brain craps out on me and I begin phasing out as I look onward on the screen. The error is filling my log full of entries over this one simple issue. I think its something to do with a facebook addition we added a few years back. The Errors are: htmlspecialchars() expects parameter 2 to be long, string given in class.opengraph.php at 67 File Line Function _LOG->HandlePHPErrors class.opengraph.php 67 htmlspecialchars class.page.php 249 s_OPENGRAPH::getMetaTags class.page.php 187 _PAGE->ShowPage pages.php 5 _PAGE->HandlePage I think I fixed this one below, look at the code and you can double check. Use of undefined constant ENT_IGNORE - assumed 'ENT_IGNORE' in class.opengraph.php at 67 File Line Function class.opengraph.php 67 _LOG->HandlePHPErrors class.page.php 249 _OPENGRAPH::getMetaTags class.page.php 187 _PAGE->ShowPage pages.php 5 _PAGE->HandlePage <?php class ISC_OPENGRAPH { /** * Gets a list of valid object types * * @param bool $includeLabels Set to true to return an associative array that includes the labels for each type * @return array The array of object types */ public static function getObjectTypes($includeLabels = false) { $objectTypes = array( 'product' => GetLang('TypeProduct'), 'album' => GetLang('TypeAlbum'), 'book' => GetLang('TypeBook'), 'drink' => GetLang('TypeDrink'), 'food' => GetLang('TypeFood'), 'game' => GetLang('TypeGame'), 'movie' => GetLang('TypeMovie'), 'song' => GetLang('TypeSong'), 'tv_show' => GetLang('TypeTVShow'), ); if (!$includeLabels) { return array_keys($objectTypes); } return $objectTypes; } /** * Generates meta HTML tags using the Open Graph schema * * @param string $type The object type * @param string $title The object's title * @param string $description Description of the object * @param string $image URL to an image of the object * @param string $url The URL to the object itself * @return string The HTML meta tags */ public static function getMetaTags($type = 'product', $title = '', $description = '', $image = '', $url = '') { $imgfile = parse_url(urldecode($image)); if(isset($imgfile['fragment'])){ $localfile = $_SERVER['DOCUMENT_ROOT'].$imgfile['path'].'#'.$imgfile['fragment']; }else{ $localfile = $_SERVER['DOCUMENT_ROOT'].$imgfile['path']; } list($width, $height) = getimagesize("$localfile"); $tags = array( 'og:type' => $type, 'og:title' => $title, 'og:description' => $description, 'og:image' => $image, 'og:image:width' => $width, 'og:image:height' => $height, 'og:image:alt' => $title, 'og:url' => $url, 'og:site_name' => GetConfig('StoreName') ); if (GetConfig('FacebookLikeButtonAdminIds')) { $tags['fb:admins'] = GetConfig('FacebookLikeButtonAdminIds'); } $metaTagsHTML = ''; foreach ($tags as $propertyName => $tagContent) { $metaTagsHTML .= '<meta property="' . $propertyName . '" content="' . htmlspecialchars($tagContent,'ENT_IGNORE','UTF-8') . '" />' . "\n"; } return $metaTagsHTML; } }
  24. I am a university student. What are the sample programs we can do with php? Can those who have php codes share about this subject? Thanks in advance
  25. Good morning. I need to subtract stock levels from oldest stock first then to the next date. It is allowed to move into negative values. example 01-10 stock in 10 stock out 5 - stock count 5 02-10 stock in 10 stock out 7 stock count ... here we need to subtract the 7 from previous days 5 til it reches 0 then stock in subtraction 01-10 stock =0 02-10 stock = 8 --- as 7 -5 gives me -2 in incoming stock is 10 leaving me with stock count of 8. 03-10 stock in 8 stock out 21 02-10 stck level must be 0 03-10 stock lever now is 8-14 = -6 and so on below is my code. $lq_in = new ListQuery('stock_audit5f5795042f369'); $lq_in->addSimpleFilter('name', '%PEPPER yellow%', 'LIKE' ); //$lq_in->addSimpleFilter('product_id', $product_id, '='); $lq_in->setOrderBy('date_entered'); $res_in = $lq_in->fetchAll(); $StockArray = []; foreach($res_in as $out_rec) { /*$upd_out = array(); $upd_out['stock_out_done'] = 0; $out_rec_u = ListQuery::quick_fetch('stock_audit5f5795042f369', $out_rec->getField('id')); $aud_upd_out = RowUpdate::for_result($out_rec_u); $aud_upd_out->set($upd_out); $aud_upd_out->save(); continue; */ $stock_out = $out_rec->getField('stock_out'); $stock_out_done = $out_rec->getField('stock_out_done'); $date_entered = $out_rec->getField('date_entered'); $product_id = $out_rec->getField('product_id'); //echo '<pre>'; // print_r($out_rec->row); $StockItems[] = $out_rec->row; //$stock_done = 0; /* foreach($res_in as $in_rec) { $upd = array(); if($stock_out_new > $in_rec->getField('stock_level')) { $upd['stock_level'] = 0; $stock_out_new = $stock_out_new-$in_rec->getField('stock_level'); $stock_done = $in_rec->getField('stock_level'); } elseif ($stock_out_new == $in_rec->getField('stock_level')) { $upd['stock_level'] = 0; $stock_out_new = 0; $stock_done = $stock_out; } elseif($stock_out_new < $in_rec->getField('stock_level')) { $upd['stock_level'] = $in_rec->getField('stock_level')-$stock_out_new; $stock_out_new = 0; $stock_done = $stock_out; } else { continue; } $in_rec_u = ListQuery::quick_fetch('stock_audit5f5795042f369', $in_rec->getField('id')); $aud_upd = RowUpdate::for_result($in_rec_u); $aud_upd->set($upd); $aud_upd->save(); if($stock_out_new == $stock_done) break; } $upd_out = array(); $upd_out['stock_out_done'] = $stock_done; $out_rec_u = ListQuery::quick_fetch('stock_audit5f5795042f369', $out_rec->getField('id')); $aud_upd_out = RowUpdate::for_result($out_rec_u); $aud_upd_out->set($upd_out); $aud_upd_out->save(); */ } function GetFirstItemWithStockKey($StockItemsarrayk = null){ if($StockItemsarrayk != null){ foreach($StockItemsarrayk as $key => $value){ if(((int) $StockItemsarrayk[$key]['stock_level']) > 0){ return $key; } } } } function SetFirstItemWithStock($StockItemsarray = null){ if($StockItemsarray != null){ foreach($StockItemsarray as $key => $value){ if(((int) $StockItemsarray[$key]['stock_level']) > 0){ return $StockItemsarray[$key]; } } } } $remainder = 0; $pkey = ""; $StockLevelKey = 0; $StockIn = []; $StockOut = []; $InStock = []; $NewStockItems = $StockItems; $ArrayKeys = []; foreach($StockItems as $key => $value){ $StockIn[$key] = (int) $StockItems[$key]['stock_in']; $StockOut[$key] = (int) $StockItems[$key]['stock_out']; $InStock[$key] = (int) $StockItems[$key]['stock_level']; $ArrayKeys[] = (int)$key; } //var_dump($InStock); foreach($NewStockItems as $key => $value){ if($key < 1){ if($StockIn[$key] > 0 && $StockOut[$key] == 0 && $InStock[$key] == 0){ $StockItems[$key]['stock_level'] = ($InStock[$key] + $StockIn[$key]); } if($StockIn[$key] == 0 && $StockOut[$key] > 0 && $InStock[$key] == 0){ $StockItems[$key]['stock_level'] = ($InStock[$key] - $StockOut[$key]); } if($StockIn[$key] > 0 && $StockOut[$key] > 0 && $InStock[$key] == 0){ $StockItems[$key]['stock_level'] = ($InStock[$key] - $StockOut[$key] + $StockIn[$key]); $StockItems[$key]['stock_out'] = 0; } } if($key > 0){ $previousWithStockItem = SetFirstItemWithStock($StockItems); $previousItemWithStockKey = GetFirstItemWithStockKey($StockItems); // echo "<pre>"; // print_r($previousWithStockItem); // var_dump($StockIn[$key]); echo "&nbsp;&nbsp;&nbsp;&nbsp;--IN"; // var_dump($InStock[$key]); echo "&nbsp;&nbsp;&nbsp;&nbsp;--- current"; // var_dump($StockOut[$key]); echo "&nbsp;&nbsp;&nbsp;&nbsp;--- OUT"; while($StockOut[$key] > 0){ if($StockOut[$key] > 0 && $previousWithStockItem['stock_level'] > 0){ $Counter = 0; $maxIteration = 0; for($Counter = $previousWithStockItem['stock_level']; $Counter >= 0; $Counter--){ $StockItems[$previousItemWithStockKey]['stock_level'] = $Counter; if($Counter == 0){ $StockOut[$key] = $StockOut[$key] - $maxIteration; } $maxIteration++; } } if((((int) $StockItems[$key]['stock_level'] < 0) || ((int) $StockItems[$key]['stock_level'] === 0))&& ($StockIn[$key] > 0)){ $valueTotal = $StockItems[$key]['stock_level'] + $StockIn[$key]; $StockItems[$key]['stock_level'] = $valueTotal; } echo "<hr/>"; echo (int) $StockOut[$key]; echo "<br/>"; echo (int) $StockItems[$key]['stock_level']; echo "<br/>"; echo "<hr/>"; if(((int) $StockOut[$key] > 0) && ((int) $StockItems[$key]['stock_level'] > 0) && ((int) $StockItems[$key]['stock_level'] > $StockOut[$key])){ $newStockLevel = $StockItems[$key]['stock_level'] - $StockOut[$key]; echo $newStockLevel; $StockItems[$key]['stock_level'] = $newStockLevel; $StockItems[$key]['stock_out'] = 0; $StockOut[$key] = 0; } if((((int) $StockItems[$key]['stock_level'] < 0) || ((int) $StockItems[$key]['stock_level'] === 0))&& ($StockIn[$key] > 0)){ $valueTotal = $StockItems[$key]['stock_level'] + $StockIn[$key]; echo $valueTotal; $StockItems[$key]['stock_level'] = $valueTotal; } } } } echo "<table><tr><td><pre>"; print_r($NewStockItems); echo "</pre></td><td><pre>"; print_r($StockItems); echo "</pre></td></table>"; /* if($StockIn[$key] > 0 && $StockOut[$key] >0 && $InStock[$key] == 0){ $StockItems[$key]['stock_level'] = ($InStock[$key] + ($StockIn[$key] + $StockOut[$key])); $StockOut[$key] = 0; $StockItems[$key]['stock_out'] = 0; } if($StockIn[$key] != 0 && $StockOut[$key] != 0 && $InStock[$key] != 0){ $StockItems[$key]['stock_level'] = ($InStock[$key] - ($StockOut[$key] + $StockIn[$key])); $StockOut[$key] = 0; $StockItems[$key]['stock_out'] = 0; }*/ /** @Rule 1 # Stockin has value and stock_out = 0 and stock_level = 0 and stock_out_done = null, actualstock to show actual stock level; # */ /*if($StockCalculation[$Skey]['stock_out'] >= $StockItems[$key]['stock_level']){ $StockItems[$key]['stock_out'] = ($StockItems[$key] - 1); $StockItems[$key]['stock_level'] = ($StockItems[$key]['stock_level'] - 1); // If StockOut == 0 next StockOutItem if($StockCalculation[$Skey]['stock_out'] == 0){ $remainder = 0; continue; }elseif($StockItems[$key]['stock_level'] == 0){ //CurrentInStock == 0 then continue to next CurrentItem $remainder = $StockItems[$key]['stock_out']; continue(2); } } $CurrentStockIn = $StockItems[$key]['stock_in']; $CurrentStockOut = $StockItems[$key]['stock_out']; $CurrentInStock = $StockItems[$key]['stock_level']; if($key == 0){ if($CurrentStockIn > 0 && $CurrentStockOut === 0 && $CurrentInStock == 0){ $CurrentInStock = $CurrentStockIn; //Query update stock level set = stock_in //"UPDATE STOCK SET stock_level = {$CurrentStockIn} where id = {$StockItems[$key]['id']}"; $StockItems[$key]['stock_level'] = $CurrentStockIn; } if($CurrentStockIn != 0 && $CurrentStockOut != 0 && $CurrentInStock == 0){ //Query Update Stocklevel if stock_out > 0 and stock_level = 0 //"UPDATE STOCK SET stock_level = "+($CurrentStockIn - $CurrentStockOut) + "where id = {$StockItems[$key]['id']}"; if($CurrentStockIn > $CurrentStockOut && $CurrentStockOut == 0){ $StockItems[$key]['stock_out'] = 0; $StockItems[$key]['stock_level'] = $CurrentInStock = $CurrentStockIn - $CurrentStockOut; } if($CurrentStockOut > $CurrentStockIn){ $StockItems[$key]['stock_level'] = $CurrentInStock = $CurrentInStock - $CurrentStockOut; } } if($CurrentInStock != 0 && $CurrentStockOut > 0){ //If Current in stock below 0 and stock out > 0 then negative more //"UPDATE STOCK SET stock_level = "+($CurrentInStock - $CurrentStockOut) + "where id = {$StockItems[$key]['id']}"; $StockItems[$key]['stock_level'] = $CurrentInStock = ($CurrentInStock - $CurrentStockOut); $StockItems[$key]['stock_out'] = 0; } if($CurrentInStock != 0 && $CurrentStockIn > 0){ //If Current in stock below 0 and stock out > 0 then negative more //"UPDATE STOCK SET stock_level = "+($CurrentInStock - $CurrentStockOut) + "where id = {$StockItems[$key]['id']}"; $StockItems[$key]['stock_level'] = $CurrentInStock = ($CurrentInStock + $CurrentStockIn); } // Run row update for first item }else{ foreach($StockCalculation as $Skey => $Sval){ $NextStockOut = $Sval['stock_out']; $NextStockIn = $Sval['stock_in']; $NextStockLevel = $Sval['stock_level']; if($Skey > 0 && $key > 0){ // print_r($NextStockOut); for($i = $NextStockOut; $i >= -1; $i--){ if($NextStockOut > 0){ if($NextStockOut > 0){ /* if($StockItems[$StockLevelKey]['stock_level'] != 0){ $StockItems[($StockLevelKey)]['stock_level'] = ($StockItems[($StockLevelKey)]['stock_level'] - 1); //$StockItems[($Skey-1)]['stock_out'] = ($StockItems[($Skey-1)]['stock_out'] -1); } if($StockItems[($Skey-1)]['stock_level'] != 0){ $StockItems[($Skey-1)]['stock_level'] = ($StockItems[($Skey-1)]['stock_level'] - 1); } } } $NextStockOut = ($NextStockOut -1); if($NextStockOut != 0){ $StockItems[$Skey]['stock_out'] = 0; break; } } } unset($StockCalculation[$Skey]); } }/* */
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.