Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Hey php goons. I have a weird question. I developed a little search and filter app in nextjs that uses wp graphql to fetch data. It works and all but I kinda want to port it to php so that I can run it directly on the wordpress site it's grabbing from. The problem is I don't know PHPexcept for the real basics. Does PHP lend itself to forms and filtering as "well" as javascript does?

I can't imagine this is something super challenging but I dobt want to get started and then find out it's going to be a lot harder in the language. I guess the only real "catch" I'd that the form has a multiselect that it uses to pick amenities offered by a resort. The fields are all selects otherwise that pull data from custom post types and taxonomies in wordpress Oh and there's a mapbox integration but I think php can support that?

That said if anyone is interested and wants to make a couple hundred and port it for me I'd be up for that too :D. I don't have pm but I am reachable via email at tomisthebest@gmail.com

Thanks goons

Adbot
ADBOT LOVES YOU

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
I have a quick question :). How come this top statement works and shows the image, yet the bottom one doesn't?

Inside PHP:
code:
echo '<img src="' . $featured_img_url . '" alt="' . the_title() . '"/>';
Outside PHP:
code:
<img src="<?php esc_url($featured_img_url) ?>" alt="<?php the_title() ?>"/>
This is using WordPress. I've run into the inverse also, where something like:

code:
echo '<a href="'.the_permalink() . '" title="' . the_title() . '">' . the_title() . '</a>';
doesn't work but this does:

code:
<a href="<?php the_permalink() ?>" title="<?php the_title() ?>"><?php the_title(); ?></a>

Impotence
Nov 8, 2010
Lipstick Apathy


sorry, cloudflare captcha loop hell when posting code

you are not actually printing anything

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Huh that would do it. Thanks for the help.

Tei
Feb 19, 2011

Empress Brosephine posted:

I have a quick question :). How come this top statement works and shows the image, yet the bottom one doesn't?

Inside PHP:
code:
echo '<img src="' . $featured_img_url . '" alt="' . the_title() . '"/>';
Outside PHP:
code:
<img src="<?php esc_url($featured_img_url) ?>" alt="<?php the_title() ?>"/>
This is using WordPress. I've run into the inverse also, where something like:

code:
echo '<a href="'.the_permalink() . '" title="' . the_title() . '">' . the_title() . '</a>';
doesn't work but this does:

code:
<a href="<?php the_permalink() ?>" title="<?php the_title() ?>"><?php the_title(); ?></a>

do the_title() escape for html ?, because mixing html with php withouth escaping properly text will lead to broken html

use a template engine

Impotence
Nov 8, 2010
Lipstick Apathy

Tei posted:

do the_title() escape for html ?, because mixing html with php withouth escaping properly text will lead to broken html

use a template engine

this basically wordperss template

Tei
Feb 19, 2011

Biowarfare posted:

this basically wordperss template

yes?, ok them... I imagine wordpress would default to escape everything that need escaping

Impotence
Nov 8, 2010
Lipstick Apathy

Tei posted:

yes?, ok them... I imagine wordpress would default to escape everything that need escaping

is not escaped but is also only your registered editors can write title

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
i've been escaping things anyways since yeah i'm a bit paranoid about sql injects and such.

i've been using more and more of PHP and its quite a interesting language. I don't think i'll ever commit to it fully, but there is something kinda...charming? about being able to write HTML directly within the code. I know this is possible with React and such, but it seems way more straight foward with PHP

Tei
Feb 19, 2011

Empress Brosephine posted:

i've been escaping things anyways since yeah i'm a bit paranoid about sql injects and such.

i've been using more and more of PHP and its quite a interesting language. I don't think i'll ever commit to it fully, but there is something kinda...charming? about being able to write HTML directly within the code. I know this is possible with React and such, but it seems way more straight foward with PHP

The best and worst thing about PHP is that is usefull even if you learn only 1%. Maybe a bit less great these days with things like wordpress.

Is the worst because you can easily fall into a trap. Like no escaping html, or mixing PHP and html... actually is kind of okay to mix PHP and HTML if you treat that file like a template. Like you have a template "people.template.php" where you use PHP like a templating engine.
But if you write all your code like that, you will live in some hell where the result will not be very good or easy to fix bugs or easy to change.

Tei fucked around with this message at 18:07 on May 9, 2021

handle
Jan 20, 2011

Bob Morales posted:

What are some common ways to refactor poo poo like this? Imagine functions.php with 500 functions just like this

PHP code:
function IsActiveEmp($EmpID) {
  $link=mysqli_connect("database","user","password") or die(mysqli_error());
  $db=mysqli_select_db("erp",$link) or die(mysqli_error());
  $query="SELECT Serial FROM TbfEmployee WHERE EmpID=".$EmpID." AND Active<>0;";
  $result=mysqli_query($query,$link) or die(mysqli_error());
  if(mysqli_num_rows($result)>0) {
    return true;
  } else {
    return false;
  }
}

rt4 posted:

Create an Employee class with an isActive() method that gets populated from the start when you load it from an EmployeeStorage interface via the GetById(int) method. You'll implement this interface several times over with a SQL version sitting at the bottom, then several decorators on top to handle things like validation and caching.

Or at least that's how I build business software.
Necroposting because I'm in the same situation and would love further details to understand this. Is there an article/example code that could help me visualize the latter? I'm almost comfortable reading basic OOP code at this point but haven't ever designed anything with it, and I don't think I can trust my gut to make the right design pattern-y choices yet.

Tei
Feb 19, 2011

handle posted:

Necroposting because I'm in the same situation and would love further details to understand this. Is there an article/example code that could help me visualize the latter? I'm almost comfortable reading basic OOP code at this point but haven't ever designed anything with it, and I don't think I can trust my gut to make the right design pattern-y choices yet.

I am phone posting, so I cant write code, bit a easy way to do this is to create wrappers.
You dont need connect on each method. the wrapper could create the connection if not connection exist.

this is very easy to do, just search and replace , deleting the connection lines that are not needed
anymore

the result will be much more readable.

anyway this code is not just old, is from 7 geological eras, maybe
make sense to do a full rewrite to laravel
PHP code:
function IsActiveEmp($EmpID) {
  $link=mysqli_connect("database","user","password") or die(mysqli_error());
  $db=mysqli_select_db("erp",$link) or die(mysqli_error());
  $query="SELECT Serial FROM TbfEmployee WHERE EmpID=".$EmpID." AND Active<>0;";
  $result=mysqli_query($query,$link) or die(mysqli_error());
  if(mysqli_num_rows($result)>0) {
    return true;
  } else {
    return false;
  }
}

function IsActiveEmp($EmpID){
$sql = query_escape(“selectc yada yada =%d”,$EmpID);
$res = query($sql);
return ( query_count($res)>0);
}

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


The way we did this during the transition from old PHP to modern PHP is extended the PDO object and added a factory method. That way in the files that were manually connecting to the database, we could replace it with a call to that. We also added some methods that do a prepare & execute together so we could upgrade those files to use parameter binding without having to change too much.
This was just to solve immediate SQL issues while working on the rewrite a proper framework so there might be better options, but this worked for us.


PHP code:
class WPDO extends \PDO
{
    public static $db;
    final public static function factory()
    {
        if (!(static::$db instanceof static)) {
            static::$db = new static("dsn goes here");
        }
        return static::$db;
    }

    public function getRow(string $sql, array $params = null)
    {
        if (!is_array($params)) {
            $sth = $this->query($sql);
            if ($sth === false) {
                return null;
            }
        } else {
            $sth = $this->prepare($sql);
            if (empty($sth)) {
                return null;
            }
            $r = $sth->execute($params);
            if ($r === false) {
                return null;
            }
        }

        $result = $sth->fetch(\PDO::FETCH_OBJ);

        if ($result === false) {
            return null;
        }

        return $result;
    }
}

function IsActiveEmp(int $EmpID): bool
{
    $db = WPDO::factory();
    $active = $db->getRow("SELECT Serial FROM TbfEmployee WHERE EmpID = :empid AND Active <> 0", [":empid" => $EmpID]);
    return !empty($active);
}

Tei
Feb 19, 2011

I like duz solution

handle
Jan 20, 2011

Thank you both! An immediate solution is great, this application just needs triage until it can be replaced in a few months.

Jeffrey of YOSPOS
Dec 22, 2005

GET LOSE, YOU CAN'T COMPARE WITH MY POWERS
Lol I am personally sorry to this thread that [php] tags look bad in dark mode. I did work to make dark mode play nice with [code] tags but [php] tags use a completely different mechanism that is harder to change dynamically. I'm working on it and this is very silly.

nielsm
Jun 1, 2009



Jeffrey of YOSPOS posted:

Lol I am personally sorry to this thread that [php] tags look bad in dark mode. I did work to make dark mode play nice with [code] tags but [php] tags use a completely different mechanism that is harder to change dynamically. I'm working on it and this is very silly.

Can the [php] tags simply be translated to [code=php] instead?

Jeffrey of YOSPOS
Dec 22, 2005

GET LOSE, YOU CAN'T COMPARE WITH MY POWERS

nielsm posted:

Can the [php] tags simply be translated to [code=php] instead?
They certainly can but they don't look as nice as the current php tags in light mode. I can let the light mode users in this thread decide if that's acceptable.

Jeffrey of YOSPOS
Dec 22, 2005

GET LOSE, YOU CAN'T COMPARE WITH MY POWERS
Here's an example from the post above for comparison:

PHP tag:
php:
<?
class WPDO extends \PDO
{
    public static $db;
    final public static function factory()
    {
        if (!(static::$db instanceof static)) {
            static::$db = new static("dsn goes here");
        }
        return static::$db;
    }

    public function getRow(string $sql, array $params = null)
    {
        if (!is_array($params)) {
            $sth = $this->query($sql);
            if ($sth === false) {
                return null;
            }
        } else {
            $sth = $this->prepare($sql);
            if (empty($sth)) {
                return null;
            }
            $r = $sth->execute($params);
            if ($r === false) {
                return null;
            }
        }

        $result = $sth->fetch(\PDO::FETCH_OBJ);

        if ($result === false) {
            return null;
        }

        return $result;
    }
}

function IsActiveEmp(int $EmpID): bool
{
    $db = WPDO::factory();
    $active = $db->getRow("SELECT Serial FROM TbfEmployee WHERE EmpID = :empid AND Active <> 0", [":empid" => $EmpID]);
    return !empty($active);
}
?>
code=php tag:
PHP code:
class WPDO extends \PDO
{
    public static $db;
    final public static function factory()
    {
        if (!(static::$db instanceof static)) {
            static::$db = new static("dsn goes here");
        }
        return static::$db;
    }

    public function getRow(string $sql, array $params = null)
    {
        if (!is_array($params)) {
            $sth = $this->query($sql);
            if ($sth === false) {
                return null;
            }
        } else {
            $sth = $this->prepare($sql);
            if (empty($sth)) {
                return null;
            }
            $r = $sth->execute($params);
            if ($r === false) {
                return null;
            }
        }

        $result = $sth->fetch(\PDO::FETCH_OBJ);

        if ($result === false) {
            return null;
        }

        return $result;
    }
}

function IsActiveEmp(int $EmpID): bool
{
    $db = WPDO::factory();
    $active = $db->getRow("SELECT Serial FROM TbfEmployee WHERE EmpID = :empid AND Active <> 0", [":empid" => $EmpID]);
    return !empty($active);
}

ModeSix
Mar 14, 2009

Jeffrey of YOSPOS posted:

Here's an example from the post above for comparison:

.......


I checked this in both light and dark mode and I don't think the code=php tag is a good solution for PHP code.

It reaches mostly acceptable levels on light mode, but downright bad on dark mode.

Tei
Feb 19, 2011

Jeffrey of YOSPOS posted:

Lol I am personally sorry to this thread that [php] tags look bad in dark mode. I did work to make dark mode play nice with [code] tags but [php] tags use a completely different mechanism that is harder to change dynamically. I'm working on it and this is very silly.

is a popular feature? I rarelly see any traffic in this thread,
people bring their php problems elsewhere

I like how the code=php look in dark mode

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Jeffrey if you post jQuery in a code tag the site bans you lol

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Empress Brosephine posted:

Jeffrey if you post jQuery in a code tag the site bans you lol

good it should also call the police and add your name to the sex offender registry.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
I agree jQuery sucks

Tei
Feb 19, 2011

Empress Brosephine posted:

I agree jQuery sucks

Nah, we are moving to better things, but is still a tool that get the job done.

Whats next? C being obsolete?

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Tei posted:

Nah, we are moving to better things, but is still a tool that get the job done.

Whats next? C being obsolete?

jquery is actually worse than using nothing for the majority of its use cases.

Jeffrey of YOSPOS
Dec 22, 2005

GET LOSE, YOU CAN'T COMPARE WITH MY POWERS

Empress Brosephine posted:

Jeffrey if you post jQuery in a code tag the site bans you lol
Lol good

Tei
Feb 19, 2011

Bruegels Fuckbooks posted:

jquery is actually worse than using nothing for the majority of its use cases.

I have seen this opinion before, but it always leave me unimpressed.

You could do this 1 line of jquery with this 1.5 lines of vanilla.
when people make these type comments (with artificial code, not real
world code) the jquery version looks better to me

Impotence
Nov 8, 2010
Lipstick Apathy

Tei posted:

I have seen this opinion before, but it always leave me unimpressed.

You could do this 1 line of jquery with this 1.5 lines of vanilla.
when people make these type comments (with artificial code, not real
world code) the jquery version looks better to me

I'm a super jquery lover and php user but honestly, these days, 99% of it is really just doable without jquery. If you're lazy, const $$$ = document.querySelectorAll and it looks better

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Tei posted:

I have seen this opinion before, but it always leave me unimpressed.

You could do this 1 line of jquery with this 1.5 lines of vanilla.
when people make these type comments (with artificial code, not real
world code) the jquery version looks better to me

the big reason i don't gently caress with jquery anymore is the performance/memory use. the library has huge overhead - e.g. for the event listeners, in order for that poo poo to work, it has to cache all the dom references internally etc (so if an element has an event handler reference, it will never garbage collect etc) and it also has to normalize all the events to a "standard" form internally. Profiling it, I've seen mousemove listeners use 50% of the CPU, spending most of it in event normalization - and it's not even that good at normalizing events because poo poo like the mousewheel will still behave differently in all the different browsers. The jquery selectors and the sizzle library are insane bullshit and are also slow.

let's consider other reasons you might use jquery - perhaps you want to use jquery promises? oh wait, they differ from A+ promises in some subtle way that you will have to read a bunch of blog articles to understand.

this isn't a bandwagon hatred - including jquery in poo poo when it wasn't needed has wasted months of my life. it seems like a huge pain in the rear end to learn an additional api that will just end up loving you if your product reaches any level of complexity (the jquerylite poo poo was one of the reasons they had to throw out angular1 for instance.)

Impotence
Nov 8, 2010
Lipstick Apathy
if it makes you feel better;
jq3 checks for queryselector/queryselectorall natively and uses that
jq4 is dropping sizzle

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
I got a little closer in my issue but still stuck. If anyone has any tips I'd love it.

https://stackoverflow.com/questions/67696512/wordpress-user-query-by-acf-custom-fields

Empress Brosephine fucked around with this message at 01:17 on May 26, 2021

handle
Jan 20, 2011

3rd edit: OK, maybe I understand enough now to try part 2 again. (Caveat: I've never worked with Wordpress.)

I'm guessing that you're using the Checkbox ACF field type for artist mediums/locations? ACF saves checkbox values as serialized arrays, and I found this article helpful to visualize why that creates problems with querying.

Since checkbox fields need to be queried using LIKE, searching for multiple selections in a checkbox should be doable by chaining single-term LIKE criteria with AND/OR. (i.e. wrapping individual key/value/compare arrays inside an array with the right relation set on the wrapper.)

I took a whack at a function that'll generate a chaining structure that WP_USER_QUERY should be able to parse, for whatever fields you want to multi-filter on, using similar syntax. Lemme know if it works! I unfortunately have no Wordpress install to test against.
PHP code:
$mediums = array('Wood', 'Paint');
$locations = array('Paris', 'London');

$args = array(
    'role' => 'artist',
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'meta_query' => build_WP_Meta_Query_for_ACF_Checkbox(array(
        'relation' => 'AND',
        array(
            'artist_medium' => $mediums,
            'relation' => 'OR'
        ),
        array(
            'studio_region_location' => $locations,
            'relation' => 'OR'
        )
    ))
);
$user_query = new WP_USER_QUERY($args);

// TODO: appropriate error-handling! NO WARRANTY EXPRESSED OR IMPLIED, etc.
function build_WP_Meta_Query_for_ACF_Checkbox($criteria) {
    $result = array();
    // default relation should be 'AND', same as WP_Meta_Query.
    $result['relation'] = (isset($criteria['relation']) && strtoupper($criteria['relation']) === 'OR' ? 'OR' : 'AND');

    foreach ($criteria as $key => $value) {
        if (is_array($value)) {
            // "root" items have no named key, but are just array() wrappers for sub-query parts.
            if (!is_string($key)) {
                $sub_query = build_WP_Meta_Query_for_ACF_Checkbox($value);
                if (count($sub_query) > 0) {
                    $result[] = $sub_query;
                }
            } elseif (count($value) > 0) {
                // build up WP_Meta_Query args.
                foreach ($value as $val) {
                    $result[] = array(
                       'key' => $key,
                       // since the LIKE clause is querying a serialized array, we should
                       // enclose the search value in double quotes (at minimum.)
                       'value'=> '"' . $val . '"',
                       'compare' => 'LIKE'
                    );
                }
            }
        }
    }

    // our values for count() reflect that $result['relation'] is always set.
    if (count($result) <= 1) {
        // a checkbox field name was given, but had no search values.
        $result = array();
    } elseif (count($result) === 2) {
        // a checkbox field was provided with only one search value, and a relation is unnecessary.
        $result = $result[0];
    }
    return $result;
}

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Holy cow you rule. I didn't check it 1:1 BUT that has exactly what the solution was; Wordpress can't use "IN", you have to keep adding the search parameters to the meta_query array via a for loop.

Thanks so much :D

handle
Jan 20, 2011

Glad it helped! Did you ever figure out part one? I couldn't tell if that was an artifact of problems with part two, or something separate.

edit: btw, if you're still looking for help on the port, I sent you an email.

handle fucked around with this message at 18:19 on May 26, 2021

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Replied back to your e-mail!

What I ended up doing was this:

PHP code:
  if (isset($_POST['mediumType']) && isset($_POST['locationType'])) {
        $meta_query = array(
            'relation' => 'AND',
            array('relation' => 'OR')
        );

        foreach ($_POST['mediumType'] as $val){
            $meta_query[0][] = array(
                'key' => 'artist_medium',
                'value'=> $val,
                'compare' =>'LIKE'
            );
        }

        foreach ($_POST['locationType'] as $loc){
            $meta_query[] = array(
                'key' => 'studio_region_location',
                'value'=> $loc,
                'compare' =>'LIKE'
            );
        }

        
        $args = array(
            'role' => 'artist',
            'orderby' => 'meta_value',
            'order' => 'ASC',
            'meta_query' => $meta_query,
        );

        $user_query = new WP_USER_QUERY($args);
        
Which seems so obvious in retrospect but I wasted all day yesterday unpaid trying to solve it rip.

astral
Apr 26, 2004

ModeSix posted:

I checked this in both light and dark mode and I don't think the code=php tag is a good solution for PHP code.

It reaches mostly acceptable levels on light mode, but downright bad on dark mode.

How is the code=php tag now? Thanks to some good feedback in the technical forum, the code highlighting system has been updated. Additional code highlighting improvements will be forthcoming.

ModeSix
Mar 14, 2009

astral posted:

How about now? Thanks to some good feedback in the technical forum, the code highlighting system has been updated. Additional code highlighting improvements will be forthcoming.

The blue on blue is still... difficult to read.

This is using the PHP tag.


It's like there's a smurf hiding in a blueberry patch. :v:

On the code=php tag it's super easy to read.

You can check this post as a reference: https://forums.somethingawful.com/showthread.php?noseen=1&threadid=2802621&pagenumber=219&perpage=40#post514831916

ModeSix fucked around with this message at 02:47 on Jul 2, 2021

astral
Apr 26, 2004

ModeSix posted:

The blue on blue is still... difficult to read.

This is using the PHP tag.


It's like there's a smurf hiding in a blueberry patch. :v:moz-extension://7515d330-bff0-465d-ac48-15c628eba573/images/quick-reply-close.gif

On the code=php tag it's super easy to read.

You can check this post as a reference: https://forums.somethingawful.com/showthread.php?noseen=1&threadid=2802621&pagenumber=219&perpage=40#post514831916

Nothing changed about the [php] tag; that's its own thing. I'm talking about the [code=] tags which were being discussed as a possible replacement for the [php] tag. I'll edit my previous post to be more specific. Sorry about that.

e: glad to hear the new code=php tag highlighting is looking good to other people, though :shobon:

Adbot
ADBOT LOVES YOU

Agrikk
Oct 17, 2003

Take care with that! We have not fully ascertained its function, and the ticking is accelerating.
I am messing around with the new graviton2-based instances on EC2 (64-bit Arm Neoverse) and decided to bring some code over from Windows/IIS/PHP7.4 to Ubuntu 20LTS/Apache2/PHP7.4 and immediately ran into a problem when I attempt to connect ot a SQL Server database:

Running this simple database connection code:

code:
<?php
$serverName='xxxxxxx, 1433';

$connectionInfo = array( "Database"=>"xxxxxxx", 
						 "UID"=>"xxxxxxx", 
						 "PWD"=>"xxxxxxx",
						 "ConnectionPooling"=>0);
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}

?>
it fails with

quote:

Fatal error: Unknown processor architecture. in /var/www/html/config.php on line 9

Google directs me to a bunch of posts about Apple M1 chips but I feel like I'm in the weeds here.

Any ideas?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply