Olcay Ertaş
Olcay Ertaş

Reputation: 6228

Build query with "values" part

I have a long insert query which contains 10+ columns. I am looking for a compact way to build this query like:

$mysqli = new MySQLi(...);
$mysqli->query("insert into table");
$mysqli->addKeyValue("columnName1", "value1");
$mysqli->addKeyValue("columnName2", "value2");
$mysqli->addKeyValue("columnName"3, "value3");
$mysqli->execute();

As far as I know there is no way to do this with default MySQLi. Is there a library that provides similar functionality?

The reason I insist on trying to do something like this is I am trying to write code that doesn't exceeds 80-100 character limit per line to make my code more readable.

I know prepared statements and bind param.

Upvotes: -1

Views: 275

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157839

I can offer you a library called SafeMysql which I wrote to make mysqli usable. With it the approach will be different:

include_once 'safemysql.class.php';
$db = new safeMysql();
$data = [
    "columnName1" => "value1",
    "columnName2" => "value2",
    "columnName3" => "value3",
];
$db->query("insert into table SET ?u", $data);

as you can see, in both cases the line size doesn't exceed even 40 characters.

Upvotes: 1

RiggsFolly
RiggsFolly

Reputation: 94642

What is wrong with bind_param this is so very similiar to what you are tring to do.

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', 
                    $code, 
                    $language, 
                    $official, 
                    $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
$stmt->execute();

// add another row
$code = 'XXX';
$language = 'Yyyyyyyy';
$official = "Y";
$percent = 19.2;

/* execute prepared statement */
$stmt->execute();

Shamlessly ripped off from the manual

Upvotes: 0

Related Questions