Jump to content

Recommended Posts

Good day guys, having some issues getting the following to work:

<?php

$db = new PDO('sqlite:test22.db');



function insertMember($db, $firstname, $sname ){

    $sql = sprintf("INSERT INTO info (name, surname) VALUES ( "%s", '%s' '%s')");
    echo $sql . '<br/>';
    $db->query($sql);
}



    $firstname = array(
        'Johnathon',
        'Anthony',
        'Erasmo',
        'Raleigh',
        'Nancie',
        'Tama',
        'Camellia',
        'Augustine',
      
    );

    $lastname = array(
        'Mischke',
        'Serna',
        'Pingree',
        'Mcnaught',
        'Pepper',
        'Schildgen',
        'Mongold',
        'Wrona',
        'Geddes',
        'Lanz',
   
    );

    $name = $firstname[rand ( 0 , count($firstname) -1)];
    $name .= ' ';
    $surname = $lastname[rand ( 0 , count($lastname) -1)];

    insertMember($db, $name, $surname);

;





?>

The video tutorial I followed made use of "%s" but for some reason my browser tells me the syntax is incorrect. I am a bit lost, as I am relatively new to PHP as a whole.
Any assistance would be appreciated.
Cheers!

While I hate what you are doing your current problem is missing comma in the values of your query.  Why not look at some real syntax in the official PHP manual to see how that is supposed to look.  Read the part on prepared queries.

Look up sprintf in the manual to see how to use it properly.

EDIT: I agree with @ginerjm - you should use a prepared query - it's easier than sprintf.

$db->prepare("INSERT INTO info (name, surname) VALUES ( ?, ? );
$db->execute( [ $name, $surname ] );

You've also got a quote issue in your actual query string. Notice the first %s is surrounded by double quotes and a different color than the rest? Change those quotes to single quotes.

And not to continue beating a dead horse, but I too hate what you're doing. This is how WordPress does 'prepared statements' (or at least it was last time I looked a couple years ago). Don't be like WordPress.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.