0

What is the correct syntax for concatenating strings and variables in PHP mysqli prepared statements?

The code I have right now is this:

        if ($test_stmt2=$mysqli->prepare("UPDATE friends SET friendslist=friendslist+','+? WHERE friendsuserid=? ")) { //Insert userid and frienduserid into friends table
               $test_stmt2->bind_param('si', $friendid, $userid); //Bind parameters (friend user id, your own user id)
               $test_stmt2->execute(); //Execute the prepared query
               echo "success";
        }

Basically, I want to get the string in the friendslist column, add a comma to it, then add another variable string ($friendid) to that cell in the friends table.

1 Answer 1

2

It seems you need SQL concatentation.

However, you shouldn't use it for this purpose. Your database structure is a deadly sin against Holy Normal Form.

Please, do not store comma-separated values in a database cell. Create a distinct table to store corresponding values.

userid | friendid
     1 |        2
     1 |        3
     1 |        5
     5 |        1
     5 |        2
     2 |       10

this way you will need a regular insert query like this:

INSERT INTO friendslist SET friendid = ?, userid = ? 

It will save you A LOT of hair in the near future

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

4 Comments

yes, i agree that my design is pretty flawed. I want to do it the way you proposed, but how will i know how many columns of friendids to create if people choose different amounts of friends? will i need to constantly expand my table?
so a different table for every user? then a row for every user's friend?
just added the table.
+1. Just for completeness: concatenation in MySQL is easiest using the CONCAT() function.

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.