INSERT / UPDATE Mysql Single Form - php

I have 2 database tables
tbl1 users ---------- tbl2 gamesystems
uid field ------------- gs_uid field
the 2 tables are tied together by the user_id..
now i want tbl2 to only be updated able and fields are not required.. with the exception of the gs_uid when they update there system.
my only issue is i need to insert the user_id into the gs_uid.
function game_system()
{
if(isset($_POST['game_system'])) {
$user_id = $_SESSION['uid'];
$motherboard = escape($_POST['motherboard']);
$processor = escape($_POST['processor']);
$memory = escape($_POST['memory']);
$graphics = escape($_POST['graphics']);
$harddrive = escape($_POST['harddrive']);
$power = escape($_POST['powersupply']);
$cooling = escape($_POST['cooling']);
$towercase = escape($_POST['towercase']);
$sql = "INSERT INTO gamesystem(gs_uid, motherboard, processor, memory, graphics, harddrive, powersupply, cooling, towercase) ";
$sql .= "VALUES('{$user_id}','{$motherboard}','{$processor}','{$memory}','{$graphics}','{$harddrive}','{$power}','{$cooling}','{$towercase}') ";
$result = query($sql);
}
}

If gs_uid is the primary key of table 'gamesystem' , then this field should not accept empty data.
Otherwise, if gs_uid is NOT the key, what's the primary key of this table? In case of UPDATE, you'll need to specify which row you'd like to update, otherwise the system will not know how to do so.
the SQL should looks like below
UPDATE "gamesystem"
SET "gs_uid" = $user_id
WHERE YOUR_PRIMARY_KEY_COLUMN = SPECIFIC VALUE;

Related

On duplicate key update for multiple values that aren't the primary key

I need to basically do an "insert if not exists else update" type query, and the way everything I've read tells me to go is Insert into...On Duplicate Key Update. The thing is, my primary key is an autoincrement value that I never interact with or keep track of and I can't really dynamically generate it to put into my query.
A typical row would be:
ID| Project_ID | Location | Cost_Center_Category | Name | Number | Year | Q_1 |
1 | 200 | NUH | 1 |asfoi | 1098123|etc.
Basically the uniqueness (not literally) of each row came with the combination of Project_ID, Location, Cost_Center_Category, Name, Number, and year. If those all were identical, then an update to Q_1 would occur.
UPDATE Labour_Planning
SET $Q = $submit
WHERE Project_ID = $selected_project
AND Year = $selected_year
AND Cost_Center_Category = $CCC
AND Cost_Center_Name = '$CC'
AND Cost_Center_Number = '$CC_Number'
AND Location = '$location';
Yeah, I know, SQL injection and all that, I will make this better. For now, I need to figure out a way to basically insert a row if ANY of the above columns are different. Is that possible with the Insert into....On Duplicate key?
Every example I see uses the primary key in their insert statement, and that's not really possible in this case.
I have done some test and thats what I get
create table test.a (
a int PRIMARY KEY,
b int,
c int
);
create UNIQUE index some_index on test.a(b,c);
insert into test.a VALUES (1,2,3);
insert into test.a VALUES (2,2,3); -- fails
insert into test.a VALUES (2,2,3) ON DUPLICATE KEY UPDATE a = 2; -- updates
Thus, all you need is to create composite unique index on fields that you consider must be unique.
I didn't want to do this for fear of obnoxious overhead, but considering I won't actually have many updates/inserts at a time, I just went with this.
$labour_select = "SELECT Project_ID
FROM Labour_Planning
WHERE Project_ID = $selected_project
AND Year = $selected_year
AND Cost_Center_Category = $CCC
AND Cost_Center_Name = '$CC'
AND Cost_Center_Number = '$CC_Number'
AND Location = '$location';";
$result = $mysqli->query($labour_select);
$num_rows = mysqli_num_rows($result);
if ($num_rows == 0){
$labour_insert = "INSERT INTO Labour_Planning (Project_ID, Location, Cost_Center_Category, Cost_Center_Name, Cost_Center_Number, Year, $Q) VALUES ($selected_project, '$location', $CCC, '$CC', '$CC_Number', $selected_year, $submit)";
$insert_result = $mysqli->query($labour_insert);
}
else {
$labour_update = "UPDATE Labour_Planning
SET $Q = $submit
WHERE Project_ID = $selected_project
AND Year = $selected_year
AND Cost_Center_Category = $CCC
AND Cost_Center_Name = '$CC'
AND Cost_Center_Number = '$CC_Number'
AND Location = '$location';";
$update_result = $mysqli->query($labour_update);
}
Now to look up prepared statements! I hear not only do they keep you protected from sql injection, it will make things of this nature faster as well! Thanks for all the help!

How to get a tuple's values that is inserted into PostgreSql db using php?

I am trying to insert a tuple into PostgreSql using PHP. After inserting the tuple I want to get the value of one of the columns of the inserted row. This column value is generated automatically by the db as it is defined as SERIAL in DDL.
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me')";
$result = pg_query($dbh,$query);
if (!$result) {
$status = 0;
} else {
$status = 1;
}
$row = pg_fetch_assoc($result);
$pID = $row['postID'];
$array = array(
'status' => $status,
'pID' => $pID
);
#Delete query is only for checking if the code is working.
$query = "DELETE FROM posts WHERE postID='$pID'";
$result = pg_query($dbh,$query);
The table 'posts' has following DDL:
CREATE TABLE posts
( title CHAR(20),
content CHAR(42),
x_coor INTEGER,
y_coor INTEGER,
userID CHAR(50),
time_stamp TIMESTAMP default current_timestamp,
postID SERIAL,
PRIMARY KEY(postID),
FOREIGN KEY (userID) REFERENCES users ON DELETE CASCADE);
I want to get the value of 'postID' column when I insert a row into the table 'posts' to perform additional functions based on postID. I have tried pg_fetch_assoc, pg_fetch_row, pg_fetch_object & pg_fetch_array. None of those seem to work. (I made appropriate modifications to the code when using each of those functions.)
Is there something incorrect in the code or perhaps I am missing something?
Thanks!
A good way is the returning clause:
INSERT INTO posts
VALUES('$title','$msg',$x,$y,'$me')
RETURNING id;
My PHP is a bit rusty, but it'd look something like:
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me') RETURNING id";
$result = pg_query($dbh, $query);
if ($result) {
$row = pg_fetch_row($result);
$inserted_id = $row[0];
}

SQLite 3 , duplicate a row and change only one field

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;

How to alter a table (add a column) simultaneously when a row is added (column name = row id) in another table?

How to write code in MySQL such that when ever a row with a primary key id is added to a table, a corresponding column is added in another table such that the name of the column is equal to the id of the row just added.
I tried the following but to no use.
sqlQuery("INSERT INTO table1(name) VALUES('$name')");
$id = sqlQuery("SELECT id FROM table1 WHERE id = LAST_INSERT_ID()");
$id = mysqli_fetch_array($id);
$id = $id['id'];
sqlQuery("ALTER TABLE table2 ADD '$id' INT(2) NOT NULL");
sqlQuery - user defined function that return mysqli_query result.
Any help would be great.
Also, I'm a newbie. Sorry if this is a silly question to ask.
Make it OOP style and there is a var in the class that automatically returns the last updated item.
$con = new mysqli(SQL_HOST, SQL_USER, SQL_PASSWORD, SQL_DATABASE); //do normal error checking with database connection
$sql = "INSERT INTO table1(name) VALUES('$name')";
$con->query($sql);
$sql2 = "ALTER TABLE table2 ADD '$con->insert_id' INT(2) NOT NULL" //$con->insert_id is the parm you are looking for.
$con->query($sql2);

insert data from one table to another table

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

Categories