I am having a problem locating comments for a given user with the following table structure:
usertable (id, userid, name)
comments (id, commentname, date)
Note: usertable.id is not the same as comments.id, and they are both autoincrement
How should I go about updating these tables to fix this problem?
Update
Is this code good for all users get their own votes when someone voted as thilo savage told me ?
$sth = thumbsup::db()->prepare(
'INSERT INTO'
.thumbsup::config('database_table_prefix')
.'votes_users(vid, userid) VALUES (?,?)');
$sth->execute(array($this->vid, $userid));
You've got two options:
Add a 'uid' column to the comments table which references the usertable's 'id' column. That way, you have a way to keep track of which comments belong to which users.
Create a table 'user_comment' with the columns 'uid' and 'cid'. This option leaves the two existing tables as they are, and the 'user_comment' table is responsible for keeping track of which comments belong to which users.
EDIT: Rewritten to use many-to-many relationship because current tables can't be altered.
Create a new table called comments_users with these fields:
cuid (primary key and auto increment) | cid | uid
Then get all of a user's comments with this code:
$user_id = '1234';
// get all the user's comment ids from comments_users table
$find = mysql_query("SELECT `cid` FROM `comments_users` WHERE `uid` = '".$user_id."'");
// generate a query that grabs all those comments
$load = "SELECT * FROM `comments` WHERE ";
while ($row = mysql_fetch_array($find) {
$load .= "`id` = '".$row['cid']."' OR ";
}
// shop off the last OR
$load = substr($load,0,-4);
// put all the user's comments into comments array
$q = mysql_query($load);
while ($comment = mysql_fetch_array($q)) {
$comments[] = $comment
}
print_r($comments);
As far as inserting goes, you'll insert comments into the comments table like you normally would, but then you'd ALSO insert a row into comments_users table filling in the appropriate cid and uid for that comment
Related
I have three tables users_tbl, skill_tbl, user_skill_tbl where
users_tbl have 1 to many relations with user_skill_tbl(auto increment)
and skill_tbl have 1 to many relations with the user_skill_tbl.
user_skill_tbl have user_skill_id, skill_id and user_id.
I don't have a problem in inserting the data in the tables.
I have a form where users detail and multiple check option of skill(i get the skill_id only) is there.
when the from is filled, first the user's table is inserted then the last inserted id is taken and the user_skill_tbl is inserted.
But My problem is when I have to update the user_skill_tbl I have used
$skill = $_POST['skill_id'];
for($i=0;$i < count($skill); i++){
$name[$i]= mysqli_escpae_string($con,$skill[$i]);
$query = "update into user_skill_tbl (skill_id)
values ('$skill_id') where user_id = '$user_id'"
after the query is executed the last id of the skill_id is updated on all the skill_id in the user_skill_tbl. I know that I should manipulate along with the user_skill_id but I am not being able to figure it out
I guess you are mixing up the update and insert syntax with "update into". It's "update tablename" or "insert into tablename".
I am not sure how you store your data in user_skill_tbl but if, as I guess, for each user you only store the records related to his/her skills, you need to first delete all the skills for the current user, something like:
$query = "delete from user_skill_tbl where user_id = '$user_id'"
and then add each skill in your for loop:
$query = "insert into user_skill_tbl (skill_id, user_id) values
('$skill_id', '$user_id')
Put everything in a transaction to avoid inconsistencies if something goes wrong during the execution.
I have some table in my SQLite3 database , for example
table1
table2
table3
All tables have a field called id (integer NOT NULL PRIMARY KEY UNIQUE) (not auto increment)
My goal is to duplicate a record of one of these tables, changing only the id field (with a new id). I would like to do this without having to know the name of all the columns in each table.
I tried this solution, it works, but in this way i have to know the names of all columns
INSERT INTO table1 (id,column1,column2,column3)
SELECT NEWID,column1,column2,column3 FROM table1
WHERE id = OLDID
I tried also the method to create a temporary table, but without success
I have to run a query like this PRAGMA table_info(table1) , save the columns's name in an array , and then run a query created with a cycle ?
thanks
My solution
$TABLENAME = "mytablename";
$ID = 1423659222480;
$NEWID = 1423659222481;
$db = new PDO('sqlite:db.sqlite3');
$result_columns = $db->query("PRAGMA table_info(".$TABLENAME.")");
$appColumns = array();
$appColumns2 = array();
foreach ($result_columns as $row) {
array_push($appColumns, $row["name"]);
if($row["name"] != "id") array_push($appColumns2, $row["name"]);
}
$appColumns = implode(",",$appColumns);
$appColumns2 = implode(",",$appColumns2);
$appColumnsWithoutID = $NEWID.",".$appColumns2;
$queryDuplicate = "INSERT INTO ".$TABLENAME." (".$appColumns.") SELECT ".$appColumnsWithoutID." FROM ".$TABLENAME." WHERE id = ".$ID;
Im creating a website for booking activities. I have 3 centres. The customer is cant book the same activity twice neither in a different centre. Im using a table in mysql which i store the infos provided by the costumers. Is there any way to filter or to check in my php code if a customer has already booked the same activity more than one time and echo an error msg?
my table(and the info im asking) contains these columns:
ID(Primary)
FirstName
LastName
Email
ContactNumber
ClassName
Week
Intensity
CentreName
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
When you create the table add the unique attribute to the fields you want to prevent, something like this
CREATE TABLE Persons
(
P_Id INT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
)
If you already have created the table just edit it like this
ALTER TABLE Persons
ADD UNIQUE (P_Id)
Hope this helps you; If you do not have a unique id i believe this will suit you best on what you need; Note that this is not the full code; You need to add some to other information to fit in your question;
// Checks if the value already exist on the database
$query = SELECT EXISTS(SELECT column_name FROM table_name WHERE
condition LIMIT 1)
// If condition is not met it will proceed with save
if (mysql_num_rows(!$query) > 0) {
echo "Activity Booked";
} else { // If condition is met it will echo an error message
echo "Unable to booked activity"; }
You need to create a unique (composite) index on the column(s) that you wish to be unique. You can disregard your PK when making your unique index. In your case your sql would look something like:
Alter table yourtablename
add unique index idx_unq(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`);
Then do an INSERT IGNORE INTO instead of an INSERT INTO.
This post may also help you.
"INSERT INTO .. ON DUPLICATE KEY UPDATE" Only inserts new entries rather than replace?
In order to see if record already exist in table you must first "test" to see if that exact record exist in your table. This is to be done before the 'Insert IGNORE Into' in your logic. Using the variables your code would look something like this:
$testcount = "Select count(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`)
from yourtablename
where
(LastName = '$LastName' AND FirstName= '$FirstName' AND Email= '$EMAIL' AND ContactNumber= '$ContactNumber' AND ClassName= '$ClassName' AND Week= '$Week' Intensity = '$Intensity' AND CentreName = '$CentreName' )";
This query will give you back (assuming there are no duplicates already in the table) a 0 or a 1 and store it in your $testcount variable. This can then be used to either determine based on the value to insert the record into the table or print a message to end user informing them that it already exist.
I am not sure how you want to structure the php code but the psuedocode would look something like:
If $testcount = 1 then do your insert.
else if $testcount = 0 then echo your message.
i have this code that work well.
$sql = "INSERT IGNORE INTO phpc_events (cid, owner, subject, description, ctime)
SELECT '1', '1', title, description, start_tdate from at_courses";
mysql_query($sql);
i put this into this page :
> http://localhost/msigilearnv2/tools/calender/copy_database.php
when first runs the page it will copy table from at_courses to phpc_events..
when second runs.. how i can prevent duplication data? because it keep add same data. i put ignore but still not works
I am sharing you one of the alternative. Lets say you have a record in the database and cid value is '1'.
First step check the value if it is already exists in the database.
$sql = "SELECT cid FROM phpc_events";
$returned = mysql_query($sql);
if(mysql_num_rows($returned) > 0){
while( $row = mysql_fetch_array($returned) ){
$PhpcArray [] = $row; //stores result returned in array to ensure less resource used
}
}
$sqlC = "SELECT anotherId FROM at_courses";
$returnedC = mysql_query($sqlC);
if(mysql_num_rows($returnedC) > 0){
while( $rowC = mysql_fetch_array($returnedC) ){
if( in_array( $rowC['anotherId'], $PhpcArray ) ){
// do nothing as id is already exists in phpc_events
}
else{
// do insertion because id in at_courses is not exist yet in phpc_events
}
}
}
Hope this helps.
Another alternative.
By the way you can also try this query if it matches your column as I don't know how your table structure looks like
SELECT cid
FROM at_courses
WHERE cid NOT IN (
SELECT cid FROM phpc_events
)
This query will return the cid in the at_courses which is not yet occur in phpc_events. Then do the insertion for those cid returned from at_courses table.
Thank you.
My MySQL isn't great, but you will need to do something the like:
$sql = "INSERT IGNORE INTO phpc_events (cid, owner, subject, description, ctime)
SELECT '1', '1', title, description, start_tdate from at_courses"
left join phpc_event on phpc_events.cid = at_courses.cid //(and others you want matched for dups
where phpc_events.cid is null
;
If you have a primary key in your tables, you can replace INSERT with REPLACE. This will insert new records or replace them if the primary key already exists.
alter the table by adding UNIQUE constraint
ALTER TABLE phpc_events ADD CONSTRAINT your_field UNIQUE (cid, owner, subject, description, ctime)
I'm building a database for making hotel reservations. One table called "reservations" holds the general details of the reservation, while another called "rooms" holds details about specific rooms (each reservation has many rooms, each room belongs to only one reservation).
I would like to be able to easily generate duplicate reservations records (except for the primary key, of course). My problem is in generating the rooms data as an array which is then inserted into the rooms table while being associated to its reservation.
I've come as far as the following trivial code (stripped down to the bare essentials for discussion purposes).
if (isset($_POST['action']) and $_POST['action'] == 'Duplicate')
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.inc.php';
$id = mysqli_real_escape_string($link, $_POST['id']);
// retrieve reservation
$sql = "SELECT type_of_reservation FROM reservations WHERE id='$id'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
$type_of_reservation = $row['type_of_reservation'];
// create new reservation record
$sql = "INSERT INTO reservations SET type_of_reservation ='$type_of_reservation'";
$id = mysqli_insert_id($link);
// retrieve rooms
$sql = "SELECT reservation_id, in_date FROM rooms WHERE reservation_id='$id'";
$result = mysqli_query($link, $sql);
while ($row = mysqli_fetch_array($result))
{
$rooms[] = array('reservation_id' => $row['reservation_id'], 'in_date' => $row['in_date']);
}
The big question is, now what? Everything I've tried either generates an error or no new entries, and I can't seem to find any discussion that addresses this specific need. Thanks for your help.
PeterC, there is no code listed that shows you inserting the ROOM record information. In the //retrieve room section of your code, you are pulling the data and putting it into an array. If you really want to create a duplicate records, I would use in insert inside the database, then you don't have to pull the records out just to put them back in.
The bit of code you want will be something like this. It will be in place of the //retrieve rooms code you have listed: (psuedo code) [note: $id represents the newly selected id from your sql insert for the duplicated reservation]
INSERT INTO rooms(res_id, other, data)
SELECT $id, other, data FROM rooms WHERE id = $_POST['id'];
This will allow you to duplicate the room data, adding the new reservation_id right inside the database. No need to pull out the records, create inserts, and then put them back in. You can read more about INSERT INTO ... SELECT statements here: http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html
// create new reservation record
$sql = "INSERT INTO reservations SET type_of_reservation ='$type_of_reservation'";
//ADD HERE CODE BELOW
$id = mysqli_insert_id($link);
with mysql_insert_id you get the inseted id, but you should insert it into db.. so add
mysqli_query($link, $sql);
before retrieving data
If you simply need to duplicate records, you can do it this way:
INSERT INTO
reservations
(
SELECT
null, # assume first column is auto incrementing primary key, so leave null
`all`,
`other`,
`column`,
`names`
FROM
reservations
WHERE
reservation_id = $oldReservationId # id of reservation to duplicate
)
Then for the rooms use the last inserted id (for instance retrieved with mysql_insert_id), like this:
INSERT INTO
rooms
(
SELECT
null, # assume first column is auto incrementing primary key, so leave null
$newReservationId, # this is the new reservation id
`all`,
`other`,
`column`,
`names`
FROM
rooms
WHERE
reservation_id = $oldReservationId # id of reservation to duplicate
)