PHP/MySQL table problem?
I can update almost everything in both my mysql tables when somebody enters a tag I just don't know how to add the tags tables id value to the q_tags tables tag_id value which will be the same when the user enters the tag.
I hope I explained this okay.
Can someone please help me.
Here is the MySQL tables below.
CREATE TABLE q_tags (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
tag_id INT UNSIGNED NOT NULL, //This value should be same as the tags table id
users_q_id INT UNSIGNED NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE tags (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
tag VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
Here is the script below.
<?php
require_once ('./mysqli_connect.php');
if (isset($_POST['submitted'])) {
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT q_tags.*, tags.* FROM q_tags, tags");
if (!$dbc) {
print mysqli_error($mysqli);
}
$page = '3';
$tag = mysqli_real_escape_string($mysqli, $_POST['tag']);
$mysqli = new mysqli("localhost", "root", "", "sitename"开发者_如何学编程);
$dbc = mysqli_query($mysqli,"SELECT q_tags.*, tags.* FROM q_tags INNER JOIN tags ON tags.id = q_tags.tag_id WHERE q_tags.users_q_id=3");
if(!mysqli_num_rows($dbc)){
$mysqli = new mysqli("localhost", "root", "", "sitename");
$clean_url = mysqli_real_escape_string($mysqli, $page);
$query1 = "INSERT INTO q_tags (tag_id, users_q_id) VALUES ('', '$page')";
$query2 = "INSERT INTO tags (tag) VALUES ('$tag')";
if (!mysqli_query($mysqli, $query1)) {
print mysqli_error($mysqli);
return;
}
if (!mysqli_query($mysqli, $query2)) {
print mysqli_error($mysqli);
return;
}
echo "$tag has been entered";
if (!$dbc) {
print mysqli_error($mysqli);
}
}
mysqli_close($mysqli);
}
?>
It seems that you are trying to insert null into your q_tags table. You need to retrieve the last inserted id before you can insert it into your q_tags table.
Try this instead:
$query1 = "INSERT INTO tags (tag) VALUES ('$tag')";
if (!mysqli_query($mysqli, $query1)) {
print mysqli_error($mysqli);
return;
}
$lastId = mysql_insert_id();
$query2 = "INSERT INTO q_tags (tag_id, users_q_id) VALUES ('$lastId', '$page')";
if (!mysqli_query($mysqli, $query2)) {
print mysqli_error($mysqli);
return;
}
精彩评论