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


  • 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


Last Updated

  • Start


Filter by number of...


  • Start





Website URL








Donation Link

Found 2,000 results

  1. I currently have an array that I've built that dumps like this: 0 => array:11 [▼ "category_code" => "123" "category_name" => "Testing" "category_description" => "This is a test category" 19738 => array:5 [▼ "identifier" => "720368842943" "description" => Test Description One "count" => 4 "details" => array:2 [▼ 0 => array:3 [▼ "detail_code" => "2751" "detail_code2" => "43" "detail_specifier" => "Detail One" ] 1 => array:3 [▼ "detail_code" => "2681" "detail_code2" => "9" "detail_specifier" => "Detail Two" ] ] "prices" => array:1 [▼ "01" => "1129.00" ] ] 19739 => array:5 [▼ "identifier" => "720368844121" "description" => "Test Description Two" "count" => 4 "details" => array:2 [▼ 0 => array:3 [▼ "detail_code" => "2751" "detail_code2" => "43" "detail_specifier" => "Detail One" ] 1 => array:3 [▼ "detail_code" => "2681" "detail_code2" => "9" "detail_specifier" => "Detail Two" ] ] "prices" => array:1 [▼ "01" => "1490.00" ] ] I'm using laravel excel in order to export that as an excel file, but it's not quite working the way I intend When it exports to excel I only get the top level info: 123 | Testing | This is a test category But I want to get that info as a header and then each subsequent product for that category as a row, so with the example above it would look like: 123 | Testing | This is a test category ==================================================================================================================== 19738 | 720368842943 | Test Description One | 4 | 2751 | 43 | Detail One | 2681 | 9 | Detail Two | 1129.00 19739 | 720368844121 | Test Description Two | 4 | 2751 | 43 | Detail One | 2681 | 9 | Detail Two | 1490.00 Here's the excel code with the array I'm using, which is dumped above: $allCategoryResult= array(); foreach($prices->categories as $category){ $categoryItem = array(); $categoryItem["category_code"] = $category->category_code; $categoryItem["category_name"] = $category->category_name; $categoryItem["category_desc"] = $category->category_desc; foreach($category->skus as $sku){ $skuItem = array(); $skuItem["identifier"] = $sku->sku_info->identifier; $skuItem["description"] = $sku->sku_info->item->description; $skuItem["count"] = $sku->sku_info->item->item_type->count; $skuItem["details"] = array(); foreach ($sku->sku_info->details as $details) { $detailsItem = array(); $detailsItem["detail_code"] = $details->detail_code; $detailsItem["detail_code2"] = $details->detail_code2; $detailsItem["detail_specifier"] = $details->detail_specifier; $skuItem["details"][] = $detailsItem; } $skuItem["prices"] = get_object_vars($sku->prices); $itemCode = $sku->sku_info->item->item_code; $categoryItem[$itemCode] = $skuItem; } $allCategoryResult[] = $categoryItem; } $name = 'Test Export'; $build = Excel::create($name, function ($excel) use ($allCategoryResult) { $excel->setTitle('Test Export'); $excel->sheet('Test Export', function ($sheet) use ($allCategoryResult) { $sheet->fromArray($allCategoryResult);
  2. I'm currently looping on an array with this structure: Categories{ CategoryName CategoryCode CategoryDescription Products{ product_info{ product_code product_type{ CountNumber ProductDescription } } prices{ "wholesale":"250", "retail":"400" } } } I'm looping on the above array at each level, and I've declared an array so that I can put all my needed values into it $priceResult = array(); foreach($prices->categories as $category){ $categoryName = $category->category_name; $categoryCode = $category->category_code; $categoryDescription = $category->category_desc; foreach($category->products as $product){ foreach($product->product_info as $info){ $product_code = $info->product_code; foreach($info->product_type as $type){ $CountNumber = $type->CountNumber; $ProductDescription = $type->ProductDescription; } } foreach ($product->prices as $price => $amount) { $price_amount = $amount; } } } The problem I'm having is I don't know how to properly push into that new ```$priceResult``` array so that I can use PHPExcel to put it into a format with a subheader. The format I would want from the above example would be something like this Test Category 1 | 123 | Category for Testing ================================================== PRD123 | 12 | Product for Testing | 150.00 PRD112 | 17 | Product for Testing | 250.00 Test Category 2 | 321 | New Category for Testing ===================================================== PRD189 | 16 | Product for Testing | 450.00 PRD139 | 34 | Product for Testing | 350.00 So basically I want to call PHPExcel on my $priceResult array in order to get that format where I can list my category info, and for each product within that category, I'd have a product row. Everything would be grouped by the category main header $build = Excel::create($name, function ($excel) use ($priceResult) { $excel->setTitle('Test Products'); UPDATE: SO I'm thinking my desired resulting array would be something like: CategoryCode : 123 CategoryName : TestCategory CategoryDescription: For Testing Products{ 0{ Product_code : 123, CountNumber : 12, ProductDescription: Test Product, price_amount : 150.00 }, 1{ Product_code : 112, CountNumber : 32, ProductDescription: Test Product 2, price_amount : 250.00 } } That way each category can be a header and all of its products can be rows for each category
  3. After searching postings on multiple forums, I am officially now "Freaking OUT" trying to understand something that is probably very simple, but cannot seem to grasp. I simply want to read basic .csv data that is sent/uploaded directly to a PHP page, and to then append each record that shows up to a single .csv file on the server. The incoming data is supposed incoming via $_POST['csv'] ... at least that's what I was told. Each.csv record line being sent/uploaded is very simple (either single or multiple records in one small file): text1,text2,text3,text4,text5 For additional processing I know about 'explode', etc., but right now I am stuck even trying to do an 'echo' to display the simple incoming data "as is". One option I tried was: $postdata = file_get_contents("php://input"); echo $postdata; In the Java App monitoring I get the following after 3 records are sent/uploaded to the PHP URL: Server response status line: HTTP/1.1 200 OK I find this strange since I did not include... http_response_code(200); ... in the page code. Obviously, I do NOT know what I am doing here {SIGH}. Any assistance or guidance is appreciated. Thank you ! - FreakingOUT
  4. I have a php script that I've been running that seems to have been working but now I'm wondering if some of my logic is potentially off. I select records from a db table within a date range which I put into an array called ```$validCount``` If that array is not empty, that means I have valid records to update with my values, and if it's empty I just insert. The trick with the insert is that if the ```STORES``` is less than the ```Quantity``` then it only inserts as many as the ```STORES``` otherwise it inserts as many as ```Quantity```. So if a record being inserted with had Stores: 14 Quantity:12 Then it would only insert 12 records but if it had Stores:1 Quantity:20 It would only insert 1 record. In short, for each customer I should only ever have as many valid records (within a valid date range) as they have stores. If they have 20 stores, I can have 1 or 2 records but should never have 30. It seems like updating works fine but I'm not sure if it's updating the proper records, though it seems like in some instances it's just inserting too many and not accounting for past updated records. This is the logic I have been working with: if(!empty($validCount)){ for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $out[] = $failedUpdate; } } }else{ if($row2["QUANTITY"] >= $row2["STORES"]){ for($i=0; $i<$row2["STORES"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertStore; } } }elseif($row2["QUANTITY"] < $row2["STORES"]){ for($i=0; $i<$row2["QUANTITY"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertQuantity; } } } } Let's say customer 123 bought 4 of product A and they have 10 locations customerNumber | product | category | startDate | expireDate | stores ---------------------------------------------------------------------------------- 123 1 A 2018-08-01 2019-03-01 10 123 1 A 2018-08-01 2019-03-01 10 123 1 A 2018-08-01 2019-03-01 10 123 1 A 2018-08-01 2019-03-01 10 Because they purchased less than their store count, I insert 4 records. Now if my ```$validCheck``` query selects all 4 of those records (since they fall in a valid date range) and my loop sees that the array isn't empty, it knows it needs to update those or insert. Let's say they bought 15 this time. Then I would need to insert 6 records, and then update the expiration date of the other 9 records. customerNumber | product | category | startDate | expireDate | stores ---------------------------------------------------------------------------------- 123 1 A 2018-08-01 2019-03-11 10 123 1 A 2018-08-01 2019-03-11 10 123 1 A 2018-08-01 2019-03-11 10 123 1 A 2018-08-01 2019-03-11 10 123 1 A 2018-08-01 2019-03-11 10 123 1 A 2018-08-01 2019-03-11 10 123 1 A 2018-08-01 2019-03-11 10 123 1 A 2018-08-01 2019-03-11 10 123 1 A 2018-08-01 2019-03-11 10 123 1 A 2018-08-01 2019-03-11 10 There can only ever be a maximum of 10 (store count) records for that customer and product within the valid date range. As soon as the row count for that customer/product reaches the equivalent of stores, it needs to now go through and update equal to the quantity so now I'm running this but it's not running and no errors, but it just returns back to the command line $total = $row2['QUANTITY'] + $validCheck; if ($total < $row2['STORES']) { $insert_count = $row2['QUANTITY']; $update_count = 0; } else { $insert_count = $row2['STORES'] - $validCheck; // insert enough to fill all stores $update_count = ($total - $insert_count); // update remainder } for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $failedUpdate = "UPDATE_FAILED"; print_r($failedUpdate); $out[] = $failedUpdate; } } for($i=0; $i<$insert_count; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $failedInsertStore = "INSERT_STORE_FAILED!!!: " . $ex->getMessage(); print_r($failedInsertStore); $out[] = $failedInsertStore; } }```
  5. exceedinglife

    Php bootstrap 4 email from form

    Hello all, I have a website with a form that I want a user to fill out then if it is valid I have the button submit and I want it to email me. The message. If success full I want a message to popup on screen saying success I am using bootstrap 4 <div class="messageSuccess"></div> <div class="row"> <div class="col-md-9 mb-md-0 mb-5"> <form id="contact-form" name="contact-form" action="" method="post"> <!--action="contactEmail.php" --> <div class="row "> <div class="col-md-6 "> <div class="md-form mb-0 "> <input class="form-control" type="text" id="txtName" name="txtName" required /> <label for="txtName">Your Name </label> <div class="nameError"></div> </div> </div> <div class="col-md-6 "> <div class="md-form mb-0 "> <input class="form-control" type="text" id="txtEmail" name="txtEmail" required /> <label id="lblEmail" for="txtEmail">Your Email Address </label> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="md-form mb-0"> <input class="form-control" type="text" id="txtSubject" name="txtSubject" data-error="Subject Here" required /> <label for="txtSubject">Subject </label> <div class="help-block with-errors"></div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="md-form"> <textarea class="form-control" type="text" id="txtMessage" name="txtMessage" rows="4" required data-error="Please leave us a message."></textarea> <label for="txtMessage">Your Message </label> </div> </div> </div> <div class="text-center text-md-left"> <input type="submit" id="BtnFormSubmit" class="btn btn-primary btn-xl text-white" value="Send Message" /> </div> <div class="status"></div> </form> <!-- JavaScript Inner File Form Validation --> <script type="text/javascript"> $(document).ready(function () { var form = $("#contact-form"); var name = $("#txtName").val(); var email = $("#txtEmail").val(); var subject = $("#txtSubject").val(); var message = $("#txtMessage").val(); var btnSubmit = $("BtnFormSubmit"); $(form).submit(function (event) { if (this.checkValidity() == false) { $(this).addClass("was-validated"); event.preventDefault(); event.stopPropagation(); } alert("Form Valid to create message"); if (!event.isDefaultPrevented) { alert("passed prevent default"); var url = "testemail.php"; // POST values 'ajax' $.ajax({ type: "POST", url: url, data: $(this).serialize(), success: function (data) { // done: // data = JSON object object for contactEmail.php // recieve message type: success | danger var messageAlert = "alert- " + data.type; var messageText = data.message; // Bootstrap alert box HTML var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" ' + 'data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>'; // if messageAlert and messageText if (messageAlert && messageText) { // Put message on page in messageSuccess section. $(form).find("#messageSuccess").html(alertBox); // Reset the form. $(form)[0].reset(); } } }); //return false; } }); //$(name).blur(function () { //}) // Validate :inputs $(":input").blur(function () { let controlType = this.type; switch (controlType) { case "text": case "password": case "textarea": validateText($(this)); break; case "email": validateEmail($(this)); break; default: break; } }); // each :input focusin remove existing validation messages if any. $(":input").click(function () { $(this).removeClass("is-valid is-invalid"); }) /* OPTIONAL ':input' KEYDOWN validation messages remove */ // Reset Form and remove all validation messages. $(":reset").click(function () { $(":input").removeClass("is-valid is-invalid"); $(form).removeClass("was-validated"); }); }); // Validate Text Function function validateText(control) { let textField = control.val(); if (textField.length > 1) { $(control).addClass("is-valid"); } else { $(control).addClass("is-invalid"); } } // Validate Email Function (Email newer regex: /^([\w-\.]+@([\w-]+\.)+[\w-]{2,6})?$/ ) function validateEmail(control) { let textField = control.val(); let regexPattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,6}\b$/i; if (regexPattern.test(textField)) { $(control).addClass("is-valid"); } else { $(control).addClass("is-invalid"); } } </script> <?php $from = 'SampleEmail@YourEmail.com'; $sendTo = 'sample@Gmail.com'; $subject = 'Your Message Subject Here';// Email Message Contact Form Fields // Array - ($varName => Text from controls) $controls = array('txtName' => 'Name', 'txtEmail' => 'Email', 'txtSubjext' => 'Subject', 'txtMessage' => 'Message'); $successMessage = 'Contact Message Successfully Sent. Thank you, I will get back to you soon.'; $errorMessage = 'There was an error submitting your message, Please try again. Or try later.'; error_reporting(E_ALL & ~E_NOTICE); try { if(count($_POST) == 0) throw new \Exception('Contact Form Message is empty'); $emailText = "You have a new message from your contact form\n------------------------------------------------------\n"; foreach($_POST as $key => $value) { if(isset($controls[$key])) { $emailText .= "$controls[$key]: $value\n"; } } $headers = array('Content-Type: text/plain; charset="UTF-8";', 'From: ' . $from, 'Reply-To: ' . $from, 'Return-Path: ' . $from, ); // Send email mail($sendTo, $subject, $emailText, implode("\n", $headers)); $responseArray = array('type' => 'success', 'message' => $successMessage); } catch(\Exception $e) { $responseArray = array('type' => 'danger', 'message' => $errorMessage); } // If AJAX request return JSON response **RARE** if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $encodedJSON = json_encode($responseArray); header('Content-Type: application/json'); echo $encodedJSON; } else { echo $responseArray['message']; } ?>
  6. Hi, I have the below code to show the suggestion text, now it’s showing all the words which contain the letter when I first type in the text field. For example, If I typed the letter “a”, it should show only the words which start with the letter “a”, now it’s showing all the words which contain the letter “a” in the suggestion. Below is my code. Thanks in advance. <?php $xmlDoc=new DOMDocument(); $xmlDoc->load("links.xml"); $x=$xmlDoc->getElementsByTagName('link'); //get the q parameter from URL $q=$_GET["q"]; //lookup all links from the xml file if length of q>0 if (strlen($q)>0) { $hint=""; for($i=0; $i<($x->length); $i++) { $y=$x->item($i)->getElementsByTagName('title'); $z=$x->item($i)->getElementsByTagName('url'); if ($y->item(0)->nodeType==1) { //find a link matching the search text if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) { if ($hint=="") { $hint="<a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes->item(0)->nodeValue . "</a>"; } else { $hint=$hint . "<br /><a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes->item(0)->nodeValue . "</a>"; } } } } } // Set output to "no suggestion" if no hint was found // or to the correct values if ($hint=="") { $response="no suggestion"; } else { $response=$hint; } //output the response echo $response; ?>
  7. I want to build a online "app builder" project that users can create android / iphone applications online without any coding knowledge. These sites are very common in market. They offer onclick app builder. I have skill in development of web applications using php frameworks. My question is How we can generate android apk from our server after getting the necessary information from user? (Appname, icon, packagename etc) PHP can do this entire task?, if yes any framework for that? Can you give me some basic tips to generate apk from our server? Can we genrate both android and iphone app from one single code? What are the requirements needed for the server? Anybody having skills in these areas, please help me. I need basic tips to get started this project. Thanks
  8. I'm trying to build a tree to display product groups, but I can't achieve what I want. There is a hierarchy for the tree which I need to follow: 1H 1HS 1HSMP I want to list all the categories (1H) with its subcategories(1HS), and it's subcategories (1HSMP). This is the code I'm currently using: <ul> <?php //Here we fetch category $categories_list = array(); if($stmt = $conn -> prepare("SELECT a.category, a.subcategory, a.subcategory1, a.category_description, a.subcategory_description, a.subcategory_description1, SUM(nsq.sales_amount) AS sales, SUM(nsq.sales_amount+nsq.cost_amount) AS RUC FROM dpb.articles a LEFT JOIN dpb.nav_sales_qty nsq ON nsq.article_no = a.article_no WHERE nsq.entry_type_desc = 'Prodaja' GROUP BY a.subcategory1")) { $stmt -> execute(); $stmt -> store_result(); $stmt -> bind_result($category, $subcategory, $subcategory1, $category_description, $subcategory_description, $subcategory_description1, $total_sales, $total_profit); while($stmt -> fetch()) { $categories_list[] = array('category' => $category, 'subcategory' => $subcategory, 'subcategory1' => $subcategory1, 'category_description' => $category_description, 'subcategory_description' => $subcategory_description, 'subcategory_description1' => $subcategory_description1, 'total_profit' => $total_profit, 'total_sales' => $total_sales); } $stmt -> close(); } foreach($categories_list as $key => $value) { ?> <li><?php echo $value['category'].' - '.$value['category_description']; ?> <ul> <?php //Here we filter subcategory if(strpos($value['subcategory'], $value['category']) === 0) { //Iterate over subcategory foreach ($value as $key2 => $value2) { debugVar($value2); ?> <li data-jstree='{"opened":true}'><?php echo $value2['subcategory'] . ' - ' . $value2['subcategory_description']; ?> <ul> <?php //Here we filter subcategory2 if (strpos($value['subcategory1'], $value['subcategory']) !== false) { ?> <li data-jstree='{"type":"file"}'> <?php echo $value['subcategory1']; ?> </li> <?php //Here we close subcategory1 if statement } ?> </ul> </li> <?php //Here we close subcategory if statement } } ?> </ul> </li> <?php //Close foreach loop } ?> </ul> The result I'm getting is attached in the photo, and it's not what I want! The result I need is the following: I find a category (1H), and then I find all of its subcategories which are 1H% (all that start with 1H) and display them bellow 1H. Then I iterate over all of these subcategories (example 1HS%, 1HP%, 1HRD%) and I find all of their subcategories which are starting with (1HS, 1HP, 1HRD) and display them. Example: 1H 1HS 1HSMP 1HSTR 1HSKT 1HP 1HPSD 1HPDD 1HPSA 1HRD 1HRDA 1HRDBV 1HRDTE 1HRDEF Can you please help me how to achieve that? I spent a lot of time, and I can't get the proper result.
  9. Hi guys, Whats the best way of sending mails from multiple table? This is what i did, but i feel there should be a better way of doing it cos sometime it delivers and sometimes it doesn't (don't know why though). Thanks $subj="New Sign up Notification"; $header="MIME-Version: 1.0" . "\r\n"; $header .="Content-type:text/html;charset=UTF-8" . "\r\n"; $header .="From: GOODGUYS<noreply@yoyo.com>"; //TABLE 1 $t1 = "table1"; $stmt = $pdo->query(" SELECT t1_email, t1_name FROM $t1 "); while($rows = $stmt->fetch(PDO::FETCH_ASSOC)){ $t1_name = $rows['t1_name']; $t1_email = $rows['t1_email']; $t1_msg =" <html> <body> <h3>Subject: News</h3> <p> Hi $t1_name, <br> This is a message to you blah blah blah </p> <p> Thank you.<br> </p> </body> </html> "; mail($t1_email,$subj,$t1_msg,$header); } //TABLE 2 $t2 = "table2"; $stmt = $pdo->query(" SELECT t2_email, t2_name FROM $t2 "); while($rows = $stmt->fetch(PDO::FETCH_ASSOC)){ $t2_name = $rows['t2_name']; $t2_email = $rows['t2_email']; $t2_msg =" <html> <body> <h3>Subject: News</h3> <p> Hi $t2_name, <br> This is a message to you blah blah blah </p> <p> Thank you.<br> </p> </body> </html> "; mail($t2_email,$subj,$t2_msg,$header); } //TABLE 3 $t3 = "table3"; $stmt = $pdo->query(" SELECT t3_email, t3_name FROM $t3 "); while($rows = $stmt->fetch(PDO::FETCH_ASSOC)){ $t3_name = $rows['t3_name']; $t3_email = $rows['t3_email']; $t2_msg =" <html> <body> <h3>Subject: News</h3> <p> Hi $t3_name, <br> This is a message to you blah blah blah </p> <p> Thank you.<br> </p> </body> </html> "; mail($t3_email,$subj,$t3_msg,$header); }
  10. Simply put, I every night I have to pull a HUGE xml file (5mb 4500+ records). with this data ( small sales site), I create a webpage using the data provided. Pretty simple. However, I first used XML and converted it to arrays. This was problematic for functions and manipulating etc.. or picking out discounts and specific items etc. So Now I use the xml file, and convert it to sql - this as you know is very time consuming (longest time is about 10-12min using INSERT UPDATE ON DUPLICATE). So I have to use a cronjob to perform this. I would rather have the page dynamicly loaded when user is visiting. Now SQL works nicely as all the manipulation features are fast. However, I still think it feels sluggish. And it feels sloppy. I do not want to learn XSLT (LAZY?), I am comfortable with PHP. I can already parse the xml file fast. Just need a way to manipulate the data. mainly sorting, and picking out specific items in the xml - then sort those results. One method I did use was to cache what I manipulated and then overnight I pull the new feed, I delete the cache. Hopefully this is not answered already, gonna feel like an idiot. What would you pro's recommend? Leave it at the SQL? Or keep pursuing the XML?
  11. As you can see in the code below: it's a PHP script that generates fake hits on a given URL with the help of Cron jobs. I want to know how to set up a session duration of a hit like 5 minutes or more. Feel free to edit the complete code As you can see in the code below: it's a PHP script that generates fake hits on a given URL with the help of Cron jobs. I want to know how to set up a session duration of a hit like 5 minutes or more. Feel free to edit the complete code //Let's make sure no warrnings are displayed by PHP error_reporting(0); // Specify url that shoud receive hits // make sure to include trailing slash "/" at the end of folders $url_1 = "http://www.yourdomain.com/"; // Specify your server and port $myserver = "yourdomain.com:80"; // Specify how many hits to receive every time the script is run // Selecting more then 5 may not work $randnr = 2; //read proxy file $proxies = file("proxy.txt"); //now we will get a random proxy address from the proxies.txt file $getrand = array_rand($proxies, $randnr); for($x=0;$x<$randnr; $x++){ //setting time limit to zero will ensure the script doesn't get timed out set_time_limit(0) //now we will separate proxy address from the port $PROXY_URL=$proxies[$getrand[$x]]; $proxyarr = explode(":", $PROXY_URL); $address = trim($proxyarr[0]); $port = trim($proxyarr[1]); //following code generates the header file $headerinfo =array( 'User-Agent' => 'UHits/1.0 ('.$myserver.')', 'Accept' => 'image/gif, image/x-xbitmap, image/jpeg, image/png, */*', 'Pragma' => 'no-cache', 'Connection' => 'keep-alive'); reset($headerinfo); //now we are ready to reach our website through the proxy $fp=fsockopen($address,$port); if($fp) { fputs($fp,"GET $url_1 HTTP/1.1rn"); fputs($fp,"Host: $myserverrn"); reset($headerinfo); while(list($header,$value)=each($headerinfo)) { fputs($fp,"$header: $valuern"); //let's give the script some time to execute sleep(2); } //end while fputs($fp,"rn"); fclose($fp); } //end if } //end for
  12. Hello! I'm new here, and this is my first post. Let's say I have a list of four links I want to display on a page using php, call them 1 2 3 and 4. Now, when link 2 is visited, or any of the links, the destination url opens in a new window, a cookie is set onclick and the page reloads, and the visited link goes to the bottom of my list, and the new the new order is: 1 3 4 2. php function to read cookie and calculate the new order here echo '<ul> <li> <a href="https://current-page" onClick="window.open(\'http://page-1\'); setCookie(\''.$cookie_name.'\', \'1\', '.$cookie_expires_time.');">Link One</a> </li> <li> <a href="https://current-page" onClick="window.open(\'http://page-2\'); setCookie(\''.$cookie_name.'\', \'2\', '.$cookie_expires_time.');">Link Two</a> </li> <li> <a href="https://current-page" onClick="window.open(\'http://page-3\'); setCookie(\''.$cookie_name.'\', \'3\', '.$cookie_expires_time.');">Link Three</a> </li> <li> <a href="https://current-page" onClick="window.open(\'http://page-4\'); setCookie(\''.$cookie_name.'\', \'4\', '.$cookie_expires_time.');">Link Four</a> </li> </ul>'; echo 'some javascript function to enable set cookie on click'; Any help is much appreciated. Thanks.
  13. Hi, new to this forum and got an issue here: I am getting a console error of a syntax error from the browser (chrome) console: var dataString='lookupId='+<?php echo $_GET['lookupId']; ?>; //Uncaught SyntaxError: Unexpected token ; var dataPlusLookID = dataString+lookId; var country_dest_id=""; $.ajax({ type : 'GET', url : 'https://www.example.co.uk/files/viator/ajax_statelist_left.php', data : dataString, dataType : 'json', success : function(data) { $("#currency_code").val(data.currency_code); $("#country_name").val(data.country_name_without_design); $("#country_dest_id").val(data.country_dest_id); country_dest_id=data.country_dest_id; } }); function searchadventurelist(path){ location.href=path+'&country_dest_id='+country_dest_id+'&lookupId=<?php echo $lookupId;?>'; } Appreciate the help
  14. Argonust

    display images

    Hi I have a script for displaying images see below <?php include "header.php"; require 'gallery/Gallery.php'; ?> <?php $models=file("models.txt", FILE_USE_INCLUDE_PATH); if(isset($_POST['model'])){ $model=($_POST['model']); } $gallery = new Gallery(); $gallery->setPath('gallery/images/'.$model); $images = $gallery->getImages(array('jpg')); ?> <div class="container"> <?php if($images): ?> <div class=gallery cf > <?php foreach($images as $image):?> <div class="gallery-item"> <a href="<?php echo $image['full'];?>"><img src="<?php echo $image['thumb']; ?>"> </div> <?php endforeach; ?> </div> <?php else: ?> There are no images <?php endif; ?> </div> <div class="form"> <form action="index.php" method="POST"> <select name="model" class="select_box" data-placeholder="Select Model" style= width:120px;/> <option></option> <?php foreach($models as $mod):?> <option><?php echo $mod ?></option> <?php endforeach;?> </select> <input type="submit" Value="Select" value="Select"> </form> </div> <script type="text/javascript"> $(".select_box").chosen(); </script> The above code works , i get no errors this images array is populated at this line "$images = $gallery->getImages(array('jpg'));" but they do no show in the container class. When I run this script all the css shows borders and the like. bet there are no images didplayed. However it does work if I replace the code in the container class with this $images = "gallery/images/".$model; $files = scandir($images); unset($files[0], $files[1]); $rows = array_chunk($files, 6); foreach ($rows as $row){ foreach ($row as $image){ echo '<td><a href="gallery/images/', $model,'/', $image,'"><img src="gallery/images/',$model,'/thumbs/',$image,'"/></a></td>'; } } Is it possible I have a conflict with the jQuery. I am using the plugin called "chosen" The $models is a text file that populates the drop down box Thank you, your help is very much appreciated
  15. sigmahokies

    Which best and cheaper host

    Hi everyone, It's been awhile since I was here in autumn time. How are everyone here? I'm good. I want to know, which best and cheaper host to create website with PHP? include Phpmyadmin or SQLBuddy. Please let me know... Thanks, Gary
  16. ttsprez

    Query Statement Help

    I'm having an issue with a query statement pulling info: This link carries customers to a "document gateway" where they are required to enter a reference code. https://pdforms.losttitleconnection.net/TX Title App Gate.php Use this Reference Code for test purpose: QKEX49MKDE On submit the PHP code is to take the reference code from the Post function of the gateway form and convert it to a variable $refcode This variable is then used in the query statement to pull 'name' and 'data' from the form_data table and use it to replace form field names with data in an html template. Then it is to present the new form in a pdf format to the browser for download or printing. I'm using the dompdf library to do this, but for now, am only using a short query test code to ensure I'm pulling the correct data by having the code display results. Currently, on submit, the browser is presenting the following: SELECT name,data FROM thetitl1_livesite754.form_data WHERE form_id IN(SELECT id FROM thetitl1_livesite754.forms WHERE reference_code = '') The following is the code as it appears in my PHP file. Help to get this figured out would be greatly appreciated. <?php //create a connection to MySQL require 'dogs.php'; //query for reference_code from 'forms' table $refcode = filter_input(INPUT_POST,'reference_code'); $mysqli = new mysqli($server, $username, $password, $dbase); $query = "SELECT name,data FROM thetitl1_livesite754.form_data WHERE form_id IN(SELECT id FROM thetitl1_livesite754.forms WHERE reference_code = '" . $refcode . "')"; die($query); $results = $mysqli->query($query); $new_form = file_get_contents("TX_Title_App.html"); //Replaces form_fields in html temp with "data" if ($results) { //below is the line referenced in error message above while ($row = mysqli_fetch_fields($results)) { echo $row["name"] . ":" . $row["data"] . "<br>"; $new_form = str_replace($row["name"], $row["data"], $new_form); } } ?>
  17. dodgeitorelse3

    sort multi-dimensional array by name

    I have an array that is created using the following code: $mapname='mapname1'; $type="pvp"; $beta="y"; $final="n"; $modded="n"; $classification="land"; $sf="n"; $tod="dawn"; $weather="fog"; $es2="y"; $mapname2='mapname2'; $type2="pvp"; $beta2="n"; $final2="y"; $modded2="n"; $classification2="sea"; $sf2="n"; $tod2="night"; $weather2="clear"; $es22="n"; $mapname3='mapname3'; $type3="pvp"; $beta3="y"; $final3="n"; $modded3="y"; $classification3="air"; $sf3="y"; $tod3="day"; $weather3="rain"; $es23="n"; $tadminlist["pvp"] = array ( ); array_push($tadminlist["pvp"], array ("name" => $mapname, "type" => $type, "beta" => $beta, "final" => $final, "modded" => $modded, "classification" => $classification, "sf" => $sf, "tod" => $tod, "weather" => $weather, "es2" => $es2)); array_push($tadminlist["pvp"], array ("name" => $mapname2, "type" => $type2, "beta" => $beta2, "final" => $final2, "modded" => $modded2, "classification" => $classification2, "sf" => $sf2, "tod" => $tod2, "weather" => $weather2, "es2" => $es22)); array_push($tadminlist["pvp"], array ("name" => $mapname3, "type" => $type3, "beta" => $beta3, "final" => $final3, "modded" => $modded3, "classification" => $classification3, "sf" => $sf3, "tod" => $tod3, "weather" => $weather3, "es2" => $es23)); echo "<pre>"; print_r($tadminlist); echo "</pre>"; echo "line = mapname, type, beta, final, modded, classification, sf, tod, weather, es2<br /><br />"; $i =0; foreach($tadminlist["pvp"] as $key => $tlist) { echo $tadminlist['pvp'][$i]['name'].", ". $tadminlist['pvp'][$i]['type'].", ". $tadminlist['pvp'][$i]['beta'].", ". $tadminlist['pvp'][$i]['final'].", ". $tadminlist['pvp'][$i]['modded'].", ". $tadminlist['pvp'][$i]['classification'].", ". $tadminlist['pvp'][$i]['sf'].", ". $tadminlist['pvp'][$i]['tod'].", ". $tadminlist['pvp'][$i]['weather'].", ". $tadminlist['pvp'][$i]['es2']."<br /><br />"; $i++; } The output is: Array ( [pvp] => Array ( [0] => Array ( [name] => mapname1 [type] => pvp [beta] => y [final] => n [modded] => n [classification] => land [sf] => n [tod] => dawn [weather] => fog [es2] => y ) [1] => Array ( [name] => mapname2 [type] => pvp [beta] => n [final] => y [modded] => n [classification] => sea [sf] => n [tod] => night [weather] => clear [es2] => n ) [2] => Array ( [name] => mapname3 [type] => pvp [beta] => y [final] => n [modded] => y [classification] => air [sf] => y [tod] => day [weather] => rain [es2] => n ) ) ) line = mapname, type, beta, final, modded, classification, sf, tod, weather, es2 mapname1, pvp, y, n, n, land, n, dawn, fog, y mapname2, pvp, n, y, n, sea, n, night, clear, n mapname3, pvp, y, n, y, air, y, day, rain, n I would like to sort the foreach loop by name in descending order. I read the page at http://php.net/manual/en/function.array-multisort.php but was unable to figure it out. Could someone give me some direction please?
  18. I have a form that I decided to include Google recaptcha as an added measure of security. When I added the recaptcha it triggers an error because the recaptcha is not whitelisted. I read that HTML5 does not allow assigning the name attribute to div. i.e. <div name="myName"></div>. Against convention, I tried adding a name to the recaptcha div and adding that name to the whitelist. That approach failed. There is an iframe within the div that has the name attribute. I tried using the iframe name in the whitelist. That approach also failed. There is a hidden input that has an id="recaptcha-token". I added 'recaptcha-token' to the whitelist. This approach also failed. The hidden input is generated by the recaptcha api, so I don't think I have a means of assigning a name attribute to this input. Does anyone have a workaround or suggestion ? Note: form validation and whitelist all worked as expected prior to adding recaptcha. This is the div within the form. <div class="row"> <div class="col-md-12"> <div class="g-recaptcha" data-sitekey="<?php print $public_key;?>"></div> </div> </div> This is the code block using the whitelist. // VERIFY LEGITIMACY OF TOKEN if (verifyFormToken('form1')) { // Building a whitelist array with keys which will send through the form, no others would be accepted later on $whitelist = array('token','req-fName','req-lName','req-email','req-phone','req-address','req-city','req-state','req-zip','req-message','req_method','req-dateDepart','req-dateReturn','recaptcha-token','submit'); // Building an array with the $_POST-superglobal foreach ($_POST as $key=>$item) { // Check if the value $key (fieldname from $_POST) can be found in the whitelisting array, if not, die with a short message to the hacker if (!in_array($key, $whitelist)) { writeLog('Unknown form fields'); die('Hack-Attempt detected. Only the fields originally included in the form are allowed!'); } } } Thanks in advance for having a look at this.
  19. I'm having an issue related to creating forms within a foreach loop. As of now, I have 3 forms in a div, each with their own datepicker instance and submit button ( also using a hidden input for the pageID) The datepickers are unique and working independently, but when it comes to posting the data via ajax and handling it in a php script, It's not inserting data into my db because the names of my two inputs are not unique. I don't really know how to make them unique on the form and then handle those unique names back in the script. Only one form will be submitted at a time so I'm trying to make it to where the user can click on any of these datepickers, select a date and submit, and the ajax will handle only the page ID and the datepicker value for that form submitted and the PHP script will then insert. The sql in my php script works but my POST variables are where I'm having the issue here. Any help is much appreciated. <?php foreach($expiredPages as $expiredPage): ?> <form id="updateTime_<?php echo $expiredPage['id']?>" class="updateTime" method="POST"> <input type="hidden" name="currentPageID<?php echo $expiredPage['id']?>" value="<?php echo $expiredPage['id']?>"> <div class="datepick input-group date" id="datetimepicker_<?php echo $expiredPage['id']?>" data-target-input="nearest"> <input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker_<?php echo $expiredPage['id']?>" name="datePicker<?php echo $expiredPage['id']?>" /> <span class="input-group-addon" data-target="#datetimepicker_<?php echo $expiredPage['id']?>" data-toggle="datetimepicker"> <span class="fa fa-calendar"></span> </span> </div> <input type="submit" name="Extend Date" class="extendDate"> </form> <?php endforeach; ?> <script type="text/javascript"> $(".extendDate").click(function(){ event.preventDefault(); var string = $('.updateTime').serialize(); console.log(string); // AJAX Code To Submit Form. $.ajax({ type: "POST", url: "extendTime.php", data: string, dataType: 'json', cache: false, success: function(response){ location.reload(); } }); }); </script> extendTime.php $pageID = $_POST['currentPageID']; $newTime = $_POST[$dtPick]; $newEndTime = DateTime::createFromFormat('m/d/Y h:i A', $newTime); $convertedDateTime = $newEndTime->format('Y-m-d H:i:s'); $extendExpiration = " UPDATE pages SET end_time = '$convertedDateTime' WHERE id = '$pageID'; "; if($mysqlConn->query($extendExpiration)=== TRUE){ echo "SUCCESS"; }else{ echo "Could not extend Time"; }
  20. shan2batman

    notifications system not working

    Hi, guys i’m trying to create a notification alert for private message section in my project. The problem is everytime when the sender is sending message the notification bar shows new msg’s in sender profile and not in receivers profile. I don’t know where i’m going wrong so can any of you experts solve it. i’ll post the code here The private message page code: The db from where the queries are called from: CREATE TABLE IF NOT EXISTS `private_message` ( `pm_id` int(255) NOT NULL AUTO_INCREMENT, `r_seen` enum('0','1') NOT NULL, `receiver` varchar(255) NOT NULL, `sender` varchar(255) NOT NULL, `sent_time` datetime NOT NULL, `subject` varchar(255) NOT NULL, `message` text NOT NULL, `sdelete` enum('0','1') NOT NULL, `rdelete` enum('0','1') NOT NULL, `parent` varchar(255) NOT NULL, `has_replies` enum('0','1') NOT NULL, `rread` enum('0','1') NOT NULL, `sread` enum('0','1') NOT NULL, `receiver_uid` int(255) NOT NULL, `sender_uid` int(255) NOT NULL, `os_id` int(255) DEFAULT NULL, UNIQUE KEY `pm_id_2` (`pm_id`), KEY `pm_id` (`pm_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=95 ; The private message page code: <?php //error_reporting(0); include 'includes/header.php'; if (!isset($_SESSION['app'])) { header("location: index.php?usernotfound?id=017"); } $updateid=""; $title=""; $data=""; $sess_id=(int)$_SESSION['id']; $sess_uname = htmlentities($_SESSION['uname']); $session_uname = stripslashes($sess_uname); $f_uname0 = htmlentities($_GET['u']); $f_uname = stripslashes($f_uname0); $sql = "select * from user where uname=:uname and activated='1' limit 1"; $stmt = $conn->prepare($sql); $stmt->bindparam(":uname", $f_uname); $stmt->execute(); $row = $stmt->fetchAll(PDO::FETCH_ASSOC); $_SESSION['f_pm']=$f_uname; $f_uid=$row[0]['user_id']; $fname_s = $row[0]['fname']; $lname_s = $row[0]['lname']; $uname_s = $row[0]['uname']; $pmid= htmlentities($_GET['pmid']); if(isset($pmid)){ $updatedelete="update private_message set sread='1', r_seen='1' where pm_id=:pmid "; $stmt_r=$conn->prepare($updatedelete); //$stmt->bindValue(":originator",$originator); $stmt_r->bindValue(":pmid",$pmid); $stmt_r->execute(); } $is_friend=FALSE; $ownerblockviewer=FALSE; $viewerblockowner=FALSE; $isowner="no"; if($f_uid==(int)$_SESSION['id']&&isset($_SESSION['app'])){ $isowner="yes"; } if ($f_uname != $session_uname &&$_SESSION['app']==TRUE) { $freind_check = "select friend_id from friends where friend_one_uid=:session and friend_two_uid=:f_name and accepted='1' or friend_one_uid=:f_name and friend_two_uid=:session and accepted='1' limit 1"; $stmt = $conn->prepare($freind_check); $stmt->bindparam(":session", $sess_id); $stmt->bindparam(":f_name", $f_uid); $stmt->execute(); $isfriend=$stmt->rowCount(); if ($isfriend>0) { $is_friend = TRUE; } $blockcheck0 = "select blocked_id from blockedusers where blocker_uid=:f_name and blockee_uid=:session limit 1"; $stmt1 = $conn->prepare($blockcheck0); $stmt1->bindValue(":session", $sess_id); $stmt1->bindValue(":f_name", $f_uid); $stmt1->execute(); $owner= $stmt1->rowCount(); if ( $stmt1->rowCount()>0) { $ownerblockviewer = TRUE; } $blockcheck2 = "select blocked_id from blockedusers where blocker_uid=:session and blockee_uid=:f_name limit 1"; $stmt2 = $conn->prepare($blockcheck2); $stmt2->bindparam(":session", $sess_id); $stmt2->bindparam(":f_name", $f_uid); $stmt2->execute(); $viewer=$stmt2->rowCount(); if ($stmt2->rowCount() > 0) { $viewerblockowner = TRUE; } } $pm_ui=""; ?> <div class="container-fluid"> <br><div class="row"> </div><br> <div class="row"> <div class="col-sm-2 col-md-3 col-xs-4"> <div class="friend_pm"> <?php include 'notification/friend_pm.php'; ?> </div> </div> <div class="col-lg-8 col-xs-8 col-md-9"> <?php #if visitor to profile is friend and is not the owner, can send private message. #build ui carry the profile id, visitorname,pm subject and comments. if($is_friend==TRUE && $isowner=="no"){ $sql1="select * from private_message where(receiver=:u and sender=:sess and rdelete='0') " . "or " . "(sender=:u and receiver=:sess and sdelete='0' ) order by sent_time desc "; $stmt1=$conn->prepare($sql1); $stmt1->bindValue(":u",$f_uname); $stmt1->bindValue(":sess",$_SESSION['uname']); $stmt1->execute(); $fetch=$stmt1->fetchAll(PDO::FETCH_ASSOC); foreach ( $fetch as $row1) $pmid=$row1['pm_id']; $pm_ui='<hr><br><br>' . '<a class="btn mark-all mark_all_as_read" value="mark_all" originator="'. htmlentities($_SESSION['uname']).'" id="'.$pmid.'">Mark All as read</a><br>' . '<textarea id="pmtext" class="pm_message input-custom2" placeholder="Send a message"></textarea>' . '<br>' . '<button class="btn btn-warning pm_btn" attr="'.$row1['sender'].'" id="'.$f_uname.'" value="'.$pmid.'" type="new_pm" name="'.$session_uname.'">' . 'Send</button>'; } ?> <div id="status_ui"> <?php echo "<br><br><br><br><br><br><div class='jumbotron scroll-custom'>" . "<div class='pm_post'>"; include "notification/pm_inbox.php"; echo "</div></div>"; ?> <?php if($is_friend==TRUE&& $isowner=="no"){ echo $pm_ui; } ?> </div> <div class="col-sm-2 hidden-xs hidden-md"> </div> </div> </div> <script type="text/javascript"> var spinner="<img src='img/spinner.gif'>"; $(".pm_btn").click(function(){ var f_uname=$(this).attr('id'); var action=$(this).attr('type'); var s_uname=$(this).attr('name'); var pm_message=$(".pm_message").val(); var os_id=$(this).attr("value"); if(pm_message==""){alert("Please write something to send"); }else{ $.post("parser/pm_system.php", {"f_uname":f_uname,"action":action,"sess_uname":s_uname,"pm_message":pm_message,"os_id":os_id}, function(data){ $(".pm_message").val(""); // alert(data); // $(".jumbotron").prepend("<small>Reply from:-"+s_uname+" right now </small><br><p>"+pm_message+"</p>"); //lets the script scroll down to the bottom of the chat class automatically $(".scroll-custom").scrollTop($(".scroll-custom")[0].scrollHeight); });} }); $(".mark_as_read").click(function(){ var action=$(this).attr("value"); var id=$(this).attr("id"); var originator=$(this).attr("originator"); $.post("parser/pm_system.php", {"action":action,"pmid":id,"originator":originator}, function(data){ alert(data); }); }); $(".mark-all").click(function(){ var action=$(this).attr("value"); var id=$(this).attr("id"); var originator=$(this).attr("originator"); //alert(action+""+id+""+); $.post("parser/pm_system.php", {"action":action,"pmid":id,"originator":originator}, function(data){ alert(data); }); }); //logic for search box $(".search").keyup(function(){ var input=$(".search").val(); var length=input.length; $("#result").html(spinner).show(); var check=$(".checkbox-search").prop('checked'); if(check!=true){ $.post("search.php",({"(un|fn|ln)":input}),function(result){ $("#result").html(result).show(); }); }else if(check==true){ var input=$(".search").val(); $("#result").html(spinner).show(); $.post("search_group.php",({"group_name":input}),function(result){ $("#result").html(result).show(); }); } }); $(document).click(function(){ $("#result").hide(); }); function load_stuff(){ $(".pm_post").load("notification/pm_inbox.php"); } //loads friends who have sent messages function load_names(){ $(".friend_pm").load("notification/friend_pm.php"); } setInterval(function(){ load_stuff(); load_names(); },3000); $(document).click(function(){ $("#result").hide(); }); $("button.friend-add-btn").click(function(){ var id=$(this).attr('id'); var name=$(this).attr('name'); $(".spinner-friend-add"+id).html(spinner).show(); $.post( "parser/friend_sys.php", ({"user": name,"friend_one_uid":id}), function (data) { alert(data); $(".spinner-friend-add"+id).html(spinner).hide(); $(".friend_fade_"+id).fadeOut(); } ); }); $('[data-toggle="popover"]').popover(); //logic to accept fried request $(document).on("click", "button.accept_btn" ,function(){ var accept_id=$(this).attr('id'); var sess=$(this).attr('sess'); var name=$(this).attr('name'); $(".show-spinner").html(spinner).show(); $.post("notification/friend_req_accept.php",({"reqid":accept_id,"friend_two_uid":sess,"friend_two":name}),function(data){ $(".show-spinner").hide(); alert(data); }); }); //logic to reject friend request $(document).on("click", "button.reject_btn" ,function(){ var accept_id=$(this).attr('id'); $(".show-spinner").html(spinner).show(); $.post("notification/friend_req_reject.php",({"reqid":accept_id}),function(data){ $(".show-spinner").hide(); alert(data); }); }); //logic for sending friend requests // $("button.friend_btn").click(function () { $(document).on("click", "button.friend_btn",function(){ alert("see"); $(".friend").html(spinner).show(); var user_f = $(this).attr('user'); var id = $(this).attr('sess'); var name=$(this).attr('name'); $.post( "parser/friend_sys.php", ({"user": user_f,"friend_one_uid":id}), function (data) { alert(data); $(".friend").html(spinner).hide(); } ); //$(".friend").html(spinner).fadeOut(250); }); //logic to like this person button. $(document).on("click", "button.like_person_btn",function(){ $(".friend").html(spinner).show(); var user_f = $(this).attr('user'); var userid=$(this).attr('userid'); var id = $(this).attr('sess'); var name=$(this).attr('name'); $.post( "parser/like_this_person_parser.php", ({"user": user_f,"like_person_one_uid":id,"like_person_two_uid":userid}), function (data) { alert(data); $(".friend").html(spinner).hide(); } ); //$(".friend").html(spinner).fadeOut(250); }); //logic for blocking friends $(document).on("click", "button.block_btn",function(){ $(".show-spinner").html(spinner).show(); var user_f = $(this).attr('user'); $.post( "parser/block_system.php", ({"user": user_f}), function (data) { alert(data); } ); $(".show-spinner").html(spinner).fadeOut(250); }); $(document).on("click", "button.unfreind_btn",function(){ $(".show-spinner").html(spinner).show(); var user_f = $(this).attr('user'); $.post( "parser/unfriend_sys.php", {"user": user_f}, function (data) { alert(data); } ); $(".show-spinner").html(spinner).fadeOut(250); }); //logic for unblocking users whom were blocked $(document).on("click", "button.unblock_btn",function(){ $(".show-spinner").html(spinner).show(); var user_f = $(this).attr('user'); $.post( "parser/unblock_sys.php", ({"user": user_f}), function (data) { alert("You have unblocked this user"); $("button.unblock_btn").hide(); $("button.block_btn").show(); } ); $(".show-spinner").html(spinner).fadeOut(250); }); //to load notifications dynamically i used the set interval method. function load_notifications(thisview=''){ var theData = { view: thisview } $.ajax({ url: "notification/new_friends.php", method: "POST", data:theData, dataType:"json", success: function(data){ // alert(data); $(".drop-menu").html(data.notification); if(data.unseen_notification>0){ $(".badge1").html(data.unseen_notification); }else{ //alert(data); $(".drop-menu").html("No Notifications"); $(".badge1").html(data.unseen_notification);} } }); }; function notification(thisview=''){ var theData= { view: thisview } $.ajax({ url:"notification/ajax_notifications.php", method: "POST", data:theData, dataType: "json", success: function(data){ $(".notify-menu").html(data.notifications); if(data.unseen_notifications>0){ $(".badge3").html(data.unseen_notifications); } } }); } function notification_pm(thisview=''){ var theData= { view: thisview } var f_uname=$(".badge_pm").attr("type"); var sender=$(".badge_pm").attr("attr"); var sess=$(".badge_pm").attr("name"); var rcvr =$(".badge_pm").attr("id"); $.ajax({ url:"notification/ajax-pm-notification.php", method: "POST", data:{"theData":theData, "f_uname": f_uname}, dataType: "html", success: function(data){ if(data>0){ // alert(data); $(".badge_pm").html("New Msg's"); }else{ // alert(data); $(".badge_pm").html("No Msg's"); } } }); } //clicking on notification icon in header does this $(document).on("click", ".count_notification", function(){ var id=''; $.post("notification/count_notifications.php", {id:id}, function(data){ }); }); //load_notifications(); $(document).on("click",".count_friend", function(){ load_notifications('yes'); }); //loads every 2 seconds for chat setInterval(function(){ load_notifications(); notification(); notification_pm(); },5000); </script> </body> </html> the ajax notification page: <?php include '../includes/dbconfig.inc.php'; $f_uname= htmlentities($_POST['f_uname']); $mark="select parent,r_seen,rread,sread,receiver,sender from private_message where (receiver=:sess1 or sender=:sess2) and (r_seen='1' or r_seen='0') and (sread='1' or sread='0')"; $stmt_m=$conn->prepare($mark); $stmt_m->bindValue(":sess1", $_SESSION['uname']); $stmt_m->bindValue(":sess2", $_SESSION['uname']); //$stmt_m->bindValue(":f_uname", $f_uname); $stmt_m->execute(); $column=$stmt_m->fetch(); if ($column['r_seen']=='0'&&$column['parent']==$_SESSION['uname']) { echo'1'; // print_r($column); } elseif ($column['r_seen']=='1'&&$column['parent']==$_SESSION['uname']) { echo '0'; // echo 'old'; }elseif ($column['r_seen']=='0'&&$column['parent']!=$_SESSION['uname']) { echo '1'; //echo'new'; }elseif ($column['r_seen']=='1'&&$column['parent']!=$_SESSION['uname']) { echo '0'; // echo'new11'; } else { echo '0'; //print_r($f_uname); } logic for notifications in header: $mark="select rread,sread,receiver,sender from private_message where (receiver=:sess or sender=:sess) and has_replies='1' and rread='1' and sread='0'"; $stmt_m=$conn->prepare($mark); $stmt_m->bindValue(":sess", $_SESSION['uname']); //$stmt_m->bindValue(":f_uname", $f_uname); $stmt_m->execute(); $column=$stmt_m->fetch(); if($column['receiver']==$_SESSION['uname']&&$column['rread']>0&&$column['sread']==0) { if ($column['sender']!=$_SESSION['uname']) { print_r($column); $pm_n="<span class='badge_pm label label-pill label-success' type='".$f_uname."'>New Msg's</span><a href='private_message.php?u=".$_SESSION['uname']."'><img src='img/logo/message-white.png' alt='private_message'></a>"; } else { $pm_n="<span class='badge_pm label label-pill label-success' type='".$f_uname."'></span><a href='private_message.php?u=".$_SESSION['uname']."'><img src='img/logo/message-black.png' alt='private_message_alert'></a>"; } }elseif ($column['sender']==$_SESSION['uname']&&$column['rread']==1&&$column['sread']==0) { if ($column['receiver']!=$_SESSION['uname']) { $pm_n="<span class='badge_pm label label-pill label-success' type='".$f_uname."'></span><a href='private_message.php?u=".$_SESSION['uname']."'><img src='img/logo/message-black.png' alt='private_message_alert'></a>"; } else { print_r($f_uname); $pm_n="<span class='badge_pm label label-pill label-success' type='".$f_uname."'>New Msg's</span><a href='private_message.php?u=".$_SESSION['uname']."'><img src='img/logo/message-white.png' alt='private_message'></a>"; } }else { $pm_n="<span class='badge_pm label label-pill label-success' type='".$f_uname."'></span><a href='private_message.php?u=".$_SESSION['uname']."'><img src='img/logo/message-black.png' alt='private_message_alert'></a>"; }
  21. This brings up my complete novice question: How make a page go somewhere specific other than the top when it refreshes?
  22. Hi Been struggling to find a way to automatically go to the top of the page after the php contact form is executed, when the success message is displayed. Probhlem I have is that the form is quite long and when it is filled in the success or failure message is not fully seen as it displays at the top. Thanks Code below: <div class="row"> <div class="col-md-6"> <div class="offset-anchor" id="contact-sent"></div> <?php if (isset($arrResult)) { if($arrResult['response'] == 'success') { ?> <div class="alert alert-success" id="contactSuccess"> <strong>Success!</strong> Your message has been sent to us. </div> <?php } else if($arrResult['response'] == 'error') { ?> <div class="alert alert-danger" id="contactError"> <strong>Error!</strong> There was an error sending your message. (<?php echo $arrResult['error'];?>) </div> <?php } else if($arrResult['response'] == 'captchaError') { ?> <div class="alert alert-danger" id="contactError"> <strong>Error!</strong> Verificantion failed. </div> <?php } } ?>
  23. I'm working with a relationship table: id (AI), user_id, friend_id, status, type. The current behavior is that the Logged In user can send friendship requests to X user but if there is already a friendship request coming from the X user to the Logged In user; the logged in user instead of sending a new request to X user, he/she should accept the one that is already in the database(which is coming from the X-user). Here is an image of what I'm talking about(in the image, the status column displays 'accepted' but try to imagine it as it was 'pending', please) : So I currently have a function for adding friends for the current Logged-In user and it goes like this: public function follow($username){ // Check Login if(!$this->session->userdata('user_id')){ // Redirect to page redirect('users/login'); } // Get item $item = $this->User_model->get_username($username); // Already friends? $friendship = $this->User_model->the_relationship($item->id); if ($friendship->status == 'accepted' || $friendship->status == 'pending') { // Create Message $this->session->set_flashdata('error', 'You are already following this user.'); // Redirect to pages redirect('users/profile/'.$item->username); // BEGINNING OF - HERE IS WHERE THE PROBLEM IS } elseif($friendship->status == 'pending'){ // Get item $item = $this->User_model->get_username($username); // Page Data $data = array( 'user_id' => $item->id, 'friend_id' => $this->session->userdata('user_id'), 'status' => 'accepted', ); $this->User_model->updateFriendship($item->id, $data); /// END OF - HERE IS WHERE THE PROBLEM IS } else { // Get item $item = $this->User_model->get_username($username); // Page Data $data = array( 'user_id' => $this->session->userdata('user_id'), 'friend_id' => $item->id, 'status' => 'pending', 'type' => 'friendship', ); $this->Relationship_model->add($data); // Activity Array $data = array( 'resource_id' => $this->db->insert_id(), 'type' => 'friendship', 'action' => 'sent', 'user_id' => $this->session->userdata('user_id'), 'message' => '(' . $this->session->userdata('username') . ') sent a friend request to ('.$item->username.') ', ); // Insert Activity $this->Activity_model->add($data); // Set Message $this->session->set_flashdata('success', 'Friend request has been sent'); // Redirect redirect('users/profile/'.$item->username); } } and here are the two functions in the model which check the current status of the relationship between the current logged in user and the X user; the second function should update the status of the friendship if there is already one: LEGEND: $this->relationship: ci_relationship table $this->type: friendship type // Relationship for single public function the_relationship($id){ $this->db->select('*'); $this->db->from($this->relationship); $this->db->where('user_id', $this->session->userdata('user_id')); $this->db->where('friend_id', $id); $this->db->where('type', $this->type); $query = $this->db->get(); if($query->num_rows() >= 1){ return $query->row(); } else { return false; } } // Update Friendship Status public function updateFriendship($id, $data){ $this->db->where('user_id', $id); $this->db->where('friend_id', $this->session->userdata('user_id')); //$this->db->where('status', 'pending'); $this->db->where('type', $this->type); $this->db->update($this->relationship, $data); } I hope I could make myself clear. Thanks in advance.
  24. Hi I have a table that is filled with values already and now i want to add another column associate_id How can i update the columns with a random number? What i have is giving all the columns same number thanks $associates_id = mt_rand(10000, 99999); $stmt = $pdo->prepare("UPDATE associates SET associates_id= $associates_id "); $stmt->execute(); $affected_rows = $stmt->rowCount(); if ($affected_rows){ echo "DONE"; }else{ echo "NOT DONE"; }
  25. Hi, I am just getting a blank page and I am unable to figure out why such a simple concept is not working. Any help would be greatly appreciated. <?php //Error Check ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); try { $conn = new PDO("mysqli:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $statement = $conn->prepare("UPDATE test SET title= ? WHERE id= ?"); $statement->bind_param('si', $title,$id); $statement->execute(); if ($statement->affected_rows >0) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } $statement->close(); ?>

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.