user1994795
user1994795

Reputation: 23

how to insert data from table1 into table 2 in php

I would like to make a ranking.

Table1

Table2

I would like to collect the data via form, into Table1. Now, everybody have to write the XP, and LvL.

It would be better, if they post the XP, and the LvL automatically come from Table2.

I insert datas into table with this:

$mysql ="INSERT INTO $table (id, name, xp, lvl) VALUES ('$id','$name','$xp','$lvl')";

And select the lvl with this:

$query="select id from table2 where $lvl>=$xp LIMIT 0 , 1";

But how can I join the selection, and put it in the insert?

Upvotes: 1

Views: 1077

Answers (1)

John Woo
John Woo

Reputation: 263723

use INSERT...INTO SELECT statement

INSERT  INTO table1 (ID, Name, ExperiencePoint, Lvl)
SELECT  '$id' AS ID, '$name' AS Name, 
        '$xp' AS ExperiencePoint, Lvl
FROM    table2
WHERE   ExperiencePoint = '$xp'

As a sidenote, the query is vulnerable with SQL Injection if the value(s) came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

Upvotes: 1

Related Questions