Log in

View Full Version : moving data from one table to another



jnrng
06-24-2014, 06:12 AM
I am new to php, mysql, I have 2 tables (table1 and table2) and wish to move data from table1 to table2 such that when a user filled in a reg_number in the form field and clicks the submit button it executes the code and opens a fresh page named "register.php.

I am having problem with this code as it fails to execute and returning blank page. Please help me in resolving this problem.
here is the form:


<form action="discharge.php" method="post">
<p>INSERT STUDENT'S REGISTRATION NUMBER
<input type="text" name="reg_number" value="">
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>

and
here is my discharge.php code:

<?php

include('connect.php');

// username and password sent from form
$reg_number=$_POST["reg_number"];

$sql="INSERT INTO table2 (reg_number, surname,first_name, othername, gender)
SELECT reg_number, surname,first_name, othername, gender FROM table1 WHERE reg_number='$reg_number'";

DELETE * FROM table1 WHERE reg_number='$reg_number'";
$result=mysql_query($sql);
if(!$result)
{
header ("location:register.php");
}


?>

Thurrock
07-11-2014, 10:14 AM
I wouldnt nest the select query as you cant really error trap that I would rather do the query and if there is a result do the insert, if the insert happens do the delete, all the way through you can have three error traps

if select {great} else {error}
if insert {great} else {error}
if delete {great} else {error}

this will allow you to see at what stage your script is failing and stop the blank screen of unknown you have

I also say that you should never pass a variable into an SQL query directly without sanitizing it first:

$reg_number=$_POST["reg_number"]; //This is Dirty and vulnerable

//You can imagine someone putting a nested mysql query into your form field and dropping or truncating your tables, disaster.

$reg_number=mysql_real_escape_string($_POST["reg_number"]); //Slightly better...

//if the reg_number is always going to be a number you could validate using is_numeric(); this would help stop nested queries

if (is_numeric($reg_number)) {
//Do the mysql stuff because it is safe to do so
}
else
{
//redirect back to try again or just echo error message and then exit;
}


Hope this helps and does not confuse things too much