logo
down
shadow

Building a dynamic PHP prepared statement from user entry


Building a dynamic PHP prepared statement from user entry

By : Chris K
Date : October 16 2020, 06:10 AM
I wish this help you As with many things, this would be a LOT easier with PDO. But, just off the top of my head this is how I would approach it. You need to build 3 structures here. The SQL, the list of parameter types ("s" or "i") and the list of parameters themselves. This is all pretty straightforward.
Getting this into the bind_param() function can be a bit tricky if you haven't done it before, but as detailed elsewhere the argument unpacking operator works nicely, once you have all your arguments into an array.
code :
<?php
if (isset($_REQUEST['sub'])) {
    $types = "";
    $where = [];
    $params = [];

    if (!empty($_REQUEST['student_fname'])) {
        $types .= 's';
        $where[] = 'student_fname = ?';
        $params[] = $_REQUEST['student_fname'];
    }
    if (!empty($_REQUEST['student_lname'])) {
        $types .= 's';
        $where[] = 'student_lname = ?';
        $params[] = $_REQUEST['student_lname'];
    }

    if (count($where)) {
        $where = "AND " . explode(" AND ", $where);
    } else {
        $where = "";
    }

    $sql = "SELECT * FROM student_records
    WHERE 1=1 
    $where
    ORDER BY class ASC, student_lname ASC";

    $stmt = $con->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    while ($res = $stmt->get_result()) {
        // ....
    }
}
<?php
if(isset($_REQUEST['sub'])){
    $where = [];
    $params = [];

    if(!empty($_REQUEST['student_fname'])) {
        $where[] = 'student_fname = ?';
        $params[] = $_REQUEST['student_fname'];
    }
    if(!empty($_REQUEST['student_lname'])){
        $where[] = 'student_lname = ?';
        $params[] = $_REQUEST['student_lname'];
    }

    if (count($where)) {
        $where = "AND " . explode(" AND ", $where);
    } else {
        $where = "";
    }

    $sql = "SELECT * FROM student_records
    WHERE 1=1 
    $where
    ORDER BY class ASC, student_lname ASC";

    $stmt = $con->prepare($sql);
    $stmt->execute($params);
    $data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}


Share : facebook icon twitter icon
Building dynamic if statement based on user-defined input

Building dynamic if statement based on user-defined input


By : Jagadish
Date : March 29 2020, 07:55 AM
may help you . To avoid using eval: Ruby can create code dynamically, so do that instead of adding strings together. All you have to do is take the strings away!
code :
conditions = to_match.map do |attr|
  proc {|row| row[attr.to_sym] > attr }
end
does_match = conditions.all? {|c| c.call(row) }
does_match = conditions.any? {|c| c.call(row) }
Catch Duplicate entry with prepared SQL statement

Catch Duplicate entry with prepared SQL statement


By : Paul DeMarco
Date : March 29 2020, 07:55 AM
help you fix your problem You can use INSERT IGNORE and then check how many rows were affected using PDOStatement::rowCount
Concept should be along the lines of:
code :
$result = $db->prepare("INSERT IGNORE INTO comptability (id_comptability, order_id, Reduction, `%TVA`, Facture) VALUES (?, ?, ?, ?, ?)");
if ($result->execute(array($no_facture, $id_order, $reduc_tot, $tot, $date))) {
  if ($result->rowCount() == 0) {
   // You had a duplicate record.
  } else {
   // all good.
  }
}
PDO Dynamic Query Building with prepared statements

PDO Dynamic Query Building with prepared statements


By : Ian White Nyc
Date : March 29 2020, 07:55 AM
I wish this help you this is funny. i can't answer my question. i found the solution. it is because of double foreach loop.
code :
$i = 0;
    foreach ($params as $key) {
        $query->bindValue($key, $values[$i], PDO::PARAM_STR);
    $i++;}
Building a Dynamic Prepared statement for searching

Building a Dynamic Prepared statement for searching


By : Nikita Belov
Date : March 29 2020, 07:55 AM
Hope this helps You were on the right track as far as you went. What you missed is how to get the right number of bind parameters. $a_bind_params has enough parameters for the title, but when you add username to it, it has to be doubled. i.e., if $a_bind_params = ['bottle','soda'], your new array needs to be ['bottle','soda','bottle','soda'] or ['bottle','bottle','soda','soda']
My Sql prepared statement insert avoid duplicate entry

My Sql prepared statement insert avoid duplicate entry


By : Karthik
Date : March 29 2020, 07:55 AM
this will help I want to insert some data into a table named USERLOGIN and be sure that no duplicate data will be inserted. I wrote this code as my insert quesry in a java program: , use this query :-
Related Posts Related Posts :
  • how to return an array through ajax
  • How to open a PDF file in browser using PHP
  • PHP problem with getimagesize()
  • HTML Parser to Get Content between Elements
  • Developing a facebook application: PHP commands don't work
  • In a (PHP) framework, what would be a good name for a "manager" class?
  • In PHP how do i update values in an asssociative array and store the entire array?
  • Why is my php script freezing?
  • Newbie Programmer needs Motivation
  • select outgoing ip for curl request
  • ASP.net or PHP webmail app I can install on my shared hosting domain with inteface similar to Gmail
  • how to maintain session in cURL in php?
  • 2 SQL get from db
  • mysql_fetch_array returns only one row
  • With or without $this in PHP
  • Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo
  • How can I simplfy this logic
  • Is there some trick to override a class dynamically in PHP?
  • PHP-based LaTeX parser -- where to begin?
  • PHP fgets "noblock"?
  • ATOM date format to UNIX in PHP
  • Why do we need to base64 encode images before transmitting?
  • Intermittent PHP warning: "imap_open(): Couldn't open stream"
  • Python array in dict
  • find alphabatic series value of ABC & ACA
  • Laravel - how get a single model instance not as collection, but single model from belongsToMany
  • php search text file for any wav file names
  • PHP -- Running shell_exec() does NOT return all output
  • Multiple PHP image upload, only uploads first image selected
  • How to increase the maximum size of a cookie?
  • Adding custom link to href tag
  • PHP regexp (preg_match_all) - find all standalone links
  • link rel="preload" with PHP and Apache
  • What is the difference between Laravel app->make(ClassA) class and new ClassA()
  • Trying to use [] to get value of parameter
  • Difference between $object->attribute and $object['attribute'] in Laravel
  • How to get table of "0" in php
  • Between two(2) Dates with date format for column (Y-m-d)
  • how display another object of data in a Templates
  • How to extend Laravel query builder?
  • Skip value of (sub)array if match exists
  • array combine of unequal length of TWo arrays
  • Security Error. Illegal access detected using ccavenue in php
  • Injection of data in twig
  • Laravel middleware logic doesn't seem to work
  • How to change application name in laravel 5.8
  • How to join string after last array value?
  • How to properly use Laravel models?
  • inserting multiple files in the database at once from multiple inputs
  • Docker + Xdebug + VSCode Could not connect to client
  • Can a sql command in php be set from pieces of other variables with "." connector?
  • Is there a more efficient way to code this conditional statement? Is there a max number of conditionals in PHP?
  • how to pass a variable through a url
  • "continue" targeting switch is equivalent to "break" error under php 7.3
  • Symfony 4 isClicked method not found
  • is php sha256 safe today (may 2019)?
  • How to only find a substring in a string?
  • How to create a instance of an array?
  • Login page "mysqli_query"
  • I need a way to find the five of clubs from this php array
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk