Jump to content

Search the Community

Showing results for tags 'php'.



More search options

  • 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 (Dreamweaver, Zend, 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

Found 2,654 results

  1. Mr-Chidi

    redirect selection

    Hi. Pls I have a form that contains countries. Let say i want to do something else if a country in among the countries in my list and something else if not included. how can i archive this simply without doing multiple ifs. eg direct listed countries to page A else direct to page B Thanks
  2. talmik

    Code for Year Count

    Hello all This bit of code is supposed to count the number of years between a creation date and the current date then place that number of years in the database. I seem to be missing something or have done something wrong. Can anyone see where it all went wrong?
  3. lilmer

    Dynamic URL

    I am new to Laravel, I have registration form which set an extension on the URL on the database table for each user. Example. I am using Laravel 5.6. Anyone can suggest what is the best way to get check if the URL exist on the database and it will proceed. As I now I try to set the Model and make a condition on the config/routes.php to check if the extension from database, but I know it is not the best solution.
  4. I have a table full of mac addresses in this format 80828704B0EE I need a method to run a query that will output this format 80:82:87:04:B0:EE I either need to insert the result of the some query that is formatting the existing mac addresses to another field or use a query to format the mac addresses on the fly. I need to create a csv file from this query. I have all that code it is just making the query to format it the way I need it. Here is a query I found that does the trick except that I get two columns, the original and the formatted one. How can I remove the mac column that this outputs? SELECT mac, concat(left(mac,2), ":",substring(mac,3,2), ":" , substring(mac,5,2), ":",substring(mac,7,2), ":",substring(mac,9,2), ":", right(mac,2)) as mac_formatted FROM phones Thanks
  5. I have a page that I use to scan (with a barcode scanner) a series of barcodes for mac addresses. The page is this code <form action="insert.php" method="post" id="phoneEntry"> <fieldset> <legend><h3>Phone MAC Entry:</h3></legend> <label for="phoneEntry_dealerName">Select Dealer</label> <select name="id" id="phoneEntry_dealerName">'; while ($dealer = $dealers->fetch_assoc()) echo ' <option value="', $dealer['id'], '">', $dealer['dealername'], '</option>'; echo ' </select> <label for="macEntry_hostedLocation">Enter the Location IP:</label> <input type="text" name="location"><br> <label for="macEntry_address">Input the MAC address:</label> <textarea name="mac" id="macEntry_address"> </textarea> <button>Save</button> </fieldset> </form>'; I scan into the text area and the MAC is much like this : 80828704B0EE I scanned in 14 different barcodes and in the database they were all shortened on the back bu 4 digits. Here is the insert.php code: Scanning the same barcode it is formatted and of the correct length in notepad+ $dealerid= "$_POST[id]"; $location= "$_POST[location]"; include('/var/www/html/hosted/index.html'); require('/var/www/html/hosted/utils/connect.php'); $stmt1 = $link->prepare(' INSERT INTO phones ( dealerid, location, mac ) VALUES ( ?, ?, ? ) '); $macList = preg_split('/[\s,]+/', $_POST['mac']); $stmt1->bind_param('iss', $dealerid, $location, $mac); foreach ($macList as $mac) $stmt1->execute(); So I am thinking that the issue is somewhere in the preg_split but I don't see it. I also need to save the same MAC address into the same table (different field) in this format 80:82:87:04:B0:EE I need to eventually run a report on both formats of each MAC entry. Thanks for any insight anyone might be able to give.
  6. Mr-Chidi

    PHP Gallery

    Hi all, I don't know if there's a gallery for this already or the right place to ask the question. User uploads multiple images. Images are store in a different folder and a unique name stored on the database. All images have a unique group for referencing purpose . When a user clicks on a link in his table he can view all images pertaining to a group. How can i go about that? What i want to achieve is for example SELECT ALL FROM IMAGE_TABLE WHERE USERNAME = USERNAME AND GROUP_ID = GROUP_ID Thanks
  7. What configuration, code or service is needed to hide root directories from a hosting. When I access it, do not show me what PHP classes I'm in. If so, hide folders but keep making use of the chain of classes that have a relationship.
  8. EmmanuelCorrea

    Resource id#51

    Good day community. With a doubt that I could not find a solution. I'm trying to log in, I have my user and my password registered (so the user does exist), but at the time of entering, he only sends me a Resource id # 51, I clarify that this is under a server, I have my bd too hosted on host, all right. Also, I do this function in localhost and I login correctly. I came across this "error" or result already when it was on the host of the server to which I do not know what is due. This is my code. $sql = sprintf("SELECT * FROM usuario WHERE usuario = '%s' AND contrasena = '%s' ", mysql_real_escape_string($usuario), mysql_real_escape_string($contrasena)); $query=mysql_query($sql); //echo mysql_errno().":".mysql_error(); echo $query; $verificar=mysql_num_rows($query); echo $verificar; if($verificar==1){ //El logueo es exitoso y se crea la sesion if($valores = mysql_fetch_assoc($query)){ if($valores['puesto'] == 'A'){ $_SESSION['usuario'] = $usuario; //header("HTTP/1.1 302 Moved Temporarily"); //header("Location: ../indexMenu.php"); }else if($valores['puesto'] == 'B'){ $_SESSION['alumno'] = $usuario; header("HTTP/1.1 302 Moved Temporarily"); header("Location: ../../../alumnos/php/indexMenu.php"); } }else{ echo 'No se ha podido iniciar sesion, por favor vuelva a intentarlo.'; }
  9. EmmanuelCorrea

    Resource id #51

    Buen día comunidad. Con una duda que no he podido encontrar una solución. Estoy intentando hacer un logueo, tengo mi usuario y mi contraseña dada de alta (osea que el usuario si existe), pero al momento de ingresar solamente me manda un Resource id #51, aclaro que esto es bajo un servidor, tengo mi bd tambien alojada en host, todo correcto. También que hago esta función en localhost y me hace el login correctamente. Me tope con este "error" o resultado ya cuando se encontraba en el host del servidor a lo cual no se a que se deba. Este es mi código. $sql = sprintf("SELECT * FROM usuario WHERE usuario = '%s' AND contrasena = '%s' ", mysql_real_escape_string($usuario), mysql_real_escape_string($contrasena)); $query=mysql_query($sql); //echo mysql_errno().":".mysql_error(); echo $query; $verificar=mysql_num_rows($query); echo $verificar; if($verificar==1){ //El logueo es exitoso y se crea la sesion if($valores = mysql_fetch_assoc($query)){ if($valores['puesto'] == 'A'){ $_SESSION['usuario'] = $usuario; //header("HTTP/1.1 302 Moved Temporarily"); //header("Location: ../indexMenu.php"); }else if($valores['puesto'] == 'B'){ $_SESSION['alumno'] = $usuario; header("HTTP/1.1 302 Moved Temporarily"); header("Location: ../../../alumnos/php/indexMenu.php"); } }else{ echo 'No se ha podido iniciar sesion, por favor vuelva a intentarlo.'; } Espero puedan ayudarme, ya que es mi proyecto de Titulación!
  10. Hi everyone, The following code is aimed to show "aaa aaa" as default value for input box in a form: <?php //xxx.php $db = mysqli_connect('localhost', '', '', ''); ?> <!DOCTYPE html> <html> <body> <form method="POST" action="xxx.php"> <input type="text" name="id" class="id_input" value=<?php echo 'aaa aaa';?>> </form> </body> </html>
  11. This is my array. It has stored images data. [other-image] => Array ( [img] => Array ( [0] => 1526973657.jpg [1] => 1526973661.jpg [2] => 1526973665.jpg ) [path] => Array ( [0] => ../post-upload/1/ [1] => ../post-upload/1/ [2] => ../post-upload/1/ ) [type] => Array ( [0] => 1 [1] => 1 [2] => 1 ) [thumb] => Array ( [0] => thumb_1526973661.jpg [1] => thumb_1526973665.jpg [2] => thumb_1526973668.jpg ) ) Now I want to delete an image and it's all related data from sub arrays. (path, type, thumb data) This is how I tried it in php: $delkey = $_POST['key']; if(in_array($delkey, $_SESSION['other-image']['img'])){ $imgkey = array_search($delkey, $_SESSION['other-image']['img']); if($imgkey) unset($_SESSION['other-image']['img'][$imgkey]); //file path $fp = UPLOAD_DIR.$nextId."/".$delkey; unlink($fp); } As I did, its only deleting element form 'img' array, but I want to delete related data from other arrays too. Can anybody tell me how to do this? Thank you.
  12. sigmahokies

    Valdiation

    Hi everyone, I am trying to have "require" label on form. If someone did not select the option on list, then "require" label will appear in form after submit. Seem my code isn't work. what did I do wrong? <?php$buzz = $buzz2 = ""; if ($_SERVER['REQUEST_METHOD'] == "POST") { if (empty($_POST['select'])) { $buzz = "<h2><color color='red'> >- </color></h2>"; $buzz2 = "<h2><color='red'> -< </color></h2>"; }} ?><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>XXXXXX</title> <link href="default.css" rel="stylesheet" type="text/css"></head><body><fieldset><h1>XXXXXXX</h1> <table> <form action="login.php" method="post"> <select name="select"> <?php echo $buzz ?><option value="" >Please select the level</option><?php echo $buzz2 ?> <option value="Administrator">Administrator</option> <option value="License">License</option> <option value="Scorer">Scorer</option> </select> <caption>Please login to enter the site below:</caption> <tr><td>Username:</td><td class="td"><input type="text" name="user"></td></tr> <tr><td>Password:</td><td class="td"><input type="password" name="password"></td></tr> <tr><td colspan="2"><input type="submit" name="submitted" value="Login"></td></tr> </form> </table></fieldset></body></html> Thanks for helping Gary Taylor
  13. KillGorack

    Filter array by KEY

    I would like to create an array from the one below that can sort of filter using date ranges; For example, make an array that contains data using date <= 2018-05-09 without a loop. A loop is an option just wondering if you can filter by keys somehow. Array ( [2018-04-23 21:31:40] => -1.174 [2018-04-24 15:43:59] => -1.015 [2018-04-26 00:14:10] => -0.37 [2018-04-30 18:41:51] => -1.042 [2018-05-01 20:08:40] => -0.72 [2018-05-02 22:11:52] => -0.107 [2018-05-07 18:40:12] => -0.298 [2018-05-09 16:35:38] => -0.36 [2018-05-10 01:14:27] => 0.408 [2018-05-14 20:49:54] => 1.549 )
  14. Hi all, I need your help. I am working on a function to add the day value that start from 0 to 6. I want to count it up the value for each day so I can connect to each url for each day, but on my code it will only show the value as 0 for each day. Here is the code: <?php $channels = json_decode(file_get_contents('channels.json'), true); $day = 0; function get_shows($channel_id, DateTime $dt, $duration=1440, $skip_finished = true) { $url = 'http://example.comapi/GS?cid=' . $channel_id . '&offset=+00.00&day=' .$day++; echo $url; $day++; } if(!isset($_GET['id']) || !isset($channels[$_GET['id']])) { } else { // today + 6 following days for($day=0; $day<=6; $day++) { // display date echo '<h3>', $dt->format('Y-m-d (l)'), '</h3>'; // display shows foreach(get_shows($channel_id, $dt, $duration) as $show) { } $dt->add(new DateInterval('P1D')); $dt->setTime(0, 0, 0); } } ?> Output: Here is what I want to achieve: Can you please show me an example how I can add the value up for each day that start from 0 to 6 when I am calling on get_show function??
  15. ajoo

    a suspicious pop-up

    Hi all, I used my localhost after a long time. The embedded flash movie tries to load data from the server via a file called testfest.php when the browser blocks a pop which has this message. pop up blocked on the page : http://localohost/myproject/undefinedtestfest.php Does this indicate something malicious? Should I unblock the pop-up and see what happens or maybe that would be unsafe? If this is suspicious then what should i be checking for ? Thanks all !
  16. Hi guys, I am trying to display data to a user who submitted it. So, user A submits data to the db and also user B. I want it so that user A cannot see user B's data but only the data they have submitted. Hope that makes sense. Here is the code along with the table of data to be displayed. <div class="panel-body"> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover" id="bookings_table"> <thead> <tr> <th class="text-center">Issue ID</th> <th class="text-center">Driver Name</th> <th class="text-center">Date Submitted</th> <th class="text-center">Fleet Number</th> <th class="text-center">Issue</th> <th class="text-center">Description</th> <th class="text-center">Priority</th> <th class="text-center">Status</th> </tr> </thead> <tbody> <?php $check = isset($_SESSION['username']); if($stmt = $link -> prepare("SELECT issue_id, driver_name, submit_date, fleet_number, issue_name, issue_description, issue_priority, issue_status FROM maintenance_requests WHERE username = ?")) { $stmt -> execute(); $stmt -> bind_result($issue_id, $driver_name, $submit_date, $fleet_number, $issue_name, $issue_description, $issue_priority, $issue_status); while($stmt->fetch()) { ?> <tr class="odd gradeX"> <td class="text-center"><?php echo $issue_id; ?></td> <td class="text-center"><?php echo $driver_name; ?></td> <td class="text-center"><?php echo $submit_date; ?></td> <td class="text-center"><?php echo $fleet_number; ?></td> <td class="text-center"><?php echo $issue_name; ?></td> <td class="text-center"><?php echo $issue_description; ?></td> <td class="text-center"><?php echo $issue_priority; ?></td> <?php if($issue_status == "Pending") { ?> <td class="text-center warning"><?php echo $issue_status;?></td> <?php }else if($issue_status == "Open"){ ?> <td class="text-center danger"><?php echo $issue_status; ?></td> <?php }else if($issue_status == "Repaired"){ ?> <td class="text-center success"><?php echo $issue_status ;} ?></td> </tr> <?php } $stmt -> close(); } mysqli_close($link); ?> If I remove the WHERE clause, it displays data from both users. Placing the WHERE clause shows no data. Can someone have a look and see where I am going wrong and maybe point me in the right direction? Many thanks in advance.
  17. It will only update if I put items in the cart with this similar order: red, blue, blue = red:1 blue:2 But if I put: red, red = red:1 red:1 Instead of putting the quantity to 2. This only seems to be happening while adding the first 2 items of the same kind otherwise the code works fine. $item = array( "image" => $image, "id" => $product_id, "price" => $price, "name" => $name, "desc" => $desc, "qty" => $qty, "slug" => $slug ); function checkCartForItem($addItem, $cartItems) { if (is_array($cartItems)){ foreach($cartItems as $key => $item) { if($item['name'] === $addItem) return $key; } } return false; } $itemExists = checkCartForItem($name, $_SESSION['cart']); if ($itemExists){ // item exists - increment quantity value by 1 $_SESSION['cart'][$itemExists]['qty']++; } else { // item does not exist - create new item and add to cart $_SESSION['cart'][] = $item; } Thanks
  18. Hi all, Trying to update two rows in a MySQL table using MySQLi and PHP with values from a bootstrap dropdown. No errors or anything (have error reporting turned on), just nothing is updated in the database. Here is the update code (if anyone has a prepared version of it would love to have it). if(isset($_POST['Update'])){//if the submit button is clicked if(isset($_GET['issue_id']) && isset($_POST['issue_priority']) && isset($_POST['issue_status'])) { $sql="UPDATE maintenance_requests SET issue_status='$issue_status', issue_priority='$issue_priority' WHERE issue_id='".$_GET['issue_id']."'"; $link->query($sql) or die("Cannot update");//update or error } } ?> And here is the form: <form role="form" method="POST" action="" /> <table class="table table-striped table-bordered table-hover" id="bookings_table"> <thead> <tr> <th class="text-center">Issue ID</th> <th class="text-center">Driver Name</th> <th class="text-center">Date Submitted</th> <th class="text-center">Fleet Number</th> <th class="text-center">Issue</th> <th class="text-center">Description</th> <th class="text-center">Priority</th> <th class="text-center">Status</th> </tr> </thead> <tbody> <tr class="odd gradeX"> <td class="text-center"><?php echo $issue_id; ?></td> <td class="text-center"><?php echo $driver_name; ?></td> <td class="text-center"><?php echo $issue_date; ?></td> <td class="text-center"><?php echo $fleet_number; ?></td> <td class="text-center"><?php echo $issue_name; ?></td> <td class="text-center"><?php echo $issue_description; ?></td> <td class="text-center"> <select name="issue_priority"> <option value="" hidden="hidden"><?php echo $issue_priority; ?></option> <option value="High">High</option> <option value="Medium">Medium</option> <option value="Low">Low</option> </select> </td> <td class="text-center"> <select name="issue_status"> <option value="" hidden="hidden"><?php echo $issue_status; ?></option> <option Value="Open">Open</option> <option Value="Pending">Pending</option> <option value="Repaired">Repaired</option> </select> </td> </tr> </tbody> <?php } $stmt -> close(); } mysqli_close($link); ?> </table> <input type="submit" class="btn btn-default" name="Update" value="Update Issue"> </div> </form> Any help would be really appreciated. Have searched the forums and searched Google but nothing found. Thanks heaps.
  19. sigmahokies

    flexible in loop in array

    Hello everyone, I'm getting there, but not perfect. Still learning to do write the script in PHP. Anyway, I am trying to get set up the flexible array and values in html and SQL. I am trying to make different name, cannot same name in loop. For example, in PHP, to get data value from $_POST from name from input in form area in html, so I can't figure how to get like array. In loop, look like: using for or foreach loop, I need to have <input type="text" name="label$j"> in different number, like to have loop name = label1, label2, label3... But I found php print the loop same - label1, label1, label1...I don't want that, because it will conflict to insert in the data in the database. here my code: <!doctype html> <html> <head> <title>Add name and number</title> <link href="defaultdatabase.css" rel="stylesheet" type="text/css"> </head> <h2>Add any DSDJ information to database</h2> <?php require ("require2.php"); $sql = "show tables from XXXX"; $list = mysqli_query($GaryDB, $sql); while ($row = mysqli_fetch_array($list)) { $table[] = $row[0]; } $option = ''; foreach ($table as $rows) { $option .= "<option value='{$rows}'>{$rows}</option>"; } ?> <form action="addname.php" method="post"> <table> <tr><th>Select the table</td><td> <select name="subject"> <?php echo $option; ?> </select></td><td><input type="submit" name="selected" value="select"></td></tr> </table> </form> <form> <table> <?php if (isset($_POST['selected'])) { $selected = $_POST['subject']; $column = "select column_name from information_schema.columns where table_name = '" . $selected . "'"; $list5 = mysqli_query($GaryDB, $column); while ($array = mysqli_fetch_array($list5)) { $input = ''; $j = 0; foreach ($array as $row5) { $input = "<tr><td>{$row5}:</td><td colspan='2'><input type='text' name='label$j'></td></tr>"; $j++; } echo $input; } if (isset($_POST['insert'])) { foreach ($array as $row6) { $ins = "{$row6},"; } foreach ($_POST['label'] as $row7) { $ins5 = "'{$row7}',"; } $insert = "insert into " . $selected . " (" . $ins . ") values (" . $ins5 . ")"; $added = mysqli_query($GaryDB,$insert); if($added) { echo "<tr><td>Data are insert into Database</td></tr>"; } else { echo "<tr><td>Data did not get in the Database</td></tr>"; } } }echo "<tr><td><input type='submit' name='insert' value='Add data in database'></td></tr>"; ?> </table> </form> </html> So, in result: <tr><td>Articles_ID:</td><td colspan='2'><input type='text' name='label1'></td></tr><tr><td>Subject_ID:</td><td colspan='2'><input type='text' name='label1'></td></tr><tr><td>ID:</td><td colspan='2'><input type='text' name='label1'></td></tr><tr><td>LastName:</td><td colspan='2'><input type='text' name='label1'></td></tr><tr><td><input type='submit' name='insert' value='Add data in database'></td></tr> Look at result name in label1, label1, label1, ...that is no no no. I want to have label1, label2, label3...can you help? Thank you so much! Gary Taylor
  20. I think I have this covered but want some feedback. When I receive a file I secure it by checking these values in $_FILES name: must be a valid filesystem file name (if I'm going to use it). I never did find a library out there that would validate filesystem parameters (names, paths). I just use a regular expression to look for things I know are illegal. name: length must not exceed filesystem limit plus path size: check for zero and max size type: validate against a list of allowed types (Wondering if someone could subvert the type here and cause trouble. Is there way to look inside a file and verify 'type'?) tmp_name: nothing to check error: should be zero Got it all? Thank you.
  21. I'm trying to build some data in an excel report through PHP but I'm still having trouble getting the array structure and foreach loops the way I need them. Basically, I'm pulling a select on Mysql, matching it to a select in DB2 ( I need values from each) and then I need to loop the results and perform some calculations and then relate it back to the highest level array for the report. My first query pulls records like this: sku_id | customer_id | locations | group_id | frame | cover | color | start_date 1 5400 2 1 1051 1150 99 2018-02-09 1 5401 3 1 1051 1150 99 2018-02-09 Based on those results I pull a query on DB2 that gets every record since that start_date where those customers ordered that same sku_id so I'm getting multiple records for the sku_id/customercombo. That query returns something like this: customer | frame | cover | color | date | TotalQTY 5400 1051 1150 99 2018-02-09 5 5400 1051 1150 99 2018-02-19 2 5400 1051 1150 99 2018-03-09 5 5401 1051 1150 99 2018-02-11 1 5401 1051 1150 99 2018-02-15 7 5401 1051 1150 99 2018-02-25 5 The queries work and my arrays are printing with the proper data, but I need some guidance on structuring these right. I'm matching the SKU up by attributes like cover, color and frame. I need to look first at each sku_id from the first query, execute the 2nd and then look at each customer to get their total quantity of that sku. So based on the example above I would need to get a total quantity of 12 for customer # 5400 and 13 for customer #5401, both for sku 1. My end goal is to get the total quantity of sku on a per dealer basis, so with the example above, my report would look like this: SKU | GROUP | TotalQTY ----------------------------------------- 1 1 25 My array structure looks right as far as my first foreach (foreach sku, perform the query, which returns an array for each record per customer). I'm not sure how to do the foreach on the customer so that I can work on a per customer basis and get the total quantity of that sku per customer. I feel like I would need to say for each dealerRslt as Customer, total all totalQTY Here's the portion of the script in question: $skuQuery = " SELECT sku_id, customer_id, locations, s.sku_group_id as groupID, s.frame as frame, s.cover1 as cover, s.color1 as color, start_date - interval 7 day as start_date from products p inner join skus s on p.sku_id = s.id where curdate() between p.start_date and p.expire_date group by sku_id, customer_id"; $skuRslt = mysqli_query($conn,$skuQuery); while($skuRow = mysqli_fetch_assoc($skuRslt)){ $skuResult[] = $skuRow; $dealerQuery = " SELECT customer, frame, cover, color, cast(Left(date, 4)||'-'||substring(date,5,2)||'-'||substring(date, 7,2) as date) as start_date, sum(orqtyc) as TotalQTY from table1 where customer = {$skuRow['dealer_id']} AND frame = {$skuRow['frame']} AND color = {$skuRow['color']} AND cover = {$skuRow['cover']} AND date >= " . str_replace('-', '', $skuRow['start_date']) . " group by customer, frame,cover,color,date "; $dealerRslt = odbc_exec($DB2Conn, $dealerQuery); foreach($skuResult as $skuRow){ while($dealerRow = odbc_fetch_array($dealerRslt)){ $dealerResult[] = $dealerRow; print_r($dealerResult); } } }
  22. thenorman138

    array result at wrong level

    I'm using an array based off of two other arrays in order to get a count of product IDs per customer. The following array is what's printing now: Array ( [5] => 4 ) Array ( [5] => 1 ) Array ( [5] => 1 ) Array ( [5] => 1 ) Array ( [5] => 2 ) So the [5] is the product number, the number after => is the quantity per customer (each array line represents a customer). I want to continue having my source array data at the customer level, but what I really want right now is one main array for each product number with totals in the array, so for the above, my desired result is this: array ( [5] => 9 ) here's what gives me the output I currently have: $skuTots = array_fill_keys(array_unique(array_column($skuResult, 'sku_id')), 0); foreach ($skuResult as $rec) { $skuTots[$rec['sku_id']] += $dealerResult[$rec['dealer_id']]; } print_r($skuTots); How can I get this desired change?
  23. I'm trying to restructure my arrays so that I can get the desired output in one final array that will be used to fill a csv, eventually spreadsheet. My first msyql query and the resulting array give me this structure: array( [0] => Array ( [sku_id] => 1 [dealer_id] => 1976 [locations] => 1 [groupID] => 1 [frame] => 1051 [cover] => 1150 [color] => 99 [start_date] => 2018-03- ) [1] => Array ( [sku_id] => 1 [dealer_id] => 5400 [locations] => 1 [groupID] => 1 [frame] => 1051 [cover] => 1150 [color] => 99 [start_date] => 2017-04- ) [2] => Array ( [sku_id] => 1 [dealer_id] => 11316 [locations] => 1 [groupID] => 1 [frame] => 1051 [cover] => 1150 [color] => 99 [start_date] => 2017-02- ) ) So I get 3 records, each for the same product (sku_id) but a different customer(dealer_id). Then I match this data up in a similar table in DB2 to get quantity for each order of the sku_id. That 2nd query/array shows this: Array ( [0] => Array ( [CSTNOC] => 1976 [TOTALQTY] => 2 ) [1] => Array ( [CSTNOC] => 5400 [TOTALQTY] => 5 ) [2] => Array ( [CSTNOC] => 11316 [TOTALQTY] => 14 ) ) However, this is what I'm trying to achieve. In the below example, sku_id, groupID and location would come directly from the first query. Days is the number of days between start_date (from query 1) and curDate(). Qty is orqtyc from query 2 and Average is a calculation based on locations, days and qty. Each row is based on a different customer, so even though the below example is for one sku, the rows signify a different customer with different locations, qty, etc. SKU_id | groupID | locations (n) | Days (x) | Qty(q) | Average (x/(q/n)) -------------------------------------------------------------------------------- 123 1 3 120 15 24 123 1 2 12 6 4 The Report or CSV would then only show one line item for the above: SKU | Group | Average Days | Total units sold 123 | 1 | 28 | 21 Basically, for every sku I'm getting those records and then I need to do those calculations by row, and get a total of those values for each sku. The report will only have one line item per sku. I have everything I need to get there, but how can I structure a final array to get my desired outputs like above? FULL SCRIPT: $skuQuery = " SELECT sku_id, dealer_id, locations, s.sku_group_id as groupID, s.frame as frame, s.cover1 as cover, s.color1 as color, start_date - interval 7 day as start_date from products p inner join skus s on p.sku_id = s.id where curdate() between p.start_date and p.expire_date group by sku_id, dealer_id limit 3"; $skuRslt = mysqli_query($conn,$skuQuery); while($skuRow = mysqli_fetch_assoc($skuRslt)){ $skuResult[] = $skuRow; $dealerQuery = " SELECT cstnoc, sum(orqtyc) as TotalQTY from table where cstnoc = {$skuRow['dealer_id']} AND framec = {$skuRow['frame']} AND colr1c = {$skuRow['color']} AND covr1c = {$skuRow['cover']} AND extd2d >= " . str_replace('-', '', $skuRow['start_date']) . " group by cstnoc, framec "; $dealerRslt = odbc_exec($DB2Conn, $dealerQuery); foreach($skuResult as $skuRow){ while($dealerRow = odbc_fetch_array($dealerRslt)){ $dealerResult[] = $dealerRow; } } print_r($dealerResult); }
  24. I'm trying to alter a db2 query in my php script and it's not executing properly when doing so. In the last line of my WHERE clause for the DB2 select, I'm using this: AND date(substr(extd2d,1,4)||'-'||substr(EXTD2d,5,2)||'-'||substr(EXTD2d,7,2)) >= {$row['start_date']} but getting an error that >= is not a valid comparison operand. However, if I remove {$row['start_date']} and use current_date or current_date - 100 DAY, it works perfectly. To clarify, the value for 'start_date' in mysql is DATE data type and the value 'extd2d' in db2 is a packed field value that holds a date (20180202), so I'm converting it to try and match the YYYY-MM-DD format. Why can't I get this to work as it is? $sql = " SELECT sku_id, dealer_id, locations, s.sku_group_id as groupID, s.frame as frame, s.cover1 as cover, s.color1 as color, start_date - interval 7 day as start_date from placements p inner join skus s on p.sku_id = s.id where curdate() between p.start_date and p.expire_date group by sku_id, dealer_id limit 100"; $result = mysqli_query($conn,$sql); while($row = mysqli_fetch_assoc($result)) { $resultData[] = $row; $sql2 = " SELECT framec, covr1c, colr1c, date(substr(extd2d,1,4)||'-'||substr(EXTD2d,5,2)||'-'||substr(EXTD2d,7,2)) as start_date, sum(orqtyc) as TotalQTY from table1 where cstnoc = {$row['dealer_id']} AND framec = {$row['frame']} AND colr1c = {$row['color']} AND covr1c = {$row['cover']} AND date(substr(extd2d,1,4)||'-'||substr(EXTD2d,5,2)||'-'||substr(EXTD2d,7,2)) >= {$row['start_date']} /*This is the line in question*/ group by framec,covr1c,colr1c,extd2d "; $result2 = odbc_exec($DB2Conn, $sql2); while($row2 = odbc_fetch_array($result2)){ $db2Result[] = $row2; } } print_r($resultData); print_r($db2Result);
×

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.