Auto Creating a Table in SQL - php

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!

Related

Update a child table based on a logged in user

firstly I apologise I am really new to PHP MySQL so if I am really off track please dont grill me!
I have a membership area and two tables. The first table is the members data and the second table will hold services that the members choose.
The table layout looks like the following:
Table: members
id = Primary Key
username
email
etc
Table: services
id = Primary Key
members_id = Foreign Key
serviceone
servicetwo
etc
What I am trying to achieve at this point is to update data into the child table based on the logged in user linked by the foreign key. My PHP looks like the following:
<?php
require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
//define page title
$title = 'Members Page';
//include header template
require('layout/header.php');
$userId = $_SESSION['id'];
if(isset($_POST['submit'])){
$sql3 = $db->prepare
("UPDATE services SET serviceone = :serviceone, servicetwo = :servicetwo WHERE members_id = :id");
$sql3->execute(array(
':serviceone' => 'variablehereoneday',
':servicetwo' => 'liketheabove',
':id' => $userId
));
}
?>
I am hoping someone may be able to point me in the right direction on how the concept of updating the child table with the logged in user looking at the primary key from the members table works.
Once again sorry if I am totally off track.
Thank you

prevent duplicate records in mysql table

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.

Create a table with a name taken from a variable in php and append a string to it

I am trying to create a table with the name taken from a variable in php.
The table name also would need to be appended with a string.
For example, $ProjectID is taking an input from an html form.
I would need to create different tables for different iterations of the project review.
So, when the project is submitted for the first time and if the project ID is 12345, a table needs to be created as P12345-1st-Review or P12345_1st_Review.
How do I do that?
I am able to create the table with the input from $ProjectID, but I am not able to append 1st_Review to it.
Any help?
The code that I have used is as below:
$ProjectID=$_POST['ProjectID'];
$sql = "CREATE TABLE $PID._1st_review (No int(4) primary key auto_increment, findings longtext);";
mysqli_query($dbconnect, $sql);
if (mysqli_error($dbconnect))
{
ECHO "Error Description:".mysqli_error($dbconnect);
}
You can always do:
$ProjectID = $_POST['ProjectID'];
$ProjectID.= "_1st_review";
Then perform the query.
Here you go.
Although I'm not sure if your query is correct(the No int thing seems vague)
<?php
$ProjectID=mysql_real_escape_string($_POST['ProjectID']); //Make sure to escape this
$sql = "CREATE TABLE ".$ProjectID."_1st_review (No int(4) PRIMARY KEY auto_increment, findings longtext);";
mysqli_query($dbconnect, $sql);
if (mysqli_error($dbconnect))
{
echo "Error Description:".mysqli_error($dbconnect);
}
?>

How to store Profile Views to show each user who's viewed their profile?

If we wanted to show each user which users of the opposite sex have viewed their profile, what would be the best way to keep track of all those views in MySQL?
Each user has a unique userid from the main Users table, which also stores their sex.
We would want to show each user the users that viewed them in order of most recent view to oldest view.
We would obviously not want to show the user themselves if they happened to view their own profile.
We would want to show guys only the girls that viewed them, and the girls only the guys that viewed them.
How would we setup the table of ProfileViews to do that?
What indexes would we use?
What would be the query we would need to show each user who has viewed them?
This is a simple example that I will make for you, hope this helps.
SQL:
CREATE TABLE user
(
user_id BIGINT NOT NULL AUTO_INCREMENT,
sex VARCHAR(10) NOT NULL,
CONSTRAINT PK_USER PRIMARY KEY (user_id)
) ENGINE=INNODB;
CREATE TABLE profileview
(
profileview_id BIGINT NOT NULL AUTO_INCREMENT,
user_id BIGINT NOT NULL,
visitor_user_id BIGINT NOT NULL,
date_time DATETIME NOT NULL,
CONSTRAINT PK_PROFILEVIEW PRIMARY KEY (profileview_id)
) ENGINE=INNODB;
ALTER TABLE profileview
ADD FOREIGN KEY FK_PROFILEVIEW_USER(user_id)
REFERENCES user (user_id);
ALTER TABLE profileview
ADD FOREIGN KEY FK_PROFILEVIEW_VISITOR(visitor_user_id)
REFERENCES user (user_id);
PHP:
This is a simple example of the user profile page - www.domain.com/profile.php?id=xxx.
At this point you need to define two variables in session when the user logs into the site:
$_SESSION['user_id'] (int) / $_SESSION['user_logged'] (boolean)
<?php
if ($_GET && isset($_GET['id']){
if(isset($_SESSION['user_id']){
$profile_user_id = $_GET['id'];
// the user that visits the profile has a session with his/her id on it.
session_start();
$visitor_user_id = $_SESSION['user_id'];
} else {
// if visitor specified an id but there is no session, redirect to login.
header("location: login.php");
}
} else {
// if no id passed redirect to index
header("location: index.php");
}
?>
<html>
<head>
<title>Your title</title>
</head>
<script src="scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
//here you will store the visit with jquery.
$(document).ready(function(){
// store the values from php.
var profile_user_id = <?php echo $profile_user_id ?>;
var visitor_user_id = <?php echo $visitor_user_id ?>;
// here, the user information goes to the visit.php file.
$.post('visit.php' { profile_user_id:profile_user_id, visitor_user_id:visitor_user_id } );
});
</script>
<body>
Here print user information from a SQL select or something of the id passed in the GET.
</body>
</html>
Now, the visit.php file to store data:
<?php
if ($_POST && isset($_POST['profile_user_id']) && isset($_POST['visitor_user_id'])) {
session_start();
// this will end the execution of the script if there is no session from user logged
if ($_SESSION['user_logged'] != true) {
exit();
}
// everything is ok, do the process:
// functions.php contains your SQL connection, I suppose you know how to do it.
include('../cgi-bin/functions.php');
$link = dbconn();
$profile_user_id = mysql_real_escape_string($_POST['profile_user_id']);
$visitor_user_id = mysql_real_escape_string($_POST['visitor_user_id']);
// this will store the data in profileview including date and time if id's are not equal.
if($profile_user_id != $visitor_user_id){
$sql = "INSERT INTO profileview (user_id, visitor_user_id, date_time) VALUES ($profile_user_id, $visitor_user_id, NOW())";
mysql_query($sql, $link);
}
}
?>
EXTRA: if you don't know what functions.php do, here it is:
<?php
function dbconn() {
if(!include_once('db.php')) {
die('Error include file.');
}
if (!$link = mysql_connect($db['hostname'],$db['username'],$db['password'])) {
die('Error connecting.');
}
if (!mysql_select_db($db['database'])) {
die('Error selecting.');
}
return $link;
}
?>
The above file will need this file too: setup here your connection parameters to your db.
db.php
<?php
$db = array(
'hostname' => 'localhost',
'username' => 'root',
'password' => 'mysql',
'database' => 'mydb'
);
?>
I suggest you to put this in the cgi-bin folder of your hosting for better practices as you can see in visit.php file code.
Now, create another file called visitors.php?id=xxx and do a select * from of your profile views according to the user_id. At this point you will be able to:
Get the user_id information and if it is men (for example)...
Select visitors by sex and do a rule to list only female visitors.
List visitors according to the time stored in profileview table.
profileviews:
profile
userwhoviewed
timestamp
Index the profile column.
So when your user views the page, check if it's the profile owner, get the sex of the profile owner, check the sex of the viewer, if different, update the table with the viewer and the timestamp.
When querying the results, just select all rows matching the target profile, ordered by timestamp desc, and iterate to build your links back to those profiles.
I normally use INT data types in these fields (keeps the rows smaller and speeds up the lookups), then have a user table that generates those UID's as an auto_increment primary key. That will hold your gender and preference fields, too, as well as any other ancillary user data, and makes it easier to change login names, if desired.
But you're leaving out your gay users. Better to just log them all and let the user filter based on their preferences. :)
UsersTable
UserID Sex
1 Boy
2 Girl
3 Girl
UsersViewsTable
UserID View Unixtimestamp
1 2 342143243432
1 3 142143243432
2 3 242143243432
3 1 442143243432
When you visite the user profile, you'll use this :
IF CurrentUserSex != UserProfileSex
INSERT INTO UsersViewsTable (UserID, View, Unixtimestamp) VALUES (CurrentUser, CurrentProfileUserID, time)
Now, you want to fetch this on a page to see last seen from opposite sex ?
SELECT * FROM UsersViewsTable LEFT JOIN UsersTable USING (UserID) WHERE Sex != CurrentUserSex GROUP BY View ORDER BY Unixtimestamp DESC
EDIT :
IF CurrentUserSex != UserProfileSex {
$Res = SELECT CurrentProfileUserID FROM UsersViewsTable WHERE UserID = CurrentUserID AND View = UserProfileID LIMIT 1
if($Res['Count'] == 1){
// Exist
UPDATE UsersViewsTable SET Unixtimestamp = time WHERE UserID = CurrentUserID AND View = UserProfileID LIMIT 1
} elseĀ {
// Doesnt exist
INSERT INTO UsersViewsTable (UserID, View, Unixtimestamp) VALUES (CurrentUser, CurrentProfileUserID, time)
}
}
Just check n compare for each user profile page with the visitor id and profile id. If two are different store in a visit table with date and time and your required info. Before inserting just check the table row
if prof id, vistor id already exists then update the time else just insert the data.
Thanks.

php/mysql creating duplicate records with multiple tables

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
)

Categories