המטרה שלי:
ליצור "מערכת" העלאת שמות משתמשים.
ז"א, יש לי קובץ TXT עם XXXX שמות משתמשים שרושמים באתר שלי. השמות מופרדים בקובץ ע"י שורה, ז"א כל שורה = שם משתמש.
הייתי מעונין להעלות את כל אותם שמות משתמשים למסד לעמודת user_name, כך שהם יהיו במסד.
ממה שראיתי יש לי המון אפשרויות לעשות את זה, דרך CSV, TXT ודרך תיבת טקסט.
CSV הצלחתי לעשות, אבל אני לא אוהב את השיטה כי זה מסורבל ולא נוח לי להפוך כל פעם את הקובץ לCSV ולערוך אותו לפני זה וכו'.
הייתי מעוניין פשוט שיהיה כפתור "upload" ואני אבחר את הקובץ TXT שעל המחשב שלי, והשרת פשוט יטען את כל שמות המשתמשים שבו למסד,
או לחלופין שתהיה איזשהי תיבת טקסט באתר, אני אדביק בה את כל השמות משתמשים שמופרדים בשורה, ודרך התיבת טקסט הם יעלו למסד.
אחד הקודים שמצאתי בגוגל הוא:
PHP קוד:
mysql_connect('localhost', 'user', 'pass') or die(mysql_error());
mysql_select_db('db_name') or die(mysql_error());
$lines = file('import.txt');
$company_names = "";
$insert_string = "INSERT INTO `ImportedWordList`(`Word`) VALUES";
$counter = 0;
$maxsize = count($lines);
foreach($lines as $line => $company) {
$insert_string .= "('".$company."')";
$counter++;
if($counter < $maxsize){
$insert_string .= ",";
}//if
}//foreach
mysql_query($insert_string) or die(mysql_error());
החיסרון בקוד:
קובץ הTXT אמור להיות על השרת.
וזה מבזבז המון זמן להעלות קובץ TXT לשרת, ורק אז להתחיל להעלות אותו למסד.
קוד העלאת הCSV בעצם עובד בדרך הזאת של העלאת הקובץ:
PHP קוד:
<?php
//connect to the database
$connect = mysql_connect("localhost","username","password");
mysql_select_db("mydatabase",$connect); //select the table
//
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO contacts (contact_first, contact_last, contact_email) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//
//redirect
header('Location: import.php?success=1'); die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
אשמח לעזרה, תודה.