PHPSponsored by Flatiron School

119K

Solutions

33K

Contributors

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.

Share tech news, updates, or what's on your mind.

Sign up to Post

I'm not real familiar with JSON, and I cannot figure out how to parse this simple array.
I am using jQuery 3.3.1 and FormData, as this is a multipart form. There are uploaded files that need to be processed.
Data is sending to PHP, and processing and updating okay. I have tried every which way to parse the return data to no avail, including using JSON.parse, data.SuccessMessage, data[0].SuccessMessage, data[0], data.SuccessMessage[0]. Obviously, I'm lost.

jQuery
var Data = new FormData(Form[0]);
$.ajax(
{
   url: 'Ajax-Forms.php',
   type: 'POST',
   data: Data,
   async: false,
   cache: false,
   contentType: false,
   processData: false,
   success: function (data)
   {
      console.log(data); // {"SuccessMessage":"Test Record 03 has been updated","ID":"4884"}
   }
}

Open in new window

PHP
echo json_encode(array("SuccessMessage"=>$SuccessMessage, "ID"=>$ID));

Open in new window

As noted in the comment, the data comes back as
{"SuccessMessage":"Test Record 03 has been updated","ID":"4884"}

Open in new window

So all I need to know is how to parse this return data.
0
Free Tool: SSL Checker
LVL 12
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Hi everyone,

I have a problem. In the database I have a column with a date (varchar (100)
. It is entered in the database as yyyy-mm-dd. the name of the field is "pickupdate". I want to show them on a php page as: dd-mm-yyyy.
But I think I'm doing something wrong because he keeps displaying the date incorrectly.

this is what I had:
-------------------------------------------------- -------------------------------------------
$originalDate = $ _POST ["pickupdate"];
$newDate = date ("d-m-Y", strtotime ($originalDate));



echo 'We have received a pick up order for a '. $ _ POST ["yesno"].' to retrieve on '. $newDate.' <br /> <br />';
-------------------------------------------------- -------------------------------------------------- ------
I hope someone can help
thank you
0
Hi guys. I'm trying to perform a post method action in my php and the site that I post to returns "This site require javascript to be enabled". Now the problem is that this is a backend php script that is sending this post method. The site is http://mlungisi.0fees.us

How can I solve this?
0
I am having a problem while inserting the Date of Birth field's value from html form to mysql datebase using the php. I have used the input type 'date' in html to get the input.
<?php
       $DOB=$_POST['DOB'];
      $DOB = explode("/",$DOB);
      $DOB = "$DOB[2]-$DOB[0]-$DOB[1]";
      $sql = "INSERT INTO signin (F_name,U_name,password,email,DOB,phn)VALUES ('$F_name','$U_name','$password','$email','$DOB','$phn')";
?>
<html
DOB:<input type="date" name="DOB" size="20"><br><br>
/html>

output error:
( ! ) Notice: Undefined offset: 2 in C:\wamp64\www\Blogger\signin.php on line 20
Call Stack
#      Time      Memory      Function      Location
1      0.0004      248128      {main}( )      ...\signin.php:0

( ! ) Notice: Undefined offset: 1 in C:\wamp64\www\Blogger\signin.php on line 20
Call Stack
#      Time      Memory      Function      Location
1      0.0004      248128      {main}( )      ...\signin.php:0
Error: INSERT INTO signin (F_name,U_name,password,email,DOB,phn)VALUES ('kkkk','qqqqq','77777','mmmmmmmmm','/2017-03-24/','10000000')
Incorrect date value: '/2017-03-24/' for column 'DOB' at row 1
0
I want to display information of employee as per selected category. (also calculate no employees of that category).

At a time only one category will be selected from dropdown list .on selecting category , the corresponding categoryid will be recieved.
On the basis of that categoryid  i want to count no of empl0yees and fetch list of employees belong to that selected category only.


Four categories are there
DRDS
DRTC
ADMIN
ALLIED
 there are three tables
Category master (category will be selected from here) [CategoryId]
designationmaster [DesignationId] [Category]
employee master [Designation]

CategoryId = Category
 DesignationId = Designation

CategoryId  of  category master should be matched with Category field of designationmaster.

DesignationId of designationmaster should be matched with Designation field of employeemaster


RESULT OF MY QUERY SHOULD BE NUMBER OF EMPLOYEES CALCULATED FOR SELECTED CATEGORY (category is selected through dropdown list and categoryid is received through post method in next submitted page


Screenshots of tables are attached.emp.PNGdesignation_master.PNGcategory_master.PNG
0
How can I use google sheets to use a web calculator.
Enter Amount, Term, & Interest Rate & return the 2 resulting values given by the calculator into the google sheet
0
Is there a website (or software for windows 10) that lets me know backlinks of another website?

I do not own website so I can not use cpanel reporting tools
0
FORM: 'application.php'
ELEMENT:  a listbox named: 'lstgroup'

when the user select a item, the value (group_id)  is needed in sql WHERE clausule  (application.php)
variable 'group_id' is send with AJAX to application.php

-Function postgroupid() works fine
-$AJAX works fine
-Call php function sendgroupid() works fine

But the $_POST['group_id'] is empty and echo returns :"Hello php! But no group_id"
I spend a week to find a solution with all kind of suggestions from internet, but nothing helps me
Here is my code:

<script type="text/javascript">

   function postgroupid() {
   
    var x = document.getElementById("lstgroup").selectedIndex;
    var y = document.getElementById("lstgroup").options;
    var group_id = y[x].value;
    document.getElementById("edtgroupid").value=group_id;
       $.ajax({
                    type: "POST",
                    url : 'application.php';
                    data: { 'group_id' : group_id }
                   }).done(function(response){alert('succes');
                  }).fail(function(jqXHR, textStatus, errorThrown){
  alert('FAILED! ERROR: ' + errorThrown);
});
 
var result="<?php sendgroupid();?>";
alert(result);
return false;
  }
 
</script>

Open in new window

<?php
function sendgroupid()
{
if (isset($_POST['group_id']) && !empty($_POST['group_id'])) {
    echo $_POST['group_id'];
  }
   else
   {
   echo 'Hello php! But no group_id';
   }
}
?>

Open in new window

0
Hi Experts,
We have a php app written that posts information to a mysql database. Everything works fine until we try and post more than around 50 records to our mysql db? 50 and less works fine but when we try to start posting 55 or more then it gives an error: Database Exception (#42000). What could be the issue?
0
PHP number format.  A college of mine installed a wholesale plugin on a WooCommerce Site.  This brilliant Plugin over wrote all sales prices in the DB.  If the sale price had no decimal point it got rid of the decimal point.  If the decimal point had two decimal points, it added 2 more zeros onto the sales price.  WooCommerce wants all prices to have two decimal points so show properly.

I am writing a piece of code for my functions.php file to update all sales prices in the DB and make sure they have 2 decimal points.

I have 2 questions;
1. This will out put a number with 2 decimal points, even if there are no decimal points on the number, correct?
$meta_value = number_format( $result->meta_value, 2 );
2. Can you see anything wron with the following code?
</php
global $wpdb;
$postmeta = $wpdb->prefix . "postmeta";
$posts = $wpdb->prefix . "posts";

// 1. First query: Get all prices
$results = $wpdb->get_results( "
    SELECT $postmeta.*
    FROM $postmeta
    INNER JOIN $posts ON $postmeta.post_id = $posts.ID
    WHERE $posts.post_type ='product'
    AND $postmeta.meta_key ='_sale_price'
    AND $postmeta.meta_value != ''
    ORDER BY $postmeta.meta_id ASC
" );

// iterating through each price and update it
foreach($results as $result){
    $meta_id    = $result->meta_id;
    $post_id    = $result->post_id;
    $meta_key   = $result->meta_key;
    $meta_value = number_format( $result->meta_value, 2 );

    // 2. Udating prices query
    $wpdb->query( 

Open in new window

0
Upgrade your Question Security!
LVL 12
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

WordPress, Plug-ins, PHP, HTML, CSS and Angular 4??

I need to create a new UI on a WordPress site and want to use Angular. I am not a PHP developer, but would consider using PHP if it made this UI something I could more easily package into a WordPress plug-in.

I am a bit confused about how PHP fits into the equation.

Also, when I need to supplement this new UI with a back-end, is PHP the technology I use to communicate with the WordPress site?

Please explain my options.

Thanks.
0
I have been struggling with the following code for some time. I get the following eror: {"error":"invalid_request","error_description":"invalid grant type"}.

Some more documentation on the API that I am working on is available here:

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://id.shoeboxed.com/oauth/token",
   CURLOPT_RETURNTRANSFER => true,
  CURLOPT_SSL_VERIFYPEER => false, 
  CURLOPT_POST => 1,  
  CURLOPT_POSTFIELDS => "{\"code\": \"['code']\",\"grant_type\":\"authorization_code\",\"redirect_uri\": \"http://website.com/foursquare2.php\",\"client_id\": \"f8de67be8dc84e449203fcdd4XXXXXXX\",\"client_secret\": \"HS5ZeIVsKW0/qqiO9/XcdeWqnF8vtzQrpY8gcdrxg0BXNZXXXXXXX\"}",
  CURLOPT_HTTPHEADER => array(
    "application/x-www-form-urlencoded" 
  )
));


/*
//Another Attempt at it is below
curl -d code=['code'] \
    -d grant_type=authorization_code \
    --data-urlencode redirect_uri='http://website.com/foursquare2.php' \
    -u f8de67be8dc84e449203fcdd44abad5a:HS5ZXXXXXXX/qqiO9/XcdeWqnF8vtzQrpY8gcdrxg0BXNXXXXXXX \
    -XPOST https://id.shoeboxed.com/oauth/token 
*/


$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

?>

Open in new window

0
Problem installing phpMyAdmin

I am trying to build a LAMP stack for a test server and I am getting these errors

Installed:
  yum-plugin-priorities.noarch 0:1.1.31-42.el7

Complete!
[root@ip-172-31-13-158 httpd]# nano /etc/yum.repos.d/remi.repo
[root@ip-172-31-13-158 httpd]# rpm -iUvh http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm
Retrieving http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm
curl: (22) The requested URL returned error: 404 Not Found
error: skipping http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm - transfer failed
[root@ip-172-31-13-158 httpd]# yum -y update
Loaded plugins: fastestmirror, priorities
Loading mirror speeds from cached hostfile
 * base: mirror.cs.pitt.edu
 * epel: mirror.beyondhosting.net
 * extras: mirror.vtti.vt.edu
 * remi-safe: repo1.ash.innoscale.net
 * updates: mirrors.lga7.us.voxel.net
No packages marked for update
[root@ip-172-31-13-158 httpd]# yum -y install phpmyadmin
Loaded plugins: fastestmirror, priorities
Loading mirror speeds from cached hostfile
 * base: mirror.cs.pitt.edu
 * epel: mirror.beyondhosting.net
 * extras: mirror.vtti.vt.edu
 * remi-safe: repo1.ash.innoscale.net
 * updates: mirrors.lga7.us.voxel.net
Resolving Dependencies
--> Running transaction check
---> Package phpMyAdmin.noarch 0:4.4.15.10-2.el7 will be installed
--> Processing Dependency: php-gd >= 5.3.7 for package: phpMyAdmin-4.4.15.10-2.el7.noarch…
0
I am trying to connect  a PHP 7.2.2 application to a SQL server database, using windows authentication, but am seeing this error

Array ( [0] => Array ( [0] => 28000 [SQLSTATE] => 28000 [1] => 18456 [code] => 18456 [2] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'NT AUTHORITY\IUSR'. [message] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'NT AUTHORITY\IUSR'. ) [1] => Array ( [0] => 28000 [SQLSTATE] => 28000 [1] => 18456 [code] => 18456 [2] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'NT AUTHORITY\IUSR'. [message] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'NT AUTHORITY\IUSR'. ) )

Open in new window


Please advise on what to need to do to resolve the problem.
0
I've got a script that I've been asked to alter by initiating a command line dynamic so as to avoid a situation where things are otherwise timing out.

What's happening is that the user will click a button that's grabbing a series of files and converting them to pdf documents. At the end of the script, it then takes the directory that has all of these new files and zips it up and makes it available to the user as a downloadable entity. It works great right up until the point where you're having to process 600+ docs, now you're looking at 20 minutes plus and it's a mess.

At the risk of providing too much info, here's the "machine" as it exists right now.

User clicks the button and you get "  function init_genPSM($empID_sel=NULL,$hID_sel=NULL,$item_sel=NULL,$cpID_sel=NULL, $orderID=NULL, $quantity=500) {"

That's the method that initiates the merry go round. Here it is in its entirety:

function init_genPSM($empID_sel=NULL,$hID_sel=NULL,$item_sel=NULL,$cpID_sel=NULL, $orderID=NULL, $quantity=500) {
        global $S;
        global $A;
        $R = new xajaxResponse();
        $R->appendResponse(Application::InitializeClass());


        if (strpos($item_sel, 'prime') !== false) {
            //ini_set('max_execution_time', $quantity > 120 ? $quantity : 120);
			//I set the max_execution_time to 500 to accommodate larger files that were showing up as empty zip files because of the system timing out (Bruce Gust 4/20/2018)
			ini_set('max_execution_time', 

Open in new window

0
Dear Experts
$myObj->movie = $name;
$myObj->url = "www.example.net/$name";

$myJSON = json_encode($myObj);

echo $myJSON;

Open in new window

the output is like this

{"movie":"mymovie.mp4","url":"http:\/\/www.example.net'\/mymovie.mp4"}

how can I write it without \ ( backslash ) ?
I want to see the url like this: http://www.example.net/mymovie.mp4
0
how to dynamically select columns in stored procedure

//There are six variables
  • var_order -> toggle between first name and last name first. The columns are generated from php
  • var_limit  -> limit on sql query
  • var_user -> user id
  • var_status -> "active"
  • var_activity -> activity id
  • var_team ->  team id

//var_order is either passed as a string for either p.first_name," ", p.last_name or p.last_name, ", ", p.first_name

DELIMITER $$

CREATE PROCEDURE brings_schedule( IN var_order VARCHAR(255), IN var_limit INT, IN var_user INT, IN var_status VARCHAR(1), IN var_activity INT, IN var_team INT )

BEGIN
	    
	SELECT 
		s.id, s.item, s.description, 
		CONCAT(var_order) AS user, p.id AS userId, p.unique_name,
		r.teamId, 
		q.uniqueName
	FROM brings AS s
	JOIN users AS p ON p.id = s.userId AND p.status != var_user
	JOIN `teams-roster` AS r ON r.teamId = var_team AND r.userId = var_user AND r.status = var_status
	JOIN teams AS q ON q.id = r.teamId
	WHERE s.status = var_startus AND s.teamId = var_team AND s.activityId = var_activity
	GROUP BY s.id
	ORDER by p.first_name
    LIMIT var_limit;

END;

$$

DELIMITER ;

Open in new window

0
Hi,

I want to use php to standard html output from several ppl.

I was thinking of using a class similar to php-html-generator found on git ( https://github.com/Airmanbzh/php-html-generator ). Essentially this class would be slightly modified to create bootstrap 4 elements without having to set attributes continually.

Or is it a better idea to use the built-in domdocument class?

Thanks!
0
i have A PHP Error was encountered
Severity: Warning

Message: mysqli_query() expects at least 2 parameters, 1 given

Filename: models/m_peminjaman.php

Line Number: 7 and 8

This Scipt:
class M_Peminjaman extends CI_Model{
    private $table="transaksi";
   
    function nootomatis(){
        $today=date('Ymd');
        $query=mysqli_query("select max(id_transaksi) from transaksi where id_transaksi like '$today%'");
        $data=mysqli_fetch_array($query);
        $lastNoFaktur=$data['last'];
       
        $lastNoUrut=substr($lastNoFaktur,8,3);
       
        $nextNoUrut=$lastNoUrut+1;
       
        $nextNoTransaksi=$today.sprintf('%03s',$nextNoUrut);
       
        return $nextNoTransaksi;
    }
0
Free Tool: IP Lookup
LVL 12
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Hi everybody.
I'm writing the php backend for an Android native app developed by another team.
They are sending to the server in the http headers the value of user_token but I'm not able to get it. I used getllheaders() functions but it doesn't return it.
I have added to .htaccess following lines:
RewriteEngine on
RewriteRule .? - [E=user_token:%{HTTP:user_token}]

Open in new window

and then tried to find the value in the superglobal $_SERVER. the index is present but it is empty.

I performed several tests using https://www.hurl.it/ but with no success (

I really don't know how to solve this issue: any idea?
Thank you
0
I have a PHP script, signup.php inside this directory: /var/www/html/signup.php
Inside this signup.php file, I have the below lines of code to copy file between sub-directories:
$avatar = "images/avatardefault.png";
        $avatar2 = "var/www/html/user/avatardefault.png";
        if (!copy($avatar, $avatar2)) {
            echo "failed to create avatar.";
        }

Open in new window

But when I run this script, I get an error:
PHP Warning:  copy(var/www/html/user/avatardefault.png): failed to open stream: No such file or directory in /var/www/html/signup.php

Open in new window


Please what could be my mistake?
0
jQuery loop. I wordpress I have a section that I add logos to.  At anytime there can be any number of logos.  Sometimes more, sometimes less.  I have them fading in and it is all hard coded.  I want to make a loop to cut down on the amount of code and also be more efficient with my coding.  Depending upon how many logos there are, my php loop on the front end makes a number  addition to the ID.  So id="customer1" id="customer2", id="customer3', etc...

My jQuery is the following and I would like to turn it into an intuitive loop.  Any suggestions?
<script>
$('#customer1').addClass('visible');
            setTimeout(function () {
                $('#customer2').addClass('visible');
            }, 100);
            setTimeout(function () {
                $('#customer3').addClass('visible');
            }, 200);
            setTimeout(function () {
                $('#customer4').addClass('visible');
            }, 300);
            setTimeout(function () {
                $('#customer5').addClass('visible');
            }, 400);
            setTimeout(function () {
                $('#customer6').addClass('visible');
            }, 600);
etc.....

Open in new window

0
I need help creating traineddata for Tesseract.  We need to train it for Car VINs.  Linux server got it installed on V4 and I creayed a set of 12 pictures to work with.
In the end, it's to be used in PHP on a website. Everything is completed except it's not accurate enough using only english traineddata.

The existing documentation is too confusing for us.  

I am looking for more specific instruction or someone we could hire for a few hours to help on this.

Out traineddata is located in /usr/share/tesseract/tessdata/
0
In symfony 4 i have a form to manage user details.

There is a one-to-many relationship between User class and SecurityGroup class.

In my form i would like to have all SecurityGroup listed with checkboxes.
I've managed to do it, but if i check a checkbox the group is not added to the user after the handle request. (In the request dump i see my 2 checked groups)

Form Field:
->add('SecurityGroups', EntityType::class, [
                'class'     => 'App\Entity\SecurityGroup',
                'choice_label' => 'displayname',
                'query_builder' => function (SecurityGroupRepository $repo) {
                    return $repo->createQueryBuilder('f')
                        ->where('f.id > :id')
                        ->setParameter('id', 1);
                },
                'label'     => 'Member Of?',
                'expanded'  => true,
                'multiple'  => true,
            ])

Open in new window


Controller
public function edit(Request $request, $id)
    {

        $user = new User();

        if ($id == -1) {
            $module_title = 'Create a new User';
        }
        else
        {
            $module_title = 'Edit User';
            $user = $this->getDoctrine()->getRepository("App:User")->find($id);
        }

        $form = $this->createForm("App\Form\UserType", $user);


        $form->handleRequest($request);

        $current_user = $this->getUser();
        dump($request);
        dump($form);

        if ($form->isSubmitted() && $form->isValid())
        {

            $user = $form->getData();
            dump($user);
            
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();
            $this->redirectToRoute('admin_user');
        }



        return $this->render('user/edit.html.twig', ['edit_form' => $form->createView(), 'module_title' => $module_title]);
    }

Open in new window


Dumps
Request {#86 ▼
  +attributes: ParameterBag {#70 ▶}
  +request: ParameterBag {#69 ▼
    #parameters: array:1 [▼
      "user" => array:8 [▼
        "username" => "admin"
        "email" => "email@email.email"
        "password" => ""
        "isActive" => "1"
        "DisplayName" => "admin"
        "SecurityGroups" => array:2 [▼
          0 => "2"
          1 => "4"
        ]
        "save" => ""
        "_token" => "YaqXjd73ZhrX8p1eOiFWZi1JWivaCLKMGZbulTsiRgE"
      ]
    ]
  }

Open in new window

0
Hi,

Php has the datetimezone function. if i was to loop through it. The timezones would be outputted into english

$tzlist = DateTimeZone::listIdentifiers(DateTimeZone::ALL);

foreach($tzlist as $t(
    echo $t."</br>";
}

Open in new window


Is there a way to change the output to french/spanish/german?

Essentially, im worried about localization for countries/states and timezones. Initially, i havent worried about these and just printed these in english.

im curious if i will need to create separate db create a reference to particular countries likely using region/country code and then use that as an index among the db tables

then create multiple country/states/timezones in different languages documents that i would include when needed

or is there a simple way to accomplish this

i would not need to include the countries ./ timezones / state files in every page

Also, timezones should i just rely on the users browsers via js to convert database datetime vars stored in UTC standard into local time? if so then i dont need to worry about the timezones above

any help is greatly appreciated!
0

PHPSponsored by Flatiron School

119K

Solutions

33K

Contributors

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.