tags:

views:

35

answers:

1

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);
}
?>
A: 

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;
}
emedbo
I get a warning now :(
tor
What does the warning *say*?
Piskvor
Warning: mysql_insert_id() [function.mysql-insert-id]: A link to the server could not be established
tor
Maybe you could replace mysql_insert_id() with mysql_insert_id($mysqli);
emedbo
@emedbo - It didn't work either, thanks though :(
tor
At the risk of sounding extraordinarily stupid... should that be mysqli_insert_id(), not mysql_insert_id() with no i on the end? Since all the other function calls have a mysqli at the beginning...
Platinum Azure