/    Sign up×
Community /Pin to ProfileBookmark

Is My http_build_query() Useage Fine Or Not ?

Programmers,

Do you think I used the http_build_query() and the ternary correctly or not ?
Any bad or wrong coding on this pagination script below ?

It gets it’s values from $_GET. Will add html form and $_POST stuffs later. Let’s get the basics of http_build_query () out of the way first. Shall we ? πŸ˜‰

NOTE:
I did not use mysqli_stmt_num_rows() or mysqli_num_rows() on this one as will use on another project/s.
Here, I used the Sql COUNT to count the matching rows found. I did that, to make use of the mysqli_stmt_bind_result().

Not into pdo yet.

[code]
//SQL COUNT.
//mysqli_stmt_bind_result();
//mysqli_stmt_get_result();
//http_build_query()

//Report Error.
ini_set(‘display_errors’,1);
ini_set(‘display_startup_errors’,1);
error_reporting(E_ALL);

//Valid $_GET Items.
$tables = array(‘admin’,’admin_settings’,’links’,’taggings’,’affiliates’,’affiliates_settings’,’partners’,’partners_settings’,’sponsors’,’sponsors_settings’,’advertisers’,’advertisers_settings’,’members’,’members_settings’,’searchers’,’searchers_settings’,’users’,’users_settings’);
$links_table_columns = array(‘id’,’date_and_time’,’domain’,’domain_email’,’word’,’phrase’);

//Extract $_GETs.
$tbl = ISSET($_GET[‘tbl’])?strtolower($_GET[‘tbl’]):die(‘Insert Table!’);
$input_1 = !EMPTY($_GET[‘input_1’])?strtolower($_GET[‘input_1’]):die(‘Make your input for us to search!’);
$input_2 = !EMPTY($_GET[‘input_2’])?strtolower($_GET[‘input_2’]):null;
$col_1 = !EMPTY($_GET[‘col_1’])?strtolower($_GET[‘col_1’]):die(‘Input MySql Column to search!’);
$col_2 = !EMPTY($_GET[‘col_2’])?strtolower($_GET[‘col_2’]):null;
$bool = !EMPTY($_GET[‘bool’])?strtolower($_GET[‘bool’]):null;
$page = !EMPTY($_GET[‘pg’])?intval($_GET[‘pg’]):1;
$limit = !EMPTY($_GET[‘lmt’])?intval($_GET[‘lmt’]):1;
$offset = ($page*$limit)-$limit;

if(ISSET($col_2))
{
if(!in_array($col_2,$links_table_columns))
{
die(‘Invalid Mysql Table!’);
}
}

if(!in_array($col_1,$links_table_columns))
{
die(‘Invalid Mysql Table!’);
}

//Query DB.
$conn = mysqli_connect(“localhost”,”root”,””,”gulf”); //mysqli_connect(“server”,”user”,”password”,”db”);

$stmt = mysqli_stmt_init($conn);

if($bool==’and’)
{
$input_1 = $_GET[‘input_1’];
$input_2 = $_GET[‘input_2′];
$sql_count = “SELECT COUNT(id) from $tbl WHERE $col_1 = ? AND $col_2 = ?”;
$sql = “SELECT id,domain,word,phrase from $tbl WHERE $col_1 = ? AND $col_2 = ? LIMIT $limit OFFSET $offset”;
}
elseif($bool==’or’)
{
$input_1 = $_GET[‘input_1’];
$input_2 = $_GET[‘input_2′];
$sql_count = “SELECT COUNT(id) from $tbl WHERE $col_1 = ? OR $col_2 = ?”;
$sql = “SELECT id,domain,word,phrase from $tbl WHERE $col_1 = ? AND $col_2 = ? LIMIT $limit OFFSET $offset”;
}
else//if($bool==’null’),if(!ISSET($bool)
{
$input_1 = $_GET[‘input_1’];
$sql_count = “SELECT COUNT(id) from $tbl WHERE $col_1 = ?”;
$sql = “SELECT id,domain,word,phrase from $tbl WHERE $col_1 = ? LIMIT $limit OFFSET $offset”;
}

if(!mysqli_stmt_prepare($stmt,$sql_count))
{
echo ‘Mysqli Error: ‘ .mysqli_stmt_error($stmt);
echo ‘<br>’;
echo ‘Mysqli Error No: ‘ .mysqli_stmt_errno($stmt);
}
else
{
if($bool==’and’ || $bool==’or’)
{
mysqli_stmt_bind_param($stmt,”ss”,$input_1,$input_2);
}
else
{
mysqli_stmt_bind_param($stmt,”s”,$input_1);
}

mysqli_stmt_execute($stmt);
$result = mysqli_stmt_bind_result($stmt,$rows_count);
mysqli_stmt_fetch($stmt);

echo ‘Total Result: ‘ .$rows_count; echo ‘<br><br>’;
}

if(!mysqli_stmt_prepare($stmt,$sql))
{
echo ‘Mysqli Error: ‘ .mysqli_stmt_error($stmt);
echo ‘<br>’;
echo ‘Mysqli Error No: ‘ .mysqli_stmt_errno($stmt);
}
else
{
if($bool==’and’ || $bool==’or’)
{
mysqli_stmt_bind_param($stmt,”ss”,$input_1,$input_2);
}
else
{
mysqli_stmt_bind_param($stmt,”s”,$input_1);
}

mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

while($row = mysqli_fetch_array($result))
{
$id = $row[‘id’];
$domain = $row[‘domain’];
$word = $row[‘word’];
$phrase = $row[‘phrase’];

echo “$id<br>”;
echo “$domain<br>”;
echo “$word<br>”;
echo “$phrase<br>”;
echo “<br>”;
}
}

mysqli_stmt_close($stmt);
mysqli_close($conn);

echo ‘Total Pages: ‘ .$total_pages = ceil($rows_count/$limit);
echo ‘<br><br>’;

$i = 0;
while($i<$total_pages)
{
$i++;
if($_GET[‘bool’]==’null’)
{
$array = array(“tbl”=>”$tbl”,”col_1″=>”$col_1″,”bool”=>”$bool”,”input_1″=>”$input_1″,”pg”=>”$i”);

$serps_url = $_SERVER[‘PHP_SELF’].’?’.http_build_query($array);
echo “<a href=”$serps_url”>$i</a>”;
}
else
{
$array = array(“tbl”=>”$tbl”,”col_1″=>”$col_1″,”col_2″=>”$col_2″,”bool”=>”$bool”,”input_1″=>”$input_1″,”input_2″=>”$input_2″,”pg”=>”$i”);

$serps_url = $_SERVER[‘PHP_SELF’].’?’.http_build_query($array);
echo “<a href=”$serps_url”>$i</a>”;
}
}

echo ‘<br>’;

[/code]

A typical pagination url look like these:

https://localhost/Work/gulp/Templates/Pagination_Template_3.php?tbl=links&col_1=word&input_1=keyword&lmt=2&pg=1

https://localhost/Work/gulp/Templates/Pagination_Template_3.php?tbl=links&col_1=word&col_2=phrase&bool=or&input_1=keyword&input_2=keyphrase&lmt=2&pg=1

I do not why the forum messes up my line alignments here. Looks fine on NotePad++.

to post a comment
PHP

13 Comments(s) ↴

Copy linkTweet thisAlerts:
@NogDogAug 03.2022 β€”Β > Is My http_build_query() Useage Fine Or Not ?

Why all that code to answer that question? (And no, I'm not going to read all of that and do a code review for you -- at least not for free.)
Copy linkTweet thisAlerts:
@SempervivumAug 03.2022 β€”Β I didn't review you code completely but focused on http_build_query. Seems to be fine, you are preparing an ass. array and hand it over to that function. Note that the main benefit of this function is: It prepares the query string completely, including correct encoding of special characters. No need to deal with functions like urlencode.
Copy linkTweet thisAlerts:
@novice2022authorAug 03.2022 β€”Β @Sempervivum#1645620

Yes. That is what I was told.

Originally, I had the pagination section, like this:
<i>
</i>$i = 0;
while($i&lt;$total_pages)
{
$i++;
if($bool=='and' || $bool=='or')
{
$serps_url = $_SERVER['PHP_SELF'].'?'.'tbl='.urlencode($tbl).'&amp;'.'col_1='.urlencode($col_1).'&amp;'.'col_2='.urlencode($col_2).'&amp;'.'bool='.$bool.'&amp;'.'input_1='.urlencode($input_1).'&amp;'.'input_2='.urlencode($input_2).'&amp;'.'lmt='.intval($limit).'&amp;'.'pg='.intval($i);
echo '&lt;a href="' .htmlspecialchars($serps_url) .'"&gt;' .$i .'&lt;/a&gt;';
}
else
{
$serps_url = $_SERVER['PHP_SELF'].'?'.'tbl='.urlencode($tbl).'&amp;'.'col_1='.urlencode($col_1).'&amp;'.'bool='.urlencode($bool).'&amp;'.'input_1='.urlencode($input_1).'&amp;'.'lmt='.intval($limit).'&amp;'.'pg='.intval($i);
echo '&lt;a href="' .htmlspecialchars($serps_url) .'"&gt;' .$i .'&lt;/a&gt;';
}
}


Then, at stackexchange, someone refered me to http_build_query() a year ago. I learnt it. But did not use it for many months and have forgotten how to use it. And so came here.

I was about to ask you what you meant by "ass" as I missed the dot. Now I understand.

Anyway, do you see anything wrong with the above code that makes no use of http_build_query() ?

Remember, the $_GET values in the urls would be user input values. Need to secure user inputs so no sql injection or any other funny business. hence, I showed my full code in my op. To see if anyone can spot any serious mistake on my part.

Thanks anyway.
Copy linkTweet thisAlerts:
@novice2022authorAug 03.2022 β€”Β @NogDog#1645617

Let us go backwards then before http_build_query() as I already got green light from Semprevivum that my http_build_query() is ok.

Do you see the code on my previous post, just above this one ?

Is it ok or I messed a thing or two out ?

Not sure if I showed use int() or intval() there.

Cheers!
Copy linkTweet thisAlerts:
@novice2022authorAug 03.2022 β€”Β One thing I learnt today, you can use mysqli_stmt_affected_rows() instead of mysqli_stmt_num_rows(). But both these functions has to be used after the mysqli_stmt_store_result() function, if the SQL query is a SELECT query. A lot of puzzle got solved tonight. ;)

Learnt now about mysqli_stmt_free_result() as had a few questions on it.
Copy linkTweet thisAlerts:
@novice2022authorAug 03.2022 β€”Β @ginerjm

Anything wrong with my ternary ?
<i>
</i>//Extract $_GETs.
$tbl = ISSET($_GET['tbl'])?strtolower($_GET['tbl']):die('Insert Table!');
$input_1 = !EMPTY($_GET['input_1'])?strtolower($_GET['input_1']):die('Make your input for us to search!');
$input_2 = !EMPTY($_GET['input_2'])?strtolower($_GET['input_2']):null;
$col_1 = !EMPTY($_GET['col_1'])?strtolower($_GET['col_1']):die('Input MySql Column to search!');
$col_2 = !EMPTY($_GET['col_2'])?strtolower($_GET['col_2']):null;
$bool = !EMPTY($_GET['bool'])?strtolower($_GET['bool']):null;
$page = !EMPTY($_GET['pg'])?intval($_GET['pg']):1;
$limit = !EMPTY($_GET['lmt'])?intval($_GET['lmt']):1;
$offset = ($page*$limit)-$limit;


Or, everything ok ?

You think you can better it ?
Copy linkTweet thisAlerts:
@novice2022authorAug 09.2022 β€”Β Hi,

Anything wrong with my ternaries below ? Acts ok to me, so far. But what is your feed-back.
<i>
</i>//Extract $_GETs.
$tbl = ISSET($_GET['tbl'])?strtolower($_GET['tbl']):die('Insert Table!');
$input_1 = !EMPTY($_GET['input_1'])?strtolower($_GET['input_1']):die('Make your input for us to search!');
$input_2 = !EMPTY($_GET['input_2'])?strtolower($_GET['input_2']):null;
$col_1 = !EMPTY($_GET['col_1'])?strtolower($_GET['col_1']):die('Input MySql Column to search!');
$col_2 = !EMPTY($_GET['col_2'])?strtolower($_GET['col_2']):null;
$bool = !EMPTY($_GET['bool'])?strtolower($_GET['bool']):null;
$page = !EMPTY($_GET['pg'])?intval($_GET['pg']):1;
$limit = !EMPTY($_GET['lmt'])?intval($_GET['lmt']):1;
$offset = ($page*$limit)-$limit;


Anyway, to better them ?
Copy linkTweet thisAlerts:
@NogDogAug 09.2022 β€”Β > @novice2022#1645712 Anything wrong with my ternaries below

tl;dr: I would never use that for form validation. It's hard to read/maintain, provides a lousy user experience, and is very non-DRY (Don't Repeat Yourself). Anyway...

The ternary operators should "work", but...
  • * Why isset() for the table name but !empty() for everything else?
  • * And why do you use all-caps for those functions? (It still works, but nobody I know does that 🤷 )

  • * : die("some message") is a pretty horrible way to report an input error. (The user then has to figure out how to navigate back to the form page, where they'll have to re-enter everything again.)

  • * I'm just guessing you have nothing in place to prevent SQL injection attacks on the table and column names?


  • ``text<i>
    </i> +----------------------------------------------+
    Table Name: | users where exists(truncate table users); -- |
    +----------------------------------------------+<i>
    </i>
    ``

    https://imgs.xkcd.com/comics/exploits_of_a_mom.png
    Copy linkTweet thisAlerts:
    @novice2022authorAug 09.2022 β€”Β @NogDog#1645717

    Thanks.

    How did you draw that cartoon and how long it took ?

    Ok. Let's see you sanitize this then ....
    <i>
    </i>$tbl = !EMPTY($_GET['tbl'])?strtolower($_GET['tbl']):die('Insert Table!');


    Forget the die() alerts as this is DEV mode. In PRO mode user won;t see such mssges but user friendly mssges. Do not worry. I was just trying to learn how to give alerts if TERNARY was triggering ELSE. That's all. Learning the basics of ternary.

    I was doing it like this ....
    <i>
    </i>$tables = array('admin','users','members');
    $links_table_columns = array('id','date_and_time','domain','domain_email','word','phrase');

    if(ISSET($col_2))
    {
    if(!in_array($col_2,$links_table_columns))
    {
    die('Invalid Mysql Table!');
    }
    }

    if(!in_array($col_1,$links_table_columns))
    {
    die('Invalid Mysql Table!');
    }


    Again, this is DEV mode.

    Reason why the $_GET['tbl'] is getting checked with ISSET and not getting checked with EMPTY is because if the $_GET['tbl'] is empty then the script would check by default a table. Like index_tbl.

    Is this ok as it is working without errors. I will remove the 'echo' in PROD mode.
    <i>
    </i>echo $tbl = ISSET($_GET['tbl'])?strtolower($_GET['tbl']):links;
    Copy linkTweet thisAlerts:
    @NogDogAug 09.2022 β€”Β > @novice2022#1645720 I was doing it like this

    Looks like that's probably okay then (checking against an array of allowed values).

    > @novice2022#1645720 How did you draw that cartoon and how long it took ?

    I didn't: https://xkcd.com/327/
    Copy linkTweet thisAlerts:
    @novice2022authorAug 09.2022 β€”Β @NogDog#1645722

    Seen that cartoon before.Looks familiar. But not on that website. Probly on another tutorial site. They usually copy each others contents.
    Copy linkTweet thisAlerts:
    @NogDogAug 09.2022 β€”Β > @novice2022#1645724 They usually copy each others contents.

    XKCD is the original source (the site I linked). He's been running that site for years, and has a number of books published on related nerdy topics, such as [u][What If?](https://en.wikipedia.org/wiki/What_If%3F_(book))[/u].
    Copy linkTweet thisAlerts:
    @novice2022authorAug 09.2022 β€”Β @NogDog#1645729

    Ok. Will checkout the wiki link. Have a hunch will be interested as just read the first line about some book.

    In the meanwhile, can you shower your brain cells this way ?

    https://forum.webdeveloper.com/d/400361-why-array-leaks-memory-on-every-page-reload
    Γ—

    Success!

    Help @novice2022 spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 β€” BETA 10.12,
    social: @webDeveloperHQ,
    });

    legal: ({
    terms: of use,
    privacy: policy
    analytics: Fullres
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinciβ€’003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @aldoushuxley,
    tipped: article
    amount: 1000 SATS,

    tipper: Anonymous,
    tipped: article
    amount: 1000 SATS,

    tipper: @linalla,
    tipped: article
    amount: 1000 SATS,
    )...