Printing out 25 most recently added tables - php

In the code below, I allow users to add tables to a MySQL database. Is there a way to print out the most recent 25 tables added?
Thanks in advance,
John
$table = mysql_real_escape_string($_POST['name']);
$query = "CREATE TABLE `$table` (id INT(11) NOT NULL auto_increment, site VARCHAR(350) NOT NULL, cat1 BIGINT(9) NOT NULL, cat2 BIGINT(9) NOT NULL, PRIMARY KEY(id), UNIQUE (site))";
$result = mysql_query($query) or die(mysql_error());

select TABLE_NAME
from INFORMATION_SCHEMA.TABLES
where TABLE_SCHEMA='your_db_name`
order by CREATE_TIME desc
limit 25
This is for MySQL version 5 and above. It will list tables created by your users and you, though.

You can but I'd advise creating a history or audit table of all the table creations (and other relevant activity). For example:
$now = time();
$user = $_SESSION['user'];
$sql = <<<END
INSERT INTO table_history
(table, user, action, action_time)
VALUES
('$table', '$user', 'CREATE', $now)
END;
mysql_query($sql) or die($sql . ': ' . mysql_error());
Also, I'd probably suggest not creating a separate table for each instance you need to use it unless they're going to be really large. Creating another column to identify the user, organization or whatever is often (but not always) a better approach.

Related

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.

Getting the last id from empty mysql table [duplicate]

How to get the next id in mysql to insert it in the table
INSERT INTO payments (date, item, method, payment_code)
VALUES (NOW(), '1 Month', 'paypal', CONCAT("sahf4d2fdd45", id))
You can use
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'table_name'
AND table_schema = DATABASE( ) ;
or if you do not wish to use information_schema you can use this
SHOW TABLE STATUS LIKE 'table_name'
You can get the next auto-increment value by doing:
SHOW TABLE STATUS FROM tablename LIKE Auto_increment
/*or*/
SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = 'tablename'
Note that you should not use this to alter the table, use an auto_increment column to do that automatically instead.
The problem is that last_insert_id() is retrospective and can thus be guaranteed within the current connection.
This baby is prospective and is therefore not unique per connection and cannot be relied upon.
Only in a single connection database would it work, but single connection databases today have a habit of becoming multiple connection databases tomorrow.
See: SHOW TABLE STATUS
This will return auto increment value for the MySQL database and I didn't check with other databases. Please note that if you are using any other database, the query syntax may be different.
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'your_table_name'
and table_schema = 'your_database_name';
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'your_table_name'
and table_schema = database();
The top answer uses PHP MySQL_ for a solution, thought I would share an updated PHP MySQLi_ solution for achieving this. There is no error output in this exmaple!
$db = new mysqli('localhost', 'user', 'pass', 'database');
$sql = "SHOW TABLE STATUS LIKE 'table'";
$result=$db->query($sql);
$row = $result->fetch_assoc();
echo $row['Auto_increment'];
Kicks out the next Auto increment coming up in a table.
In PHP you can try this:
$query = mysql_query("SELECT MAX(id) FROM `your_table_name`");
$results = mysql_fetch_array($query);
$cur_auto_id = $results['MAX(id)'] + 1;
OR
$result = mysql_query("SHOW TABLE STATUS WHERE `Name` = 'your_table_name'");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];
Use LAST_INSERT_ID() from your SQL query.
Or
You can also use mysql_insert_id() to get it using PHP.
Solution:
CREATE TRIGGER `IdTrigger` BEFORE INSERT ON `payments`
FOR EACH ROW
BEGIN
SELECT AUTO_INCREMENT Into #xId
FROM information_schema.tables
WHERE
Table_SCHEMA ="DataBaseName" AND
table_name = "payments";
SET NEW.`payment_code` = CONCAT("sahf4d2fdd45",#xId);
END;
"DataBaseName" is the name of our Data Base
Simple query would do
SHOW TABLE STATUS LIKE 'table_name'
For MySQL 8 use SHOW CREATE TABLE to retrieve the next autoincrement insert id:
SHOW CREATE TABLE mysql.time_zone
Result:
CREATE TABLE `time_zone` (
`Time_zone_id` int unsigned NOT NULL AUTO_INCREMENT,
`Use_leap_seconds` enum('Y','N') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'N',
PRIMARY KEY (`Time_zone_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1784 DEFAULT CHARSET=utf8 STATS_PERSISTENT=0 ROW_FORMAT=DYNAMIC COMMENT='Time zones'
See the AUTO_INCREMENT=1784 at the last line of returned query.
Compare with the last value inserted:
select max(Time_zone_id) from mysql.time_zone
Result:
+-------------------+
| max(Time_zone_id) |
+-------------------+
| 1783 |
+-------------------+
Tested on MySQL v8.0.20.
SELECT id FROM `table` ORDER BY id DESC LIMIT 1
Although I doubt in its productiveness but it's 100% reliable
You have to connect to MySQL and select a database before you can do this
$table_name = "myTable";
$query = mysql_query("SHOW TABLE STATUS WHERE name='$table_name'");
$row = mysql_fetch_array($query);
$next_inc_value = $row["AUTO_INCREMENT"];
I suggest to rethink what you are doing. I never experienced one single use case where that special knowledge is required. The next id is a very special implementation detail and I wouldn't count on getting it is ACID safe.
Make one simple transaction which updates your inserted row with the last id:
BEGIN;
INSERT INTO payments (date, item, method)
VALUES (NOW(), '1 Month', 'paypal');
UPDATE payments SET payment_code = CONCAT("sahf4d2fdd45", LAST_INSERT_ID())
WHERE id = LAST_INSERT_ID();
COMMIT;
You can't use the ID while inserting, neither do you need it. MySQL does not even know the ID when you are inserting that record. You could just save "sahf4d2fdd45" in the payment_code table and use id and payment_code later on.
If you really need your payment_code to have the ID in it then UPDATE the row after the insert to add the ID.
What do you need the next incremental ID for?
MySQL only allows one auto-increment field per table and it must also be the primary key to guarantee uniqueness.
Note that when you get the next insert ID it may not be available when you use it since the value you have is only within the scope of that transaction. Therefore depending on the load on your database, that value may be already used by the time the next request comes in.
I would suggest that you review your design to ensure that you do not need to know which auto-increment value to assign next
use "mysql_insert_id()". mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.
Below are the example of use:
<?php
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable VALUES('','value')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
I hope above example is useful.
If return no correct AUTO_INCREMENT, try it:
ANALYZE TABLE `my_table`;
SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE (TABLE_NAME = 'my_table');
This clear cache for table, in BD
using the answer of ravi404:
CREATE FUNCTION `getAutoincrementalNextVal`(`TableName` VARCHAR(50))
RETURNS BIGINT
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE Value BIGINT;
SELECT
AUTO_INCREMENT INTO Value
FROM
information_schema.tables
WHERE
table_name = TableName AND
table_schema = DATABASE();
RETURN Value;
END
using in your insert query, to create a SHA1 Hash. ex.:
INSERT INTO
document (Code, Title, Body)
VALUES (
sha1( getAutoincrementalNextval ('document') ),
'Title',
'Body'
);
Improvement of #ravi404, in case your autoincrement offset IS NOT 1 :
SELECT (`auto_increment`-1) + IFNULL(##auto_increment_offset,1)
FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = your_table_name
AND table_schema = DATABASE( );
(auto_increment-1) : db engine seems to alwaus consider an offset of 1. So you need to ditch this assumption, then add the optional value of ##auto_increment_offset, or default to 1 : IFNULL(##auto_increment_offset,1)
For me it works, and looks simple:
$auto_inc_db = mysql_query("SELECT * FROM my_table_name ORDER BY id ASC ");
while($auto_inc_result = mysql_fetch_array($auto_inc_db))
{
$last_id = $auto_inc_result['id'];
}
$next_id = ($last_id+1);
echo $next_id;//this is the new id, if auto increment is on
SELECT AUTO_INCREMENT AS next_id FROM information_schema.tables WHERE table_name = 'table name' AND table_schema = 'database name of table name'
mysql_insert_id();
That's it :)

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!

Too many MySQL queries?

I have a question if anyone can answer. Please excuse my inexperience with this, but this is my first project that I have attempted and all of this is really new to me. I am in the process of trying to build an inventory system at work using php and mySQL and I have hit a bit of a wall regarding how I am going to display the items that are currently loaned out to people.
I have the items that are being provisioned to users broken down into 4 categories and records of the loans for these items are stored into 4 different tables. I also have another table for users, as well as tables for the items, and their characteristics.
What I want when my page is displayed to to have all of the items that are assigned to each user grouped together in a table. I have two ideas on how I can do this, but I'm not sure which would be the best way.
My first thought was to pull all of the users from the users table and store the information into an array, then pull all of the information from the 4 loan tables and store each table into an array. From there I would do something like
for($i=1;$i>sizeof($usersArray);$i++){
for($a=1;$a>sizeof($loanTable1Array);$a++){
if($userArray[$i][userID] == $loanTable1Array[$a][userID]{
//list items
}
}
for($b=1;$b>sizeof($loanTable2Array);$b++){
if($userArray[$i][userID] == $loanTable2Array[$b][userID]{
//list items
}
}
for($c=1;$c>sizeof($loanTable3Array);$c++){
if($userArray[$i][userID] == $loanTable3Array[$c][userID]{
//list items
}
}
for($d=1;$d>sizeof($loanTable4Array);$d++){
if($userArray[$i][userID] == $loanTable4Array[$d][userID]{
//list items
}
}
}
My concern with this though is that I will have around 100-150 users and each table will have an average of 100 different items. This would mean around 40,000 - 60,000 iterations of the loop.
My other idea was to do pull all of the entries from the user table, then use that data to query the other 4 tables using the userID in a where statement like this. But then I read that if you have a query in a loop then you're doing it wrong.
$sql = "SELECT userID FROM users";
$allUsers = runQuery($sql); //data is sanitized before running the query
for($i = 1; $i<sizeof($allUsers); $i++){
$loan1sql = "SELECT * FROM loantable1 WHERE userID = {$allUsers[$i][$userID]}'";
$loan1Items= runQuery($loan1sql);
for($a = 1; $a<sizeof($loan1Items); $a++){
//list items
}
$loan2sql = "SELECT * FROM loantable2 WHERE userID = '{$allUsers[$i][$userID]}'";
$loan2Items= runQuery($loan2sql);
for($b = 1; $b<sizeof($loan2Items); $b++){
//list items
}
$loan3sql = "SELECT * FROM loantable3 WHERE userID = '{$allUsers[$i][$userID]}'";
$loan3Items= runQuery($loan3sql);
for($c = 1; $c<sizeof($loan3Items); $c++){
//list items
}
$loan4sql = "SELECT * FROM loantable4 WHERE userID = '{$allUsers[$i][$userID]}'";
$loan4Items= runQuery($loan4sql);
for($d = 1; $d<sizeof($loan1Items); $d++){
//list items
}
}
Doing this would result in 400 - 600 calls to the database each time the page is loaded. Does anyone have any input on what my best course of action would be? Any help would be greatly appreciated.
By considering an extra category column , you could have one loantable instead of four . Then you would just use one query by JOINing the tables .
Just an example showing one way to do it :
-- Table structure for table `users`
CREATE TABLE IF NOT EXISTS `users` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`userID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
-- Dumping data for table `users`
INSERT INTO `users` (`userID`) VALUES
(1),
(2);
-- --------------------------------------------------------
-- Table structure for table `loantable`
CREATE TABLE IF NOT EXISTS `loantable` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`category` int(11) NOT NULL,
`userID` int(11) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
-- Dumping data for table `loantable`
INSERT INTO `loantable` (`ID`, `category`, `userID`) VALUES
(1, 1, 1),
(2, 2, 1),
(3, 3, 1),
(4, 1, 2),
(5, 3, 2);
Then you would use just one query like :
SELECT *
FROM
`users`
LEFT OUTER JOIN loantable ON loantable.userID = users.userID
WHERE 1
ORDER BY
users.userID
,category
(refer to answers above. This was too long to add as a comment, but I thought it would be helpful)
#cartalot and #Uours THANK YOU!!!! - I had considered creating one table for all of the loans early on but didn't know how to implement it. This makes perfect sense though. My whole issue was confusing the foreign key - parent key constraints in mySQL with how you can actually join tables to display information on your page.
Not to sound like a complete moron, but I think this might be constructive to someone that reads this down the road. I got confused by how you can create fk - pk relations in myPHPAdmin and what they actually do. I though that these relations were necessary to join tables (obviously wrong). I saw the visual connections and though that these tables were somehow "connected".
I know understand that when you create a foreign key parent key restraints all you are basically doing is limiting they data that you can enter into a table based on what is in another table. You can still join information from different tables without these constraints.

MySQL, PHP many-to-many relationship

I've got a many-to-many relationship between Person and Interests. This means that I had to create a middle table called person_interests.
The Person table was created using:
create table if not exists Person
(
id int not null auto_increment primary key,
username varchar(10) not null,
name varchar(40) not null,
gender varchar(6) not null,
dateOfBirth timestamp not null,
signUpDate timestamp not null,
email varchar(40) not null
);
The interests table was created using:
create table if not exists interests
(
id int not null auto_increment primary key,
interestName varchar(10) not null
);
insert into interests(id, interestName)
values
(1, 'sport'),
(2, 'computer'),
(3, 'dancing'),
(4, 'boating'),
(5, 'car');
and person_interests was created using:
create table if not exists person_interests
(
id int not null auto_increment primary key,
UserID int not null,
foreign key (UserID) references Person(id),
Interestid int not null,
foreign key (Interestid) references interests(id)
);
I'm trying to select entries from the person_interests table but with no luck. My PHP function for doing this is:
function get_person_interests($id)
{
$connection = mysql_open();
$query = "select pi.UserID, i.interestName from interests as i, person_interests as pi, where i.id = pi.interestid";
$result = mysql_query($query, $connection) or show_error();
$person_interests = array();
while($person_interest = mysql_fetch_array($result))
{
$person_interests = $person_interest;
}
mysql_close($connection) or show_error();
return $person_interests;
}
But this doesn't work! This is what my template (user_detail.tpl) looks like:
{foreach $interests as $interest}
<li>{$interest.interestName}</li>
{/foreach}
and this is what my user_detail.php looks like:
$id = $_GET['id'];
$Person = get_person($id);
$interests = get_person_interests($id);
$smarty = new Smarty;
$smarty->assign("Person", $Person);
$smarty->assign("interests", $interests);
$smarty->display("user_detail.tpl")
I'm trying to display the interests that the user chose upon signup. They are stored in the person_interests table. Every time I try to go to the user_detail.php page it gives me this error:
Error 1064 : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where i.id = pi.interestid' at line 1
If anybody can help me then that would be much appreciated!
SQL syntax error. You shouldn't have a comma before the where clause. I would suggest that you write your query as a join though:
$query = "select pi.UserID, i.interestName from person_interests as pi join interests as i on i.id = pi.interestid";
Of course, if you want the interests of a particular person (Which your code suggests), you need to filter on the user_id:
$query = "select pi.UserID, i.interestName from person_interests as pi join interests as i on i.id = pi.interestid where pi.UserID =" . mysql_escape_string($id);
In reply to your comment:
I think you want to replace this line:
$person_interests = $person_interest;
With:
$person_interests[] = $person_interest;
Looks like a typo. You have "Interestid" in your table, but "interestid" in your query. Note the case difference. And you have a comma after your where. You should rewrite this using a join by doing:
select
pi.UserId,
i.interestname
from
person_interests pi
left join
interests i
on
pi.Interestid = i.id
You have an error in your SQL query which you should debug first.
Connect to your database with a commandline client (the command is named mysql).
Then write the SQL query in a text editor. Then copy the query and paste it into the commandline client to run it.
The commandline client will always tell you where the error is. You can then read the SQL statement in the MySQL manual and look where you've made a syntax error or something similar.
Then you can adopt the query in your editor accordingly and try again.
Repeat until your query has no error any longer and gets you the expected results.
Then copy the working query into your application and replace the invariants with the variables. Take care that you properly escape the values.

Categories