insert mysql table results twice for duplicate results in multiple columns? - php

Would some one please help me, i have a block user script. Basically everything is working ok.
When the user clicks block on the other users profile, this echos the user id, and inserts the user_id and other profile_id into the database and sets the column 'blocked' from '0' to '1'.
the user who is logged in can now not see the other user they have blocked, however the other the user they blocked can still see their profile.
the way my database works is that it needs both sets id in both columns like so:
user_id | blocked_id | blocked
1 2 1
2 1 1
In order for both users to not see each other and both be blocked i need to try insert the two id's twice almost.
It's kind of like duplicating the values inserted into the table to create the same result twice but only the other way around in the table columns.
so at the moment i have:
$sql = mysql_query("INSERT INTO ptb_block_user (user_id, blocked_id) VALUES (".$_SESSION['user_id'].", ".$user_to_id.")");
and i would need to insert these values twice but the opposite way round so it looks like the table above.
I hope im making myself clear, does anyone know how i could do this?
Thanks.
<?php
session_start();
confirm_logged_in();
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
if (!isset($_GET['to']))
exit('No user specified.');
$user_id = $_GET['to'];
$sql = mysql_query("INSERT INTO ptb_block_user (user_id, blocked_id) VALUES (".$_SESSION['user_id'].", ".$user_to_id.")");
$result1 = mysql_query("UPDATE ptb_block_user SET blocked='1' WHERE user_id=".$_SESSION['user_id']."")
or die(mysql_error());
if($result1)
{
$_SESSION['message2']="<div class=\"infobox-profile\"><strong>User Blocked</strong> - This user has successfully been blocked. You will no longer be abler to interact with each other's profiles.</div><div class=\"infobox-close\"></div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
}
else
if($result2)
{
$_SESSION['message2']="<div class=\"infobox-favourites\"><strong>User Unblocked</strong> - This user has successfully been unblocked. You can now interact with each other's profiles.</div><div class=\"infobox-close4\"></div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
}
?>

Your question is not entirely clear to me, but it seems like you're asking how to insert both values with the same query. VALUES can take multiple tuples:
INSERT INTO ptb_block_user (user_id, blocked_id, blocked) VALUES
(".$_SESSION['user_id'].", ".$user_to_id.", 1),
(".$user_to_id.", ".$_SESSION['user_id'].", 1)
Your code is highly vulnerable to mysql injection, and you should not use ext/mysql:
http://www.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated

INSERT INTO ptb_block_user
(user_id, blocked_id)
VALUES
(".$_SESSION['user_id'].", ".$user_to_id."),
(".$user_to_id.",".$_SESSION['user_id'].")
?

Related

using php to insert records in my database

I am trying to insert data into my database from a user form using php
I normally do not have any issues when doing this except this time and I believe it is because of the date type as explained below
Here is the code:
<?php
session_start();
$user = $_SESSION['who'];
if (!$_SESSION['who']){
header("location: login.php");
}
if (isset($_POST['submit'])){
require_once('dbconn.php');
$flightID = $_POST["flights"];
$sql= "INSERT INTO booking (flight_id,customer_id,checkedin,checkin_datetime, booking_datetime,baggage)
VALUES ('1', '1','0','10-10-10', '10-10-10','30')";
if($recordSet = $dbConn->query($sql)) {
echo "record set";
}
else
echo "not set";
}
?>
I will be using variables instead of hard coded values for my insert statement however I am just trying to get it to work.
Here are the attributes in my database table for booking
id, flight_id, customer_id, checkedin, checkin_datetime, booking_datetime, baggage
The ID is automatic which is why it is not in my sql statement
currently my page is displaying not set I think it may be due to the date field as I am not sure which format it may use.
UPDATE: I changed the date in my sql statement and it still is not working, no errors coming up as well.
You can Use
$sql= "INSERT into booking (flight_id,customer_id,checkedin,checkin_datetime, booking_datetime,baggage)
VALUES ('1', '1','0','2020-10-10', '2020-10-10','30')";
$sql= "INSERT INTO booking (flight_id,customer_id,checkedin,checkin_datetime, booking_datetime,baggage)
VALUES ('1', '1','0','2010-10-20', '2010-10-20','30')";
Note :
date format: YYYY-MM-DD
All id must be exists in the database (if you use Foreign Key for flight_id and customer_id).
Date format looks ok in the sql statement.
make sure ID field is auto increment in the database as you have not used in the sql statement.

Auto Creating a Table in SQL

I wonder if someone can help?
I am new to PHP and have started creating a membership based website as a project to try and learn some new PHP and I was wondering what the correct syntax would be to auto-create a table?
Here is my current code, I am looking to create an individual table for each user however upon trying and trying I can't seem to get it to work!
Any suggestions/corrections?
<?php
require("dbconnection.php");
if(empty($_SESSION['username'])) {
header("Location: index.php");
die("Redirecting to index.php");
}
$user = $_SESSION['username'];
$sql = "CREATE TABLE $user (id int(5) NOT NULL)";
$result = mysql_query($sql);
if(!$result) {
echo "FAILED";
}
echo "CREATED";
?>
The dbconnection.php file is working correctly as all my other pages call it in order to carry out other tasks.
DO NOT DO THAT !
Why not inserting a new row in a single table that hold all data of all the users ?
$sql = "INSERT INTO users (username) VALUES ('".$sql."')";
Based on my experience, It's highly not recommendable to create each table for each user because it's very expensive in terms of space and resources. If Facebook were doing the same thing, they would be having 1.1 billion tables on their database! Instead of that they have 1 table for all these members. Use one table, then keep a Primary Key column e.g. Id to be used to identify the person. e.g.
$sql = "CREATE TABLE IF NOT EXISTS users (
id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
names VARCHAR(100),
email VARCHAR(100),
password VARCHAR(200)
)";
mysql_query($sql) or die(mysql_error());
Then as user signs up, the id column auto increments, thus he/she will have a unique Id that you can use to trace him/her, like this;
$res = mysql_query("SELECT * FROM users WHERE id ='".$id."'") or die(mysql_error());
$data = mysql_fetch_assoc($res);
echo $data['names']." ".$data['email']; /* names, email, password ... etc */
This is much better. Rather than creating 1 million tables, you can just have 1 table for all the 1 million people.
Regards!

PHP/MySQL INSERT feature logic error

I recently asked a question about writing to multiple tables: PHP/MySQL insert into multiple data tables on submit
I have now tried out this code and there are no errors produced in the actual code but the results I am getting are strange. When a user clicks register this 'insert.php' page is called and the code can be found below.
<?php
$username = $_POST["username"];
$password = $_POST["password"];
$institution = $_POST["institution"];
$conn = pg_connect("database connection information"); //in reality this has been filled
$result = pg_query($conn, "INSERT INTO institutions (i_id, name) VALUES (null, '$institution') RETURNING i_id");
$insert_row = pg_fetch_row($result);
$insti_id = $insert_row[0];
// INSTITUTION SAVED AND HAS ITS OWN ID BUT NO MEMBER OF STAFF ID
$resultTwo = pg_query($conn, "INSERT INTO staff VALUES (NULL, '$username', '$password', '$insti_id'");
$insert_rowTwo = pg_fetch_row($resultTwo);
$user_id = $insert_rowTwo[0];
// USER SAVED WITH OWN ID AND COMPANY ID
// ASSIGN AN INSTITUTION TO A STAFF MEMBER IF THE STAFF'S $company_id MATCHES THAT OF THE
// INSTITUION IN QUESTION
$update = pg_query($conn, "UPDATE institutions SET u_id = '$user_id' WHERE i_id = '$insti_id'");
pg_close($conn);
?>
What the result of this is just the browser waiting for a server response but there it just constantly waits. Almost like an infinite loop I'm assuming. There are no current errors produced so I think it may be down to a logic error. Any ideas?
The errors:
RETURNING clause is missing in the second INSERT statement.
Provide an explicit list of columns for your second INSERT statement, too.
Don't supply NULL in the INSERT statements if you want the column default (serial columns?) to kick in. Use the keyword DEFAULT or just don't mention the column at all.
The better solution:
Use data-moidifying CTE, available since PostgreSQL 9.1 to do it all in one statement and save a overhead and round trips to the server. (MySQL knows nothing of the sort, not even plain CTEs).
Also, skip the UPDATE by re-modelling the logic. Retrieve one id with nextval(), and make do with just two INSERT statements.
Assuming this data model (you should have supplied that in your question):
CREATE TABLE institutions(i_id serial, name text, u_id int);
CREATE TABLE staff(user_id serial, username text, password text, i_id int);
This one query does it all:
WITH x AS (
INSERT INTO staff(username, password, i_id) -- provide column list
VALUES ('$username', '$password', nextval('institutions_i_id_seq'))
RETURNING user_id, i_id
)
INSERT INTO institutions (i_id, u_id, name)
SELECT x.i_id, x.user_id, '$institution'
FROM x
RETURNING u_id, i_id; -- if you need the values back, else you are done
Data model
You might think about changing your data model to a classical n:m relationship.
Would include these tables and primary keys:
staff (u_id serial PRIMARY KEY, ...)
institution (i_id serial PRIMARY KEY, ...)
institution_staff (i_id, u_id, ..., PRIMARY KEY(i_id, u_id)) -- implements n:m
You can always define institution_staff.i_id UNIQUE, if a user can only belong to one institution.

Select from table, and insert data to another - Multiply data -SQL

I have a button that will delete all users that fits into this query:
DELETE FROM users WHERE lastlogin < ".time()." - ".$sdata['activitylimit']."*3600
Although, I have to take some parts of each users data, and put it into another table ("username" and "email")
How can I take the users username AND email from the table users, and insert it into my table "reserved_data"?
The table reserved_data looks like this:
id (just the id)
data (the email or username value)
type (what type of data is it((username/email)))
You can't do that directly, thanks to the table layout of the reserved_data table. Why do you do that? Why haven't you got a deleted_users table, containing their username and email? That way you could do this:
$q1 = "INSERT INTO deleted_users (username, email) SELECT username, email FROM users WHERE lastlogin < (".time()." - ".$sdata['activitylimit']." * 3600)";
$q2 = "DELETE FROM users WHERE lastlogin < (".time()." - ".$sdata['activitylimit']." * 3600)";
If you won't change the table, use something like this:
$toDelete = mysql_query("SELECT username, email FROM users WHERE lastlogin < (".time()." - ".$sdata['activitylimit']." * 3600)");
while($user = mysql_fetch_assoc($toDelete))
{
mysql_query("INSERT INTO reserved_data (`data`, `type`) VALUES ('" . $user['username'] . ", 'username'");
mysql_query("INSERT INTO reserved_data (`data`, `type`) VALUES ('" . $user['email'] . ", 'email'");
}
// Now perform the delete
mysql_query("DELETE FROM users WHERE lastlogin < (".time()." - ".$sdata['activitylimit']." * 3600)");
You see the latter requires more code and is generally a bad idea. You lose the relation between a username and its email address.
Besides, you might want to use transactions, since it's possible for one to not be included in the first query but be included in the second query. You then lose this user's data.
And perhaps you can fix all your problems by simply adding an (in)active column to your users table. One rarely wants to really delete data.
Also you can use on delete trigger to log data to reserved_data table. Just move your reserved_data insert to trigger
I would not recommend approach with deletion mark. You don't need it there is no requirement to restore deleted users and it brings quite much new problems.

PHP/SQL never updates only inserts

For some reason my insert/update check only ever inserts. the value userID does have a value so i dont know what is up with this. Any ideas?
$result = mysql_query("SELECT * FROM users where userID = $userID ");
if (mysql_num_rows($result) > 0) {
mysql_query("UPDATE users SET firstName='$firstName', lastName='$lastName',
birthday='$birthday', update='$today', accessToken='$accessToken', emailOne='$emailOne' WHERE userID='$userId'");
} else {
mysql_query("INSERT INTO users (userID, firstName, lastName, birthday, updated, accessToken, emailOne )
VALUES ('$userId', '$firstName', '$lastName','$birthday', '$today', '$accessToken', '$emailOne')");
}
You'd be far better off doing INSERT ... ON DUPLICATE KEY UPDATE. Your version is subject to race conditions. It's entirely possible that between the time you do the SELECT * and then attempt the update/insert queries, ANOTHER script has already inserted the same ID number and then your script breaks. This also reduces the database load by one query.
As well, unless you've passed all those variables in the query through mysql_real_escape_string(), you'll probably be getting a visit from Little Bobby Tables.
From the way you're inserting the records, it seems that your userId field is a varchar (or alphanumeric) field. So your query NEVER reads the data that matches it since it is searching for it as a numeric. You've got to re-write the first line as:
$result = mysql_query("SELECT * FROM users where userID = '$userID' ");
Hope it helps.

Categories