I was wondering how can I update my two database tables using PHP and MySQL? I want to add a second table called tags_2 that will check if a tag already exists and if it does add it to the current count in the table and if the tag does not exist add it to the table.
I hope I explained it right?
I basically need help in adding the correct code in the right places this has stumped me all day for some reason? I got the first table to work but not the second?
Here is my MySQL tables below.
CREATE TABLE tags (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
page TEXT NOT NULL,
tag VARCHAR(255) NOT NULL,
count INT NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE tags_2 (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
tag VARCHAR(255) NOT NULL,
count INT NOT NULL,
PRIMARY KEY (id)
);
And Here is my PHP script below.
<?php
require_once ('./mysqli_connect.php');
if (isset($_POST['submitted'])){
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT * FROM tags");
if (!$dbc) {
print mysqli_error($mysqli);
}
$page = $_SERVER['SCRIPT_FILENAME'];
$tag = mysqli_real_escape_string($mysqli, $_POST['tag']);
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT id, count, page FROM tags WHERE tag='$tag' AND page = '$page'");
if(mysqli_num_rows($dbc)){
$tag_info = mysqli_fetch_array($dbc);
$tag_info_id = $tag_info["id"];
$tag_info_count = $tag_info["count"] + 1;
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"UPDATE tags SET count='$tag_info_count' WHERE id='$tag_info_id'");
echo "$tag now with $tag_info_count instances";
} else {
$mysqli = new mysqli("localhost", "root", "", "sitename");
$clean_url = mysqli_real_escape_string($mysqli, $page);
$dbc = mysqli_query($mysqli,"INSERT INTO tags (tag, count, page) VALUES ('$tag', 1, '$clean_url')");
if (!$dbc) {
print mysqli_error($mysqli);
}
echo "1 record added";
}
mysqli_close($mysqli);
}
?>
Will the tables look better like this.
CREATE TABLE tags (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
page TEXT NOT NULL,
tag VARCHAR(255) NOT NULL,
count INT NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE tags_2 (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
tag_id INT UNSIGNED NOT NULL DEFAULT 0,
tag VARCHAR(255) NOT NULL,
count INT NOT NULL,
PRIMARY KEY (id)
);