Question

I am having problem to insert some staff in a 3th table.

Table first contains first_id, test_name | Table second contains second_id, test_second | Table first-second contains first_id, second_id, note (can be null)

$first_id = 1;
$second_id = 3;

$stmt = $this->conn->prepare("INSERT INTO first-second (first_id, second_id) values (?, ?)");
$stmt->bind_param("ii", $first_id, $second_id);
$result_insert = $stmt->execute();
$stmt->close();

In PHPMyadmin I can do the insert but I don't know why with stmt doesn'work.

Thank you.

Was it helpful?

Solution

I would avoid to define table name with dash, it's not a good practice. Anyway you can solve your problem just putting backticks between the name of the table.

Something like this:

"INSERT INTO `table-mame` WHERE ...

OTHER TIPS

Add backticks around your table name:

$stmt = $this->conn->prepare("INSERT INTO `first-second` (first_id, second_id) values (?, ?)");

It is advised though, to not use "strange" characters in table names.

I'm assuming that you are using textbox/textarea or any other type that ask for input to insert data into your database. Your input might have special characters in it that cause for the query to fail. Try using mysqli_real_escape_string before your insert query.

$input1=mysqli_real_escape_string($_POST['input1']);
$input2=mysqli_real_escape_string($_POST['input2']);
$input3=mysqli_real_escape_string($_POST['input3']);

mysqli_query($conn,"INSERT INTO first-second (first_id, second_id, note) VALUES ('$input1','$input2','$input3')");

By the way, it's okay to use hyphen in a table name, but not recommendable:
Can a table field contain a hyphen?

$first_id = 1;
$second_id = 3;

$stmt = $this->conn->prepare("INSERT INTO first-second (first_id, second_id) values (:f1, :f2)");
$result_insert = $stmt->execute(array('f1'=>$first_id , 'f2'=>$second_id));
$stmt->close();

Hope this help.

Thanks

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top