Online Users Page


QN

Previous notifications:
4 years ago
New Blog Entry In .:A-MAN:. lists stuff!
11 years ago
Regular accepted your friend request
More..
17X27
4 years ago
Anyone know if there's something like tagged templates from js, in php?

Hoping to transform something like this:
`SELECT * FROM MyTable WHERE Something=${"abc"} AND SomethingElse=${1}`


Into something like this:
{
    $stmt = $Conn->prepare("SELECT * FROM MyTable WHERE Something=? AND SomethingElse=?");
    $stmt->bindParam(1, $param[0], PDO::PARAM_STR);
    $stmt->bindParam(2, $param[1], PDO::PARAM_INT);
    $stmt->execute();

    return $stmt->fetch();
}


I've got an example of how it can be done in js, and it will output to the console to show it's working/what it does.
Bottom half is what actually matters:

class PDO {
  static PARAM_STR = "PARAM_STRING";
  static PARAM_INT = "PARAM_INT";
  // other types...

  prepare(query) {
    return new PreparedStatement(query);
  }
}

class PreparedStatement {
  constructor(query) {
    console.log(query);
  }

  bindParam(parameter, variable, dataType) {
    console.log(parameter, variable, dataType);
  }
}

// set up fake connection
const Conn = new PDO();


// actual meat of what i'm trying to show
function safeQuery(strings, ...params) {
  const query =
    strings.join("?") + (strings.length == params.length ? "?" : "");

  const stmt = Conn.prepare(query);

  for (let i = 0; i < params.length; i++) {
    const value = params[i];
    let type;

    // prob a better way to do this, like a dictionary
    switch (typeof value) {
      case "string":
        type = PDO.PARAM_STR;
        break;
      case "number":
        // we could resolve into other types like double, float
        // esp in php
        type = PDO.PARAM_INT;
        break;
      default:
      // error handling bla bla
    }

    stmt.bindParam(i + 1, value, type);
  }
}

safeQuery`SELECT * FROM MyTable WHERE Something=${"abc"} AND SomethingElse=${1}`;


Would make writing queries + converting possibly unsafe ones way easier.
Back

Please Login To Post

70.:A-MAN:.
4 years ago
Idk of anything like that.
Reply
v3.2