Large MySQL query and insert - php

hey everyone im new here as well as to php only been at it for about 2 months kinda learning as i go. what i need to get done right now is to take data from about 16 different tables in a data base and duplicate the tables. the table are for applicants and either have an application id in common or a family id in commmon the id's are just genereated hashes. what im doing right now is individually wquerying every table and then doing an insert using the data and just changing the application id and or family id. some tables are pretty big and im trying to figuere out an easier faster way to do this heres an example piece iv writen for one of my tables.
<?
//get family info based on application id
$queryC="SELECT Fam_Type, Fam_Title, Fam_SSNI20, Fam_SSNI20_Select, Fam_Name_First, Fam_Name_Middle, Fam_Name_Last, Fam_Name_Suffix, Fam_Gender, Fam_DOB, Fam_Disabled, Fam_Addy1, Fam_Addy2, Fam_City, Fam_State_Prov, Fam_Zip, Fam_Country, Fam_Home_Phone, Fam_Work_Phone, Fam_Work_Phone_Ext, Fam_Cell_Phone, Fam_Occupation, Fam_Employer, Fam_Primary_Res, Fam_Custody, Fam_Guard_Excuse, Fam_ChiDep_Ans, Fam_ReaVeh_Ans, InstructDone, SetDone, AppDone, HouDone, DepDone, AssDone, ReaDone, IncDone, ExpDone, QueDone, ApplicationDone, StatusDone, Fam_Init, Fam_Start_Date, Fam_End_Date, Fam_Agree, username, password, email, Fam_Letter, Exp_Educational, Fam_Tax, Scan_FileNames, Scan_Descriptions, Fam_Complete, referral, Fam_Holds, appealed, Appeal_Letter, Appeal_Viewed, taxDocuments
FROM familY
WHERE familyID='$famid' AND applicationID='$appid'";
$resultC = mysql_db_query($aidDB, $queryC, $connection); echo $queryC;
while($rC=mysql_fetch_array($resultC)){
$Fam_Type="$rC['0']";
$Fam_Title="$rC['1']";
$Fam_SSNI20="$rC['2']";
$Fam_SSNI20_Select="$rC['3']";
$Fam_Name_First="$rC['4']";
$Fam_Name_Middle="$rC['5']";
$Fam_Name_Last="$rC['6']";
$Fam_Name_Suffix ="$rC['7']";
$Fam_Gender="$rC['8']";
$Fam_DOB="$rC['9']";
$Fam_Disabled="$rC['10']";
$Fam_Addy1 ="$rC['11']";
$Fam_Addy2 ="$rC['12']";
$Fam_City="$rC['13']";
$Fam_State_Prov="$rC['14']";
$Fam_Zip="$rC['15']";
$Fam_Country="$rC['16']";
$Fam_Home_Phone ="$rC['17']";
$Fam_Work_Phone ="$rC['18']";
$Fam_Work_Phone_Ext="$rC['19']";
$Fam_Cell_Phone ="$rC['20']";
$Fam_Occupation ="$rC['21']";
$Fam_Employer="$rC['22']";
$Fam_Primary_Res ="$rC['23']";
$Fam_Custody="$rC['24']";
$Fam_Guard_Excuse ="$rC['25']";
$Fam_ChiDep_Ans ="$rC['26']";
$Fam_ReaVeh_Ans="$rC['27']";
$InstructDone ="$rC['28']";
$SetDone ="$rC['29']";
$AppDone ="$rC['30']";
$HouDone ="$rC['31']";
$DepDone ="$rC['32']";
$AssDone="$rC['33']";
$ReaDone ="$rC['34']";
$IncDone ="$rC['35']";
$ExpDone ="$rC['36']";
$QueDone="$rC['37']";
$ApplicationDone ="$rC['38']";
$StatusDone ="$rC['39']";
$Fam_Init="$rC['40']";
$Fam_Start_Date ="$rC['41']";
$Fam_End_Date ="$rC['42']";
$Fam_Agree ="$rC['43']";
$username ="$rC['44']";
$password ="$rC['45']";
$email ="$rC['46']";
$Fam_Letter="$rC['47']";
$Exp_Educational ="$rC['48']";
$Fam_Tax ="$rC['49']";
$Scan_FileNames="$rC['50']";
$Scan_Descriptions ="$rC['51']";
$Fam_Complete ="$rC['52']";
$referral="$rC[''53]";
$Fam_Holds="$rC['54']";
$appealed="$rC['55']";
$Appeal_Letter="$rC['56']";
$Appeal_Viewed="$rC['57']";
$taxDocuments="$rC['58']";
//insert into family with new applicationid
$queryC2="INSERT INTO family (familyID, applicationID, Fam_Type, Fam_Title, Fam_SSNI20, Fam_SSNI20_Select, Fam_Name_First, Fam_Name_Middle, Fam_Name_Last, Fam_Name_Suffix, Fam_Gender, Fam_DOB, Fam_Disabled, Fam_Addy1, Fam_Addy2, Fam_City, Fam_State_Prov, Fam_Zip, Fam_Country, Fam_Home_Phone, Fam_Work_Phone, Fam_Work_Phone_Ext, Fam_Cell_Phone, Fam_Occupation, Fam_Employer, Fam_Primary_Res, Fam_Custody, Fam_Guard_Excuse, Fam_ChiDep_Ans, Fam_ReaVeh_Ans, InstructDone, SetDone, AppDone, HouDone, DepDone, AssDone, ReaDone, IncDone, ExpDone, QueDone, ApplicationDone, StatusDone, Fam_Init, Fam_Start_Date, Fam_End_Date, Fam_Agree, username, password, email, Fam_Letter, Exp_Educational, Fam_Tax, Scan_FileNames, Scan_Descriptions, Fam_Complete, referral, Fam_Holds, appealed, Appeal_Letter, Appeal_Viewed, taxDocuments )
VALUES
(
'$newfam1id,'
'$newappid,'
'$Fam_Type,'
'$Fam_Title,'
'$Fam_SSNI20,'
'$Fam_SSNI20_Select,'
'$Fam_Name_First,'
'$Fam_Name_Middle, '
'$Fam_Name_Last,'
'$Fam_Name_Suffix,'
'$Fam_Gender,'
'$Fam_DOB,'
'$Fam_Disabled,'
'$am_Addy1,'
'$Fam_Addy2,'
'$Fam_City,'
'$Fam_State_Prov,'
'$Fam_Zip,'
'$Fam_Country,'
'$Fam_Home_Phone,'
'$Fam_Work_Phone, '
'$Fam_Work_Phone_Ext,'
'$Fam_Cell_Phone,'
'$Fam_Occupation,'
'$Fam_Employer,'
'$Primary_Res,'
'$Fam_Custody,'
'$Fam_Guard_Excuse,'
'$Fam_ChiDep_Ans,'
'$Fam_ReaVeh_Ans,'
'$InstructDone,'
'$SetDone,'
'$AppDone,'
'$HouDone,'
'$DepDone,'
'$AssDone,'
'$ReaDone,'
'$IncDone,'
'$ExpDone,'
'$QueDone,'
'$ApplicationDone,'
'$StatusDone,'
'$Fam_Init,'
'$Fam_Start_Date,'
'$Fam_End_Date,'
'$Fam_Agree,'
'$username,'
'$password,'
'$email,'
'$Fam_Letter,'
'$Exp_Educational,'
'$Fam_Tax,'
'$Scan_FileNames,'
'$Scan_Descriptions,'
'$Fam_Complete,'
'$referral,'
'$Fam_Holds,'
'$appealed,'
'$Appeal_Letter,'
'$Appeal_Viewed,'
'$taxDocuments'
)"; echo $queryC2;
}
?>

you do not need to loop all the rows.
use this:
Insert into new_table select * from old_table where {your criteria here}

mysql has INSERT into table (fields,list) SELECT fields,list FROM another_table syntax

You can reduce the amount of PHP code on the SELECT side of things by using mysql_fetch_assoc() instead of array, especially since you're then just reassigning the returned array chunks to individual variables:
$query = "SELECT Fam_Type, Fam_Title, Fam_SSNI20, Fam_SSNI20_Select etc... etc...";
$resultC = mysql_db_query($aidDB, $queryC, $connection); echo $queryC;
while($rC = mysql_fetch_assoc($resultC)) {
...
}
At this point you end up with associated array which you can get at the individual values as:
echo "Fam_Type is " . $rc['Fam_Type'];
echo "Fam_Title is " . $rc['Fam_Title'];
which saves you that long huge blob of variable assignments. Of course, if any of the fields in your query would map internally to the same name (say, you're doing a join and are retrieving two different 'id' fields from two different tables), then you'd need to alias them to different names so they come out distinctly in the array, but that's a simple mod to the query:
SELECT table1.id AS table1_id, table2.id AS table2_id ...
which would leave to:
$result['table1_id'] = ...
As a side node, you should always check to see if the query succeeded. You blindly assume it worked and try to retrieve data. But if the query fails, the mysql functions return FALSE, which would not be a valid result statement and break your fetch attempt. At bare minimum, add some basic error checking
$resultC = mysql_db_query(...) or die("MySQL error: " . mysql_error());
which will spit out the error message and explain why the query failed, instead of then failing with "... is not a valid statement handle" later on. As well, mysql_db_query() is deprecated as of PHP 5.3, and will vanish in some future PHP version. May want to switch to the regular mysql_query() instead.

you can simply do:
INSERT INTO family ( appliction_id, all_the_other_fields )
SELECT 'your_new_app_id', all_the_other_fields
FROM familY
WHERE familyID='$famid' AND applicationID='$appid'
let's hope your $famid and $appid variables are escaped, shall we?

Related

PHP/Mysql: Array instead of stdClass Object

I have the below code:
$result = $conn->query($sql)->fetch(PDO::FETCH_COLUMN);
$myArray = explode(',', $result);
$sql = ("SELECT username,status,location FROM Users WHERE username IN ('" . implode("','",$myArray) . "') AND status > 0 ORDER BY username");
$data = $conn->query($sql)->fetchAll(PDO::FETCH_OBJ);
print_r ($data);
FYI $result is "kk,bb"
The output is as follows:
Array ( [0] => stdClass Object ( [username] => bb [status] => 1 [location] => ) [1] => stdClass Object ( [username] => kk [status] => 1 [location] => ) )
But I really just want to see a two-dimensional array without it saying stdClass Object in front of each item. I tried different kinds of fetching, but this is the only one I could make work. I know there are functions for converting object to array, but I´d rather if there´s a way to do this right, if there is such a thing, in the pasted code.
I hope someone can help, thanks in advance!
You requested objects by using PDO::FETCH_OBJECT. If you want to fetch as arrays, use another fetch type:
$data = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC);
or
$data = $conn->query($sql)->fetchAll(PDO::FETCH_NUM);
The other choices are documented here: http://php.net/manual/en/pdostatement.fetch.php
By the way, why do you run one query to get the values in $myArray, then use these in an SQL-injection vulnerable way in a second query? Wouldn't it be easier to use a JOIN?
Re your comment:
Fist of all, I strongly urge you to code safely the first time, don't rely on "going back later." You probably won't have time to go back later, because once the code seems to work "good enough," the temptation is to go live immediately. Even if you do go back later to fix security flaws, you might miss one. Either way, your development process creates a high risk that you will go live with insecure code.
A piece of old advice from famous computer scientist Andrew S. Tanenbaum: "Security, like correctness, is not an add-on feature."
Now about joins. If you use SQL, you should understand how to do a joins. Not knowing joins in SQL is like thinking you know PHP even though you don't know how to use foreach(). Technically, you can still do some stuff, but you're missing out on a major part of the language.
Joins allow you to query multiple tables in one query, and find rows from each table that match.
In your example, I don't know your first query, but I'll take a guess that it queries some other table to get a list of usernames. Maybe it queries a list of users who are recipients of a email, like this:
SELECT username FROM EmailRecipients WHERE EmailId = 1234
Then your code uses the result list of usernames in a second query. But you can do it all in one query:
SELECT Users.username, Users.status, Users.location
FROM Users JOIN EmailRecipients
ON Users.username = EmailRecipients.username
WHERE EmailRecipients.EmailId = 1234
The SQL engine searches the EmailRecipients table and say it finds six rows for the recipients of email 1234. For each of the six rows, it looks up the corresponding row in the Users table with the matching username. Then it uses columns from those rows in the SELECT result.
When you join tables, there's a possibility both tables might have some columns with the same name. That's why I showed column named by qualifying them as belonging to one table or the other. This removes the ambiguity about which table you meant in each case.
It doesn't matter which table you list first. This type of join is the same left-to-right as it is right-to-level, like some expressions in algebra (2 + 4 is the same as 4 + 2, etc.). MySQL automatically figures out which table is most efficient to read first.
There's more to learn about joins, but that should get you started. I suggest you pick up a tutorial or a book on SQL sometime.
Re your comment:
Where is the "SQL-injection vulnerable way in a second query"?
In your code:
$result = $conn->query($sql)->fetch(PDO::FETCH_COLUMN);
$myArray = explode(',', $result);
$sql = ("SELECT username,status,location FROM Users WHERE username IN ('" . implode("','",$myArray) . "') AND status > 0 ORDER BY username");
$data = $conn->query($sql)->fetchAll(PDO::FETCH_OBJ);
There's no guarantee that the elements in $myArray are safe to use in an SQL statement. Just because they came out of the database doesn't make them safe. What if they contain names like "O'Reilly"? That will upset your quote-implosion.
You can never be 100% sure the data is safe, so it's better to use query parameters. Then you don't care if it's safe, because bound parameters are never combined with the SQL query string.
Here's how to create a dynamic list for the IN ( ) predicate from an array, and bind parameter values to the query using PDO:
$result = $conn->query($sql)->fetch(PDO::FETCH_COLUMN);
$myArray = explode(',', $result);
$placeholders = implode(',', array_fill(0, count($myArray), '?'));
$sql = "
SELECT username,status,location FROM Users
WHERE username IN ($placeholders) AND status > 0
ORDER BY username");
$stmt = $conn->prepare($sql);
$stmt->execute($myArray);
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
While both answers are perfectly valid, I just wanted to add in that there is another solution to your issue.
You can change the default fetch style by defining it where you connect to the database:
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$mydb = 'mydbname';
$conn = new PDO("mysql:host=$host;dbname=$mydb", $user, $pass, [
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
Or you can change it by using setAttribute() using the existing connection:
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
Then you can simply use:
$conn->query($sql)->fetchAll();
And you still have the ability to overwrite the default value:
$conn->query($sql)->fetchAll(PDO::FETCH_NUM);
using PDO::FETCH_ASSOC you can make it as an array. So
$data = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC);
Documentation link:
PDO Statement

Undesired data insertion to database

An employee can claim the amount of money spent on official duty from the employer.
I am working on a website in which after a staff filled in the official duty activity (details), staff is then shown a dynamic form in which they can add/remove transport/meal/hotel claim, depending on how long (days) it takes to complete the duty. Here is the design I came up with.
Here is the output . TransportID 8 & 9 should be in the same row as activityID 11. Is there a way to insert > 1 primary keys into a field?
foreach ( $_POST["dates"] as $index=>$date ) {
$origin = $_POST["origins"][$index];
$destination = $_POST["destinations"][$index];
$cost = $_POST["costs"][$index];
//Insert into transport table
$sql_transport1 = sprintf("INSERT INTO tbl_transport (Date, Origin, Destination, Cost) VALUES ('%s','%s','%s','%s')",
mysql_real_escape_string($date),
mysql_real_escape_string($origin),
mysql_real_escape_string($destination),
mysql_real_escape_string($cost));
$result_transport1 = $db->query($sql_transport1);
$inserted_transport_id1 = $db->last_insert_id();
//Insert into transport_mainclaim table
$sql_transport_mainclaim1 = sprintf("INSERT INTO tbl_transport_mainclaim (claimID, transportID) VALUES ('%s','%s')",
mysql_real_escape_string($inserted_mainclaim_id1),
mysql_real_escape_string($inserted_transport_id1));
$result_transport_mainclaim1 = $db->query($sql_transport_mainclaim1);
$all_transport_id = implode(",",$inserted_transport_id1);
//Insert into mainclaim table
$sql_mainclaim = sprintf("INSERT INTO tbl_mainclaim (activityID, transportID, IC) VALUES ('%s','%s','%s')",
mysql_real_escape_string($inserted_activity_id),
mysql_real_escape_string($all_transport_id),
mysql_real_escape_string($_SESSION['IC']));
$result_mainclaim = $db->query($sql_mainclaim);
$inserted_mainclaim_id = $db->last_insert_id();
}
I have tried using $all_transport_ID = implode(",",$inserted_transport_id1);to separate IDs with comma but failed to do so.
Is the database structure wrongly designed? Please guide me as I want to get this right.
Sorry I couldn't comment on your post because of reputation but I think you gave the wrong link. Your code is operating on table tbl_transport whereas the link you gave shows table named tbl_mainclaim.
Regardless of that,you are trying to insert two integer values 8 and 9 in the column of integer type on the same row as activity id with int value 11. How are you planning to store that?
UPDATE: I think the way which you are implementing this code is wrong. If i am correct your variable $inserted_transport_id is an array whereas in this line you are treating it as a variable. $inserted_transport_id1 = $db->last_insert_id();
As you are using implode which combines array into a string , here you are treating it as an array.
$all_transport_id = implode(",",$inserted_transport_id1);
So I am not sure what you are trying to implement. Its not clear what you are trying to do with that foreach loop for whole SQL.
And if your application permits, you can remove tbl_transport_mainclaim,tbl_meal_mainclaim,tbl_hotel_mainclaim and directly assign foreign key of the tables tbl_transport,tbl_hotel,tbl_meal which references to the respective columns on the tbl_mainclaim.
I might be able to help you with your further explaination about what you are trying to implement in this page.
Don't escape $all_transport_id; do escape (or verify that they are numeric) the values in $inserted_transport_id1.
In the future, do this to help with debugging:
echo $sql_mainclaim;

MySQL: multiple search/select queries at the same time?

I have a question on how to go about the next phase of a project I am working on.
Phase I:
create a php script that scraped directory for all .txt file..
Open/parse each line, explode into array...
Loop through array picking out pieces of data that were needed and INSERTING everything into the database (120+ .txt files & 100k records inserted)..
this leads me to my next step,
Phase II:
I need to take a 'list' of several 10's of thousand of numbers..
loop through each one, using that piece of data (number) as the search term to QUERY the database.. if a match is found I need to grab a piece of data in a different column of the same record/row..
General thoughts/steps I plan to take
scrape directory to find 'source' text file.
open/parse 'source file'.... line by line...
explode each line by its delimiting character.. and grab the 'target search number'
dump each number into a 'master list' array...
loop through my 'master list' array.. using each number in my search (SELECT) statement..
if a match is found, grab a piece of data in another column in the matching/returned row (record)...
output this data.. either to screen or .txt file (havent decided on that step yet,..most likely text file through each returned number on a new line)
Specifics:
I am not sure how to go about doing a 'multiple' search/select statement like this?
How can I do multiple SELECT statements each with a unique search term? and also collect the returned column data?
is the DB fast enough to return the matching value/data in a loop like this? Do I need to wait/pause/delay somehow for the return data before iterating through the loop again?
thanks!
current function I am using/trying:
this is where I am currently:
$harNumArray2 = implode(',', $harNumArray);
//$harNumArray2 = '"' . implode('","', $harNumArray) . '"';
$query = "SELECT guar_nu FROM placements WHERE har_id IN ($harNumArray2)";
echo $query;
$match = mysql_query($query);
//$match = mysql_query('"' . $query . '"');
$results = $match;
echo("<BR><BR>");
print_r($results);
I get these outputs respectively:
Array ( [0] => sample_source.txt )
Total FILES TO GRAB HAR ID's FROM: 1
TOAL HARS FOUND IN ALL FILES: 5
SELECT guar_nu FROM placements WHERE har_id IN ("108383442","106620416","109570835","109700427","100022236")
&
Array ( [0] => sample_source.txt )
Total FILES TO GRAB HAR ID's FROM: 1
TOAL HARS FOUND IN ALL FILES: 5
SELECT guar_nu FROM placements WHERE har_id IN (108383442,106620416,109570835,109700427,100022236)
Where do I stick this to actually execute it now?
thanks!
update:
this code seems to be working 'ok'.. but I dont understand on how to handle the retirned data correctly.. I seem to only be outputting (printing) the last variable/rows data..instead of the entire list..
$harNumArray2 = implode(',', $harNumArray);
//$harNumArray2 = '"' . implode('","', $harNumArray) . '"';
//$query = "'SELECT guar_num FROM placements WHERE har_id IN ($harNumArray2)'";
$result = mysql_query("SELECT har_id, guar_num FROM placements WHERE har_id IN (" . $harNumArray2 . ")")
//$result = mysql_query("SELECT har_id, guar_num FROM placements WHERE har_id IN (0108383442,0106620416)")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array($result);
$numRows = mysql_num_rows($result);
/*
while($row = #mysql_fetch_assoc($result) ){
// do something
echo("something <BR>");
}
*/
// Print out the contents of the entry
echo("TOTAL ROWS RETURNED : " . $numRows . "<BR>");
echo "HAR ID: ".$row['har_id'];
echo " GUAR ID: ".$row['guar_num'];
How do I handle this returned data properly?
thanks!
I don't know if this answers your question but I think you're asking about sub-queries. They're pretty straightforward and just look something like this
SELECT * FROM tbl1 WHERE id = (SELECT num FROM tbl2 WHERE id = 1);
That will only work if there is one unique value to that second subquery. If it returns multiple rows it will return a parse error. If you have to select multiple rows research JOIN statements. This can get you started
http://www.w3schools.com/sql/sql_join.asp
I am not sure how to go about doing a 'multiple' search/select statement like this?
With regards to a multiple select, (and I'll assume that you're using MySQL) you can perform that simply with the "IN" keyword:
for example:
SELECT *
FROM YOUR_TABLE
WHERE COLUMN_NAME IN (LIST, OF, SEARCH, VALUES, SEPARATED, BY COMMAS)
EDIT: following your updated code in the question.
just a point before we go on... you should try to avoid the mysql_ functions in PHP for new code, as they are about to be deprecated. Think about using the generic PHP DB handler PDO or the newer mysqli_ functions. More help on choosing the "right" API for you is here.
How do I handle this returned data properly?
For handling more than one row of data (which you are), you should use a loop. Something like the following should do it (and my example will use the mysqli_ functions - which are probably a little more similar to the API you've been using):
$mysqli = mysqli_connect("localhost", "user", "pass");
mysqli_select_db($mysqli, "YOUR_DB");
// make a comma separated list of the $ids.
$ids = join(", ", $id_list);
// note: you need to pass the db connection to many of these methods with the mysqli_ API
$results = mysqli_query($mysqli, "SELECT har_id, guar_num FROM placements WHERE har_id IN ($ids)");
$num_rows = mysqli_num_rows($results);
while ($row = mysqli_fetch_assoc($results)) {
echo "HAR_ID: ". $row["har_id"]. "\tGUAR_NUM: " . $row["guar_num"] . "\n";
}
Please be aware that this is very basic (and untested!) code, just to show the bare minimum of the steps. :)

text input (seperated by comma) mysql input as array

I have a form where I am trying to implement a tag system.
It is just an:
<input type="text"/>
with values separated by commas.
e.g. "John,Mary,Ben,Steven,George"
(The list can be as long as the user wants it to be.)
I want to take that list and insert it into my database as an array (where users can add more tags later if they want). I suppose it doesn't have to be an array, that is just what seems will work best.
So, my question is how to take that list, turn it into an array, echo the array (values separated by commas), add more values later, and make the array searchable for other users. I know this question seems elementary, but no matter how much reading I do, I just can't seem to wrap my brain around how it all works. Once I think I have it figured out, something goes wrong. A simple example would be really appreciated. Thanks!
Here's what I got so far:
$DBCONNECT
$artisttags = $info['artisttags'];
$full_name = $info['full_name'];
$tel = $info['tel'];
$mainint = $info['maininst'];
if(isset($_POST['submit'])) {
$tags = $_POST['tags'];
if($artisttags == NULL) {
$artisttagsarray = array($full_name, $tel, $maininst);
array_push($artisttagsarray,$tags);
mysql_query("UPDATE users SET artisttags='$artisttagsarray' WHERE id='$id'");
print_r($artisttagsarray); //to see if I did it right
die();
} else {
array_push($artisttags,$tags);
mysql_query("UPDATE users SET artisttags='$artisttags' WHERE id='$id'");
echo $tags;
echo " <br/>";
echo $artisttags;
die();
}
}
Create a new table, let's call it "tags":
tags
- userid
- artisttag
Each user may have multiple rows in this table (with one different tag on each row). When querying you use a JOIN operation to combine the two tables. For example:
SELECT username, artisttag
FROM users, tags
WHERE users.userid = tags.userid
AND users.userid = 4711
This will give you all information about the user with id 4711.
Relational database systems are built for this type of work so it will not waste space and performance. In fact, this is the optimal way of doing it if you want to be able to search the tags.

Extract all the data from a database

Hey, I am wondering how to extract the data from a table in a database onto a table in a page (users.php),
For example:
I want to be able to get all of the usernames and all the id's from my database onto a table.
So if I have in my database:
1 - Fred
2 - Frank
3 - Margret
It will see that I have them user's and id's in the database and print them onto a table.
Any help would be great,
Thanks.
Connect to your database. Host is the location, like localhost if its on your computer, or on the same server as your code. User and Password are self explanatory.
mysql_connect("host", "user", "pass");
The name of the database you want to access.
mysql_select_db("database");
The actual mysql query.
$result = mysql_query('SELECT `User_Name`, `User_ID` FROM TABLE');
Sort it into an array
while($temp = mysql_fetch_array($result)
{
$id = $temp['User_ID'];
$array[$id]['User_ID'] = $id;
$array[$id]['User_Name'] = $temp['User_Name'];
}
Turn the array into a table. (You could skip the last step and go right to this one.
$html ='<table><tr><td>User ID</td><td>User Name</td></tr>';
foreach($array as $id => $info)
{
$html .= '<tr><td>'.$info['User_ID'].'</td><td>'.$info['User_Name'].'</td></tr>';
}
echo $html . '</table>';
Or, the formatting you wanted
$html ='User Id - User Name';
foreach($array as $id => $info)
{
$html .= $info['User_ID'].' - '.$info['User_Name'].'<br>';
}
echo $html;
(For this answer, I will use the mysqli extension -- you could also want to use PDO ;; note that the mysql extension is old and should not be used for new applications)
You first have to connect to your database, using mysqli_connect (And you should test if the connection worked, with mysqli_connect_errno and/or mysqli_connect_error).
Then, you'll have to specifiy with which database you want to work, with mysqli_select_db.
Now, you can send an SQL query that will select all data from your users, with mysqli_query (And you can check for errors with mysqli_error and/or mysqli_errno).
That SQL query will most likely look like something like this :
select id, name
from your_user_table
order by name
And, now, you can fetch the data, using something like mysqli_fetch_assoc -- or some other function that works the same way, but can fetch data in some other form.
Once you have fetched your data, you can use them -- for instance, for display.
Read the pages of the manual I linked to : many of them include examples, that will allow you to learn more, especially about the way those functions should be used ;-)
For instance, there is a complete example on the page of mysqli_fetch_assoc, that does exactly what you want -- with countries insteand of users, but the idea is quite the same ^^
You can do something like the following (using the built-in PHP MySQL functions):
// assuming here you have already connected to the database
$query = "SELECT id,username FROM users";
$result = mysql_query($query, $db);
while ($row = mysql_fetch_array($result))
{
print $row["id"] . " - " . $row["username"] . "\n";
}
which will give you (for example):
1 - Fred
2 - Frank
3 - Margret
Where I've put the print statement, you can do whatever you feel like there eg put it into a table using standard HTML etc.

Categories