1

Say I have a PHP function that generates a unique robot name, e.g.:

$rname = generateRobotName();   

I would like to duplicate all the robots with REMOTE controller AND assign a unique Robot Name to each new one (generated by the above function).

How do I go about that?

INSERT INTO robots values (origin, name, color, position, controller)
SELECT origin, '".$rname."', color, position, controller
FROM robots
WHERE controller = 'remote'
4
  • You can implement generateRobotName on MySQl side Commented Sep 18, 2020 at 12:53
  • @SlavaRozhnev It's quite an extensive function so I don't think that would be possible? Is there no other way to use the existing PHP function? Commented Sep 18, 2020 at 12:57
  • Are you sure you are having different columns there? Commented Sep 18, 2020 at 13:09
  • prepare(INSERT INTO robots (origin, name, color, position, controller) SELECT origin, ?, color, position, controller FROM robots WHERE controller = 'remote'); should wok then bind $rname. Commented Sep 18, 2020 at 18:49

2 Answers 2

3

In order to avoid SQL injections and other vulnerabilities that come with the integration of variables straight in the SQL statement (not a huge problem in this case, but it's good practice), you can use PDO with prepared statements. The following code loops through each of the steps for each MySQL query and updates the robot name:

$SQLInsert = "INSERT INTO robots (origin, name, color, position, controller) values (:origin, :name, :color, :position, :controller)";
$SQLSelect = "SELECT origin, name, color, position, controller FROM robots WHERE controller = 'remote'";

foreach ($pdo->query($SQLSelect) as $row){
    $params = [
            ':origin' => $row['origin'],
            ':name' => generateRobotName(),
            ':color' => $row['color'],
            ':position' => $row['position'],
            ':controller' => $row['controller']
        ];
    $SQLInsert = $pdo->prepare($SQLInsert);
    $SQLInsert->execute($params);
}

The above code does the SQL Select query, and for each row it finds, $row, It inserts the old data using the second defined query while still adding the robot name. DO keep in mind $pdo is defined as the PDO object, and you will need PDO support in your PHP install. Working example can be found here. Cheers!

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks so much! Using this approach, would the $rname have different value for each new row?
it may. I'll have to change the code. Your statements were a bit confusing. Are there two statements of MySQL? I now assume you are trying to update each row with a robot name?
Yes, exactly, that's what I'm trying to do.
Thank you for the answer. When trying the above, I am getting the following error: "Insert value list does not match column list: 1136 Column count doesn't match value count at row 1" I've made sure many times that everything matches up, and the numbers". Not sure why that is happening. I got it working with Slava's answer (which is very similar to yours).
@user3783243 Thank you for pointing this out. That was a huge oversight. I didn't know how I could miss it, lol. I have updated the answer to match your concern.
2

You can split the task for 2 parts:

  • get data from MySQl

  • nsert new data updated by PHP

    $sql = "SELECT origin, name, color, position, controller 
            FROM robots
            WHERE controller = 'remote'";
    
    $stmt= $pdo->prepare("insert into robots (origin, name, color, position, controller) values (?, ?, ?, ?, ?);");
    
    
    foreach ($pdo->query($sql) as $row) {
        $stmt->execute([
            $row['origin'],
            generateRobotName(),
            $row['color'],
            $row['position'],
            $row['controller']
        ]);
    }
    
    

Here the live code PHPize.online

Another example with named parameters:

$sql = "SELECT origin, name, color, position, controller
        FROM robots WHERE controller = 'remote'";

$stmt= $pdo->prepare(
    "insert into robots (origin, name, color, position, controller) 
        values (:origin, :name, :color, :position, :controller);"
);

foreach ($pdo->query($sql, PDO::FETCH_ASSOC) as $row) {
    $row['name'] = generateRobotName();
    $stmt->execute($row);
}

PHPize it here

2 Comments

Thank you for this answer! I got it working. Can I just ask - what do the question marks stand for? Does that stand for placeholders like :origin, :name, :color, :position? When I put those placeholders in, instead of question marks, I get an error: Invalid parameter number: parameter was not defined in So I wonder why the question marks work. Thanks a lot!
I just now updated my answer. The question marks are place holders for columns that you want to insert. If you not inserted all of table columns, you mast to write the inserted column names in query, as edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.