I'm trying to insert into several related database tables some data after clicking a submit button, my tables are:
USERS: ID (primary key), User, Name, Password
LEVELS: ID, User_ID (foreign key), Level1, Level2, Level3, Level4
where User_ID on the table levels is the same ID as the primary key for users.
I want to make this insert with php, my code is as follows:
$host="xxxxxx"; // Host name
$username="xxxxxx"; // Mysql username
$password="xxxxxx"; // Mysql password
$db_name="xxxxxx"; // Database name
$tbl_name="USERS"; // Table name
// Connect to server and select databse.
$dbh= mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// sent from form
$name=$_POST["name"];
$user=$_POST["user"];
$password=$_POST["password"];
$L4=$_POST["L4"];
$L3=$_POST["L3"];
$L2=$_POST["L2"];
$L1=$_POST["L1"];
$sql="INSERT INTO $tbl_name (Name, User, Password) VALUES('$name','$user','$password');";
$userid = mysql_insert_id();
$tab1= mysql_query($sql, $dbh) or die ("problem query 1");
$sql2 = "INSERT INTO LEVELS (User_ID, Level1, Level2, Level3, Level4) VALUES('$userid','$L1','$L2','$L3','$L4');";
$tab2= mysql_query($sql2, $dbh) or die ("problem query 2");
either, I don't get how to relate the tables, or something here is wrong, cause only the first sql statement is being executed, and the second one prints the die 'problem query 2'.
Can anybody please help me?
Thanks!
$userid = mysql_insert_id();
should be called after the insert query is executed and in your case you are calling it before the first query being executed.
So it should be as
$sql="INSERT INTO $tbl_name (Name, User, Password) VALUES('$name','$user','$password');";
$tab1= mysql_query($sql, $dbh) or die ("problem query 1");
$userid = mysql_insert_id();
Related
My registration on my website does not seem to be inserting the registration details of users into the database correctly. The table consists of 2 fields (ID & PASSWORD, ID being a 9 digit int). When ever i enter in a ID and PASSWORD, in my table it shows up as a single digit number and will increment by 1 everytime i enter another record via my registration form. It essentially resets the ID i inserted through the form to a incremental number.
Below is my code:
<?php
$host="********"; // Host name
$username="******"; // Mysql username
$password="*********"; // Mysql password
$db_name="arihealthinfo"; // Database name
$tbl_name="USERS"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$ParticipantID=$_POST["ParticipantID"];
$password=$_POST["UserPass"];
$sql = "INSERT INTO USERS (ID, PASSWORD) VALUES ('$participantID', '$password')";
mysql_query($sql);
echo "Thank you for registering, you can now login:";
?>
<a href= http://www.arihealth.info/index.php>Login Page.</a>
<?php
?>
PASSWORD is a reserved mysql keyword.
Try using this query instead with using backticks
$sql = "INSERT INTO `USERS` (`ID`, `PASSWORD`) VALUES ('$participantID', '$password')";
and it should work like expected.
Edit: The answer is simple, my bad on the keyword thing and not being able to comment yet on questions.
You made a typo:
$ParticipantID=$_POST["ParticipantID"];
$sql = "INSERT INTO USERS (ID, PASSWORD) VALUES ('$participantID', '$password')";
See the capital P on the variable?
I'm having a issue with an insert statement. It should transfer a row of data from one table to another upon clicking a link from a table from that specified row.
At the minute the only field being inserted into the other table is the reference.
In other words I want to retrieve a person's name and details from a row in one table which corresponds to a unique reference number and move it to the next table in the process.
Table Page.php
<td align="center">Refer for Triage</td>
<td align="center">Refer for IA</td>
Script.php - action page
require_once('auth.php');
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="sysadmin"; // Mysql password
$db_name="Elite"; // Database name
$tbl_name="Instruction"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$Reference=$_REQUEST['Reference'];
$Forename=$_REQUEST['Forename'];
$surname=$_REQUEST['surname'];
$DOB=$_REQUEST['DOB'];
$Mobile=$_REQUEST['Mobile'];
$Home=$_REQUEST['Home'];
$Address=$_REQUEST['Address'];
$Postcode=$_REQUEST['Postcode1'];
$Email=$_REQUEST['Email'];
$Accident=$_REQUEST['Accident'];
$Details=$_REQUEST['Details'];
//semi colon removed
$sql="INSERT INTO
Triage
(
Reference,
Forename,
surname,
`D.O.B`,
`Mobile Number`,
`Home Number`,
Address,
Postcode1,
Email,
Accident,
Details
)
VALUES
(
'".$Reference."',
'".$Forename."',
'".$surname."',
'".$DOB."',
'".$Mobile."',
'".$Home."',
'".$Address."',
'".$Postcode1."',
'".$Email."',
'".$Accident."',
'".$Details."'
)";
$result=mysql_query($sql);
// echo "Successful";
// echo "<BR>";
// echo "<a href='list_records.php'>View result</a>";
// mysql_error()
echo $sql
?>
Pretty new to PHP and MySQL.
I have created an insert statement in my php script, to transfer a row of data from one table to the next for certain fields. Only thing is, it doesn't seem to be working?
Can anybody see where the issue is?
<?php
require_once('auth.php');
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="Instruction"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$Reference=$_REQUEST['Reference'];
$Forename=$_REQUEST['Forename'];
$surname=$_REQUEST['surname'];
$DOB=$_REQUEST['DOB'];
$Mobile=$_REQUEST['Mobile'];
$Home=$_REQUEST['Home'];
$Address=$_REQUEST['Address'];
$Postcode=$_REQUEST['Postcode1'];
$Email=$_REQUEST['Email'];
$Accident=$_REQUEST['Accident'];
$Details=$_REQUEST['Details'];
//semi colon removed
$sql="INSERT INTO Triage (Reference,Forename,surname,D.O.B,Mobile Number,Home Number,Address,Postcode1,Email,Accident,Details)
VALUES('.$Reference.','.$Forename.','.$surname.','.$DOB.','.$Mobile.','.$Home.','.$Address.','.$Postcode1.','.$Email.','.$Accident.','.$Details.')";
$result=mysql_query($sql);
echo "Successful";
echo "<BR>";
echo "<a href='list_records.php'>View result</a>";
?>
You have column names like Mobile Numbe etc, you need to use `` for them also the concatenation does not look correct you should have something as
sql="INSERT INTO
Triage
(
Reference,
Forename,
surname,
`D.O.B`,
`Mobile Number`,
`Home Number`,
Address,
Postcode1,
Email,
Accident,
Details
)
VALUES
(
'".$Reference."',
'".$Forename."',
'".$surname."',
'".$DOB."',
'".$Mobile."',
'".$Home."',
'".$Address."',
'".$Postcode1."',
'".$Email."',
'".$Accident."',
'".$Details."'
)";
In addition you should use mysql_real_escape_string() for all the request data something as
$Reference=mysql_real_escape_string($_REQUEST['Reference']);
and so on for others
I have a PHP form that should insert data into my SQL database on hostgator. However it is not adding any data but the id field keeps incrementing. I do not receive any error message when submitting the form and when i go to the database the other fields are just empty thus not displaying any data.
I am pulling my hair and cant figure out what the problem is. Can someone please help me
Thanks
<?php
$host="localhost"; // Host name
$username="xxxxxx"; // Mysql username
$password="xxxxxx"; // Mysql password
$db_name="rob1124_inventory"; // Database name
$tbl_name="data"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$qty=$_POST['qty'];
$product=$_POST['product'];
$price=$_POST['price'];
$totalprice=$_POST['totalprice'];
$seller=$_POST['seller'];
$city=$_POST['city'];
// Insert data into mysql
$sql="INSERT INTO $tbl_name(qty, product, price, totalprice, seller,city)
VALUES('$qty', '$product', '$price', '$totalprice', '$seller', '$city')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
Change to utf-8 from all varchar fields of your table and
try to get mysql_error().
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
mysql_query("set names 'utf8'");
//You codes....
// Insert data into mysql
$sql="INSERT INTO $tbl_name(qty, product, price, totalprice, seller,city)
VALUES('$qty', '$product', '$price', '$totalprice', '$seller', '$city')";
$result=mysql_query($sql) or die(mysql_error());
//Your codes...
Since the id is incrementing atleast the form and the DB connect, it tries to enter data.
One usually occurring error is that the data types in the databases columns don't match with the type of data recieved. Like trying to insert chars into ints etc. Or the length of the data is to large for the assigned size in the database. Check to see that the types are correct and try again.
But still, those that are correct should be inserted. Hard to tell without knowing more about the database design.
I have the below code that i am wanting to into certain files so that when someone visits this "certain" file they get banned if they are not allready. but for some reason it is not adding new visitors into the database, if i add a user manually it works fine and echo's Banned! but otherwise it just echo's the $sql query but does not actually do it.
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="banlist"; // Database name
$tbl_name="list"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$sql="SELECT * FROM $tbl_name WHERE ip='$ip'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if ($count==0){
$sql="INSERT INTO $tbl_name (`id` ,`ip`) VALUES (NULL , $ip)";
mysql_query($sql);
echo $sql;
//header("location:index.html");
} else {
// Register $myusername, $mypassword and redirect to file "login_success.php"
//header("location:index.html");
echo "banned!";
exit();
}
?>
Have you double-checked that your MySQL account has the INSERT privilege?
You'll also find that things go more smoothly if you always check the return value of mysql_query(). While you're developing, you could change these lines (from the end of your snippet):
mysql_query($sql);
echo $sql;
... to this:
$result = mysql_query($sql);
if($result === FALSE) {
echo 'INSERT failed with this error: '.mysql_error();
} else {
echo 'INSERT succeeded';
}
Also if you're not yet familiar with SQL injection, you'll want to become familiar with it. Your code is currently vulnerable to this kind of attack, because it doesn't filter input (the HTTP headers where you're looking for an IP address) and it doesn't escape output (the variable portion of your dynamically-constructed SQL queries).
just few remarks
$sql="SELECT * FROM $tbl_name WHERE ip='$ip'";
$result=mysql_query($sql);
wouldn't be better to do a
$sql="SELECT count(*) FROM $tbl_name WHERE ip='$ip'";
$result=mysql_query($sql);
since you don't use that data.
$sql="INSERT INTO $tbl_name (`id` ,`ip`) VALUES (NULL , '$ip')";
mysql_query($sql);
if your id is an auto increment you don't have to include it
$sql="INSERT INTO $tbl_name (`ip`) VALUES ('$ip')";
mysql_query($sql);
You should quote $ip since it's probably a varchar in your table.
Since an ip address should be a sort of unique identifier you have better to use the IP as primary key.
last point checking for results of mysql_query would be a good pratice, like there
$sql="INSERT INTO $tbl_name (`ip`) VALUES ($ip)";
$ret = mysql_query($sql);
if (!$ret) {
die('Invalid query: ' . mysql_error());
}
I think it would give you valuable information about what is happening. in that case it would probably say you have an error near the IP address (because of the missing quotes).