modifying tables in my database - php

I have database with a table called members, which stores data for my admin,client,technicians all in one.But now I want to break this table into three separate tables as admin table,client table and techs table.As I have now written queries based on the members table I want to keep the common fields which were used in queries in the members table as they are now.Therefore I reduced the members table only to have fields ID,Name,UserName,Password,Level,Category.Throughout the site it is recognized if the user is a admin,client,or technician by setting levels(which corresponds to Level field).
When inserting data I tried using this code.First insert the common fields to members and then depending on the level write separate queries specifying to which table should data be inserted.
if($_POST['Submit']){
if(mysql_fetch_array(mysql_query("SELECT * FROM `members` WHERE UN='$r[UN]' AND ID!='$r[ID]' "))) {
?><script language="javascript" type="text/javascript">alert('Username already exsits.Please enter another.');
</script>
<?php
}
else {
mysql_query("INSERT INTO members (Name,UN,Password,Level,Category) VALUES ('$r[Name]','$r[UN]','$r[PW]','$r[Level]','$r[Category]')");
$row=mysql_query("SELECT * FROM members WHERE Name='$r[Name]'") or die('query unsuccesful');
if ($row['Level']==1){
mysql_query("INSERT INTO client(Name,Mobile,Phone,Fax,Email,Address) VALUES ('$r[Name]','$r[Mobile]','$r[Phone]','$r[Fax]','$r[Email]','$r[Address]')");
}
elseif($row['Level']==2){
mysql_query("INSERT INTO techs (Name,,Category,Company,Price,Comments,Rate,Qualifications,Mobile,Phone,Fax,Email,Address) VALUES ('$r[Name]','$r[Category]','$r[Company]','$r[Price]','$r[Comments]','$r[Rate]','$r[Qualifications]','$r[Mobile]','$r[Phone]','$r[Fax]','$r[Email]','$r[Address]')");
}
else{
mysql_query("INSERT INTO admin (Name,Mobile,Phone,Fax,Email,Address) VALUES ('$r[Name]','$r[Mobile]','$r[Phone]','$r[Fax]','$r[Email]','$r[Address]')");
}
if(!$user){
$user=$r;
$_SESSION['user']=$r;
}
But data gets inserted only to members table and nothing goes for client,techs or admin.Any idea how I can mend this please

You are not fetching data on the 2nd select.
$row=mysql_query("SELECT * FROM members WHERE Name='$r[Name]'") or die('query unsuccesful');
if(mysql_fetch_array($row)) {... }

Related

Mysqli insert into multiple table with auto increment

hello i tried using mysqli to fetch autoincrement id from the first table to insert it for second table, this is my database design for each table
Table users
id_user PK auto-inc
username
password
nama
role
status
table siswa
id_siswa PK auto-inc
id_tingkatan
nama_siswa
jk_siswa
hp_siswa
nama_ortu
jk_ortu
hp_ortu
id_user
this is what i have tried
$query = "INSERT INTO users
(username, password, nama, role, status)
VALUES ('$name','$password','$nama','$role','$status')";
$koneksi->query($query);
$query = "INSERT INTO siswa
(id_tingkatan, nama_siswa, jk_siswa, hp_siswa,
nama_ortu, jk_ortu, hp_ortu, id_user)
VALUES ('$tingkatan','$nama','$jksiswa','$hpsiswa',
'$namaortu','$hportu', $koneksi->insert_id)";
$koneksi->query($query);
the data is inserted into users table but not to siswa table, any suggestion to fix this?
edit : overlooked variable only ($jkortu) fixed now, thanks
In the latter INSERT, the number of items in the first commalist does not correspond with the number of items in the second commalist. This should throw a syntax error.
You are missing a parameter.
You should always test for mysql errors, otherwise it will fail silently, and you have no idea what is going on:
if (!$server->query($query)) {
throw new Exception($server->error());
}

PHP Creating entries in different tables

I'm currently working on a project and stuck with something.
I am looking for a way to join two different tables. When you create an entry in one table, it will automatically create an entry in another table.
For example lets say I am creating new patients for a system. When I input all data in to the form and click submit, all of the data is then stored in the patients table under the unique patient id.
Now where I have created a row for Bob in the patients table, I would like for it to also create a row for Bob in the accounting table. So that the accounting data would be tied with the patient data.
So when I submit for a new patient, I would it to also create a new row in the accounting table that can refer to the patient it's created for.
I am not sure if I made my question clear..
EDIT:
Thanks for all the help! I managed to get it up and working with the following..
<?
session_start();
include "database_connect.inc";
$sql="INSERT into patients SET patient_fname='".addslashes($_POST['fname'])."',
patient_initial='".$_POST['initial']."',
patient_lname='".addslashes($_POST['lname'])."',
address='".addslashes($_POST['address'])."',
city='".addslashes($_POST['city'])."',
state='".$_POST['state']."',
zipcode='".$_POST['zip']."',
phone1label='".$_POST['phone1label']."',
phone1='".$_POST['phone1']."',
phone2label='".$_POST['phone2label']."',
phone2='".$_POST['phone2']."',
phone3label='".$_POST['phone3label']."',
phone3='".$_POST['phone3']."',
phone4label='".$_POST['phone4label']."',
phone4='".$_POST['phone4']."',
dateofinjury='".$_POST['dateofinjury']."',
office_location='".$_POST['officelocation']."',
law_office1='".$_POST['lawoffice1']."',
law_office2='".$_POST['lawoffice2']."',
insurance1='".$_POST['insurance1']."',
pip='".$_POST['pip']."',
claim1='".$_POST['claim1']."',
insurance3='".$_POST['insurance3']."',
claim3='".$_POST['claim3']."'";
$result = mysql_query($sql,$cn);
if (!$result) die("ERROR - Query failed while trying to add a new patient record!<br>".$sql);
$sql="INSERT INTO accounts (patient_id,patient_name,patient_lname) VALUES(LAST_INSERT_ID(),'".$_POST['fname']."','".$_POST['lname']."')";
if (!mysql_query($sql,$cn))
{
die('Error' . mysql_error());
}
header("location:createpatient.php");
?>
Based on your question, I prefer suggest you this concept:
example:
table1 name: patients
table2 name: accounting
indicator:
patient_id in patients table1
accounting_id in accounting table2
then, let's do it!:
<?php
$sql="INSERT INTO patients (patient_fname, ...)
VALUES ('$_POST[patient_fname]','....')";
mysql_query($sql);
if (!mysql_query($sql,$cn))
{
die('Error' . mysql_error());
}
$getIdInTable1 = mysql_query("SELECT LAST_INSERT_ID() AS patient_id
FROM patients");
$setID = mysql_fetch_assoc($getIdInTable1);
$sql="INSERT INTO accounting (patient_id, ....)
VALUES ({$setID['accounting_id']}, '$_POST['patient_id']','....')";
if (!mysql_query($sql,$cn))
{
die('Error' . mysql_error());
}
mysql_close($db_server);
header("location:createpatient.php");
exit();
?>
'Hope this really help you.
At first give it a try, then ask where you get actually stuck.
If i were you, i would try something like this.
BEGIN;
INSERT INTO patients(name,details)
VALUES('test', 'test');
INSERT INTO patient_profiles (patient_id, information)
VALUES(LAST_INSERT_ID(),'something useful');
COMMIT;
Please refer some manual.
it s better than You use a manual progressive max code to join tables instead of id

import data from one table and insert it into another

I have two tables product_myob and products. What I want to do is to import products from product_myob when the import button is clicked to table products. Table products already contains some products.
I try to execute below query but the table is not updated. Please help me with the code.
INSERT INTO products(myob_id, myob_displayID, Name)
SELECT UID,displayID,itemName
FROM product_myob
WHERE UID NOT IN (SELECT myob_id from products);
It seems there is a unique check on your products table and you are inserting some duplicate data if this is the case then you can ignore duplicate values by below query, even you don't need to check UID in product table as this query automatically ignore it. Other wise elaborate your question:
INSERT ignore INTO products(myob_id, myob_displayID, Name)
(SELECT UID,displayID,itemName
FROM product_myob);
This is a sample code that you can use. Using MySQLi though because MySQL is deprecated already.
<?php
/* ESTABLISH CONNECTION AND CHANGE THE NECESSARY HOST, USERNAME, PASSWORD AND DATABASE */
$connection=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
$result=mysqli_query($connection,"SELECT * FROM product_myob");
while($row=mysqli_fetch_array($result)){
$myobid=mysqli_real_escape_string($con,$row['UID']);
$myobdisplayid=mysqli_real_escape_string($con,$row['displayID']);
$name=mysqli_real_escape_string($con,$row['itemName']);
/* CHECK IF DATA IS ALREADY IN THE products TABLE */
$result2=mysqli_query($connection,"SELECT * FROM products WHERE myob_id='$myobid' AND myob_displayID='$myobdisplayid' AND Name='$name'");
if(mysqli_num_rows($result2)==0){
mysqli_query($connection,"INSERT INTO products (myob_id, myob_displayID, Name) VALUES ('$myobid','$myobdisplayid','$name')");
} /* END OF IF MYSQLI_NUM_ROWS($RESULT2) IS 0 */
else {
echo "Data has already been inserted before.<br>";
}
} /* END OF WHILE LOOP RESULT */
?>

Search mysql database before inserting data

I cant quite think about how to do this with mysql and php. Basically I want to be able to submit data into a mysql database but before it is inserted, it will check to see if that entry already exists.
$guid=$_POST['guid'];
$name=$_POST['name'];
//Username
$user="webhost";
//Password
$pass="*******";
//IP To Host
$ip="***********";
//Database
$db="dayz2";
//Table
$table="whitelist";
//Database Connection
$con=#mysql_connect("$ip", "$user", "$pass")
or die(mysql_error());
//Select Database
$dbcon=#mysql_select_db($db, $con)
or die(mysql_error());
$dupesql = "SELECT * FROM $table where (name = '$name' AND guid = '$guid')";
$duperaw = mysql_query($dupesql);
if (mysql_num_rows($duberaw) > 0) {
echo "Entry Already Exists";
}
else {
//Query Data Into Whitelist Table
$sql="INSERT INTO $table (name, guid) VALUES ('$name', '$guid')";
//Submit Data into Whitelist Table
$result=#mysql_query($sql, $con) or die(mysql_error());
}
?>
You can do it in another way, instead of:
submit data into a mysql database but before it is inserted, it will
check to see if that entry already exists.
You can do:
INSERT data into a mysql database if not existed, else ignore them
Something like :
INSERT IGNORE INTO table
INSERT IGNORE INTO yourtablename
SET fieldname = 'blah'
,..
It depends what you are trying to do - what is the exact criteria for your query?
You have several options:
use INSERT IGNORE ... if you only want to insert new rows that don't have a duplicate primary key. See http://dev.mysql.com/doc/refman/5.5/en/insert.html.
use INSERT ... ON DUPLICATE KEY UPDATE to insert new rows and update rows where there is a primary key match.
See http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html.
use a normal SQL SELECT ... to pull the results first before performing business logic on the results before deciding which to INSERT ... or UPDATE ... depending on your requirements.
It depends how you want to handle case when the entry exists.
I you want to throw some error then you can create table trigger for insert event and put some checks there, but it will be slow because every insert will do this check.

PHP/MySQL INSERT feature logic error

I recently asked a question about writing to multiple tables: PHP/MySQL insert into multiple data tables on submit
I have now tried out this code and there are no errors produced in the actual code but the results I am getting are strange. When a user clicks register this 'insert.php' page is called and the code can be found below.
<?php
$username = $_POST["username"];
$password = $_POST["password"];
$institution = $_POST["institution"];
$conn = pg_connect("database connection information"); //in reality this has been filled
$result = pg_query($conn, "INSERT INTO institutions (i_id, name) VALUES (null, '$institution') RETURNING i_id");
$insert_row = pg_fetch_row($result);
$insti_id = $insert_row[0];
// INSTITUTION SAVED AND HAS ITS OWN ID BUT NO MEMBER OF STAFF ID
$resultTwo = pg_query($conn, "INSERT INTO staff VALUES (NULL, '$username', '$password', '$insti_id'");
$insert_rowTwo = pg_fetch_row($resultTwo);
$user_id = $insert_rowTwo[0];
// USER SAVED WITH OWN ID AND COMPANY ID
// ASSIGN AN INSTITUTION TO A STAFF MEMBER IF THE STAFF'S $company_id MATCHES THAT OF THE
// INSTITUION IN QUESTION
$update = pg_query($conn, "UPDATE institutions SET u_id = '$user_id' WHERE i_id = '$insti_id'");
pg_close($conn);
?>
What the result of this is just the browser waiting for a server response but there it just constantly waits. Almost like an infinite loop I'm assuming. There are no current errors produced so I think it may be down to a logic error. Any ideas?
The errors:
RETURNING clause is missing in the second INSERT statement.
Provide an explicit list of columns for your second INSERT statement, too.
Don't supply NULL in the INSERT statements if you want the column default (serial columns?) to kick in. Use the keyword DEFAULT or just don't mention the column at all.
The better solution:
Use data-moidifying CTE, available since PostgreSQL 9.1 to do it all in one statement and save a overhead and round trips to the server. (MySQL knows nothing of the sort, not even plain CTEs).
Also, skip the UPDATE by re-modelling the logic. Retrieve one id with nextval(), and make do with just two INSERT statements.
Assuming this data model (you should have supplied that in your question):
CREATE TABLE institutions(i_id serial, name text, u_id int);
CREATE TABLE staff(user_id serial, username text, password text, i_id int);
This one query does it all:
WITH x AS (
INSERT INTO staff(username, password, i_id) -- provide column list
VALUES ('$username', '$password', nextval('institutions_i_id_seq'))
RETURNING user_id, i_id
)
INSERT INTO institutions (i_id, u_id, name)
SELECT x.i_id, x.user_id, '$institution'
FROM x
RETURNING u_id, i_id; -- if you need the values back, else you are done
Data model
You might think about changing your data model to a classical n:m relationship.
Would include these tables and primary keys:
staff (u_id serial PRIMARY KEY, ...)
institution (i_id serial PRIMARY KEY, ...)
institution_staff (i_id, u_id, ..., PRIMARY KEY(i_id, u_id)) -- implements n:m
You can always define institution_staff.i_id UNIQUE, if a user can only belong to one institution.

Categories