This is the first time i'm working in Laravel. I'm developing a custom command which will read a file and insert rows in database. I'm getting errors. Below is my code any help will be appreciated.
Command File.
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
use App\Ship;
//use DB;
class shipdata extends Command
{
protected $signature = 'ship:start';
protected $description = 'This Command will Read file and Extract data from it and will store data in database';
public function __construct()
{
parent::__construct();
}
public function handle()
{
// $this->line('Query Working');
ShipNow::ShipNow();
}
}
Model File
public function ShipNow()
{
$dir = "d:/xampp/htdocs/lara12/IN/";
$failed_dir = "d:/xampp/htdocs/lara12/FAILED/";
$processed_dir = "d:/xampp/htdocs/lara12/PROCESSED/";
$files = array();
// Get all files which need to process
foreach (glob($dir."*.SHIP") as $file) {
$files[] = $file;
}
// If .SHIP files available in the folder then start processing
if(count($files) > 0)
{
// Start processing file
foreach($files as $file)
{
$row = 1;
$file_name = $file;
// Get file name without extension
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file_name);
// Generate new filename with extension PROC
$rename_filename = $withoutExt.".PROC";
// Rename filename
$file_proc = rename($file_name, $rename_filename);
// File processing
$error = 0;
if (($handle = fopen($rename_filename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
$num = count($data);
// For header table insert
if($row==1)
{
$myparams['warehouse'] = $data[0];
$myparams['SHIPMENT_ID'] = $data[1];
$myparams['COMPANY'] = $data[2];
$myparams['CARRIER'] = $data[3];
$myparams['CARRIER_SERVICE'] = $data[4];
$myparams['CUSTOMER'] = $data[5];
$myparams['CUSTOMER_NAME'] = $data[6];
$myparams['SHIP_TO_NAME'] = $data[7];
$myparams['SHIP_TO_ADDRESS1'] = $data[8];
$myparams['SHIP_TO_ADDRESS2'] = $data[9];
$myparams['SHIP_TO_ADDRESS3'] = $data[10];
$myparams['SHIP_TO_CITY'] = $data[11];
$myparams['SHIP_TO_COUNTRY'] = $data[12];
$myparams['SHIP_TO_POSTAL_CODE'] = $data[13];
$myparams['SHIP_TO_ATTENTION_TO'] = $data[14];
$myparams['SHIP_TO_PHONE_NUM'] = $data[15];
$myparams['SHIP_TO_EMAIL_ADDRESS'] = $data[16];
$myparams = save();
/* $sql = "exec dbo.Portal_3PL_ShipmentEntry_Header '".$myparams['SHIPMENT_ID']."','".$myparams['COMPANY']."','".$myparams['CARRIER']."','".$myparams['CARRIER_SERVICE']."','".$myparams['CUSTOMER']."','".$myparams['CUSTOMER_NAME']."','".$myparams['SHIP_TO_NAME']."','".$myparams['SHIP_TO_ADDRESS1']."','".$myparams['SHIP_TO_ADDRESS2']."','".$myparams['SHIP_TO_ADDRESS3']."','".$myparams['SHIP_TO_CITY']."','".$myparams['SHIP_TO_COUNTRY']."','".$myparams['SHIP_TO_POSTAL_CODE']."','".$myparams['SHIP_TO_ATTENTION_TO']."','".$myparams['SHIP_TO_PHONE_NUM']."','".$myparams['SHIP_TO_EMAIL_ADDRESS']."'";
$sql_result = odbc_exec($conn, $sql);
if (odbc_error())
{
echo odbc_errormsg($conn);
$error = 1;
}
$ERP_ORDER_LINE_NUM = 1;
$shipment_header = odbc_fetch_array($sql_result);*/
}
// For shipment detail
else
// {
// $ITEM = $data[1];
// $QUANTITY = intval($data[2]);
// $INTERNAL_SHIPMENT_NUM = $shipment_header['INTERNAL_SHIPMENT_NUM'];
//
// $query2 = "exec dbo.Portal_3PL_ShipmentEntry_Detail '".$INTERNAL_SHIPMENT_NUM."','".$myparams['COMPANY']."',".$ERP_ORDER_LINE_NUM.",'".$ITEM."','".$QUANTITY."',NULL,'N'";
// echo $query2.PHP_EOL;
// $query_result2 = odbc_exec($conn, $query2);
// if (odbc_error())
// {
// echo odbc_errormsg($conn);
// $error = 1;
//
// }else{
// $ERP_ORDER_LINE_NUM++;
// }
// $shipment_detail = odbc_fetch_array($query_result2);
//
// echo trim($shipment_detail['Result'])."#".trim($shipment_detail['Comment'])."#".trim($shipment_detail['INTERNAL_SHIPMENT_LINE_NUM']);
// }
$row++;
}
if($error == 1)
{
$failed_file = "FAILED/".basename($withoutExt).".FAIL";
$file_to_move = "IN/".basename($rename_filename);
fclose($handle);
rename($file_to_move, $failed_file);
// $sql = "INSERT INTO qcimportlog (filename, recordprocess, status) VALUES
// ('$file_name', '$row', 'failed')";
// $result = mysql_query($sql) or die(mysql_error());
}
else
{
$processed_file = "PROCESSED/".basename($rename_filename);
$file_to_move = "IN/".basename($rename_filename);
echo $processed_file;
fclose($handle);
rename($file_to_move, $processed_file);
// $sql = "INSERT INTO qcimportlog (filename, recordprocess, status) VALUES
// ('$file_name', '$row', 'success')";
// $result = mysql_query($sql) or die(mysql_error());
}
}
}
}
else
{
echo "No files to process";
}
}
Kernel.Php
protected $commands = [
Commands\QuizStart::class,
Commands\SendWelcomeEmailCommand::class,
Commands\shipdata::class,
];
ERRORs:
D:\xampp\htdocs\lara12>php artisan ship:start
PHP Fatal error: Class 'App\Console\Commands\ShipNow' not found in D:\xampp\htdocs\lara12\app\Console\Commands\shipdata.php on line 26
[Symfony\Component\Debug\Exception\FatalErrorException]
Class 'App\Console\Commands\ShipNow' not found
ShipNow::ShipNow() should be Ship::ShipNow(), since that's the name of the Model and you call it as a static method, so it has to be a static method in the Ship file:
public static function ShipNow()
{
...
Related
I am a beginner in PHP. I am getting this error whenever I am trying to upload a file through the browser.
"Error in main QueryYou have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '',OTHER_PAYMENT='',TOTAL_CASH_OUTFLOW=''' at line 1"
I am unable to identify where I am going wrong. Here is my code for inserting values
<?php
class Common { public function uploadData($connection,$SL_NO,$PROGRAM,$STATE,$BRANCH,$OPENING_BALANCE,$CASH_RECEIVED_FROM_OTHER_BRANCH,$DISBURSEMENT_CASH_WITHDRAWAL,$CASH_COLLECTION,$ONLINE_COLLECTION,$PRE_SETTLEMENT,$INSURANCE,$LPF_GST,$OTHER_COLLECTION,$TOTAL_CASH_INFLOW,$CASH_REMITTED_TO_OTHER_BRANCH,$CASH_DISBURSEMENT,$CASHLESS_DISBURSEMENT,$CASH_DEPOSITED,$BANK_NAME,$ACCOUNT_NO,$OTHER_PAYMENT,$TOTAL_CASH_OUTFLOW) { $mainQuery = "INSERT INTO exceldata SET
SL_NO='$SL_NO',PROGRAM='$PROGRAM',STATE='$STATE',BRANCH='$BRANCH',OPENING_BALANCE='$OPENING_BALANCE',CASH_RECEIVED_FROM_OTHER_BRANCH='$CASH_RECEIVED_FROM_OTHER_BRANCH',DISBURSEMENT_CASH_WITHDRAWAL='$DISBURSEMENT_CASH_WITHDRAWAL',CASH_COLLECTION='$CASH_COLLECTION',ONLINE_COLLECTION='$ONLINE_COLLECTION',PRE_SETTLEMENT='$PRE_SETTLEMENT',INSURANCE='$INSURANCE',LPF_GST='$LPF_GST',LPF_GST='$LPF_GST',OTHER_COLLECTION='$OTHER_COLLECTION',TOTAL_CASH_INFLOW='$TOTAL_CASH_INFLOW',CASH_REMITTED_TO_OTHER_BRANCH='$CASH_REMITTED_TO_OTHER_BRANCH',CASH_DISBURSEMENT='$CASH_DISBURSEMENT',CASHLESS_DISBURSEMENT='$CASHLESS_DISBURSEMENT',CASH_DEPOSITED='$CASH_DEPOSITED',BANK_NAME='$BANK_NAME',ACCOUNT_NO='$ACCOUNT_NO,OTHER_PAYMENT='$OTHER_PAYMENT',TOTAL_CASH_OUTFLOW='$TOTAL_CASH_OUTFLOW'"; $result1 = $connection->query($mainQuery) or die("Error in main Query".$connection->error); return $result1; } }
My script code:
<?php
include "config.php";
include_once "Common.php";
if($_FILES['excelDoc']['name']) {
$arrFileName = explode('.', $_FILES['excelDoc']['name']);
if ($arrFileName[1] == 'csv') {
$handle = fopen($_FILES['excelDoc']['tmp_name'], "r");
$count = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$count++;
if ($count == 1) {
continue;
}
$SL_NO = $connection->real_escape_string($data[0]);
$PROGRAM = $connection->real_escape_string($data[1]);
$STATE = $connection->real_escape_string($data[2]);
$BRANCH = $connection->real_escape_string($data[3]);
$OPENING_BALANCE = $connection->real_escape_string($data[4]);
$CASH_RECEIVED_FROM_OTHER_BRANCH = $connection->real_escape_string($data[5]);
$DISBURSEMENT_CASH_WITHDRAWAL = $connection->real_escape_string($data[6]);
$CASH_COLLECTION = $connection->real_escape_string($data[7]);
$ONLINE_COLLECTION = $connection->real_escape_string($data[8]);
$PRE_SETTLEMENT = $connection->real_escape_string($data[9]);
$INSURANCE = $connection->real_escape_string($data[10]);
$LPF_GST = $connection->real_escape_string($data[11]);
$OTHER_COLLECTION = $connection->real_escape_string($data[12]);
$TOTAL_CASH_INFLOW = $connection->real_escape_string($data[13]);
$CASH_REMITTED_TO_OTHER_BRANCH = $connection->real_escape_string($data[14]);
$CASH_DISBURSEMENT = $connection->real_escape_string($data[15]);
$CASHLESS_DISBURSEMENT = $connection->real_escape_string($data[16]);
$CASH_DEPOSITED = $connection->real_escape_string($data[17]);
$BANK_NAME = $connection->real_escape_string($data[18]);
$ACCOUNT_NO = $connection->real_escape_string($data[19]);
$OTHER_PAYMENT = $connection->real_escape_string($data[20]);
$TOTAL_CASH_OUTFLOW = $connection->real_escape_string($data[21]);
$common = new Common();
$SheetUpload = $common->uploadData($connection,$SL_NO,$PROGRAM,$STATE,$BRANCH,$OPENING_BALANCE,$CASH_RECEIVED_FROM_OTHER_BRANCH,$DISBURSEMENT_CASH_WITHDRAWAL,$CASH_COLLECTION,$ONLINE_COLLECTION,$PRE_SETTLEMENT,$INSURANCE,$LPF_GST,$OTHER_COLLECTION,$TOTAL_CASH_INFLOW,$CASH_REMITTED_TO_OTHER_BRANCH,$CASH_DISBURSEMENT,$CASHLESS_DISBURSEMENT,$CASH_DEPOSITED,$BANK_NAME,$ACCOUNT_NO,$OTHER_PAYMENT,$TOTAL_CASH_OUTFLOW);
}
if ($SheetUpload){
echo "<script>alert('Sheet has been uploaded successfull !');window.location.href='index.php';</script>";
}
}
}
problem is in my excel 369 rows are there. when I echo/print that data it showing correct but when I am inserting same data in DB table in inserted only 18 - 30 records.
if (isset($_POST['Submit'])) {
$file = $_FILES['csv_file']['tmp_name'];
$handle = fopen($file, "r");
if ($file == NULL) {
error(_('Please select a file to import'));
redirect(page_link_to('excel_data_upload'));
}else {
$conn = connect();
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$num3 = $filesop[3];
$num8 = $filesop[8];
$num9 = $filesop[9];
$num20 = $filesop[20];
if($num3!='ExpiryDate' &&$num8!='VCNO' &&$num20!='TotalB2CAmount' && $num9 !='STBNO'){
$insertAgent = mysqli_query($conn, "INSERT INTO `upload_billing_data`
(`vc_number`,`stb_number`,`operator_id`,`expiry_date`,`monthly_bill_amount`)
VALUES ('$num8','$num9',140,'$num3','$num20')");
if($insertAgent)
{
echo 'succss';
}else{
echo 'error';
}
}
}
close($conn);
}
}
I am fetching from the excel data. I want to insert all records
Change the code as below and you might get to save all data using one query to the database:
$query_insert = array();
while(($filesop = fgetcsv($handle, 1000, ",")) !== false) {
$num3 = filterString($filesop[3]);
$num8 = filterString($filesop[8]);
$num9 = filterString($filesop[9]);
$num20 = filterString($filesop[20]);
if ($num3!='ExpiryDate' &&$num8!='VCNO' &&$num20!='TotalB2CAmount' && $num9 !='STBNO') {
$query_insert[] = "('{$num8}', '{$num9}', 140, '{$num3}', '{$num20}')";
}
}
// If no row matched your if, then there will be no row to add to the database
if (count($query_insert)>0) {
$conn = connect();
$query_insert_string = implode(', ', $query_insert);
$query = "INSERT INTO `upload_billing_data` (`vc_number`, `stb_number`, `operator_id`, `expiry_date`, `monthly_bill_amount`) VALUES {$query_insert_string};";
$insertAgent = mysqli_query($query);
// The rest of you code
...
close($conn);
}
// This function makes sure that you string doesn't contain characters that might damage the query
function filterString($string) {
$string = str_replace(array("\'", '"'), array('', ''), $string);
$string = filter_var($string, FILTER_SANITIZE_STRING);
return $string;
}
Please check this modified code
if (isset($_POST['Submit'])) {
$file = $_FILES['csv_file']['tmp_name'];
$handle = fopen($file, "r");
if ($file == NULL) {
error(_('Please select a file to import'));
redirect(page_link_to('excel_data_upload'));
}else {
$conn = connect();
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$num3 = $filesop[3];
$num8 = $filesop[8];
$num9 = $filesop[9];
$num20 = $filesop[20];
if($num3!='ExpiryDate' &&$num8!='VCNO' &&$num20!='TotalB2CAmount' && $num9 !='STBNO'){
$insertAgent = mysqli_query($conn, "INSERT INTO `upload_billing_data`
(`vc_number`,`stb_number`,`operator_id`,`expiry_date`,`monthly_bill_amount`)
VALUES ('".mysqli_real_escape_string($num8)."','".mysqli_real_escape_string($num9)."',140,'".mysqli_real_escape_string($num3)."','".mysqli_real_escape_string($num20)."')");
if($insertAgent)
{
echo 'succss';
}else{
echo 'error';
}
}
}
close($conn);
}
}
BY using mysqli_real_escape_string() you will be able to avoid sqlinjection issues and you will be able to handle issue of quotes which might be causing an issue.
in your else block where you are echo "error". you can use mysqli_error($conn); to get exact what error is occurring while performing an insert
So I am wanting to allow my members to view a profile via a url such as: mywebsite.com/account/Username
however, at the moment my members can view via the url: mywebsite.com/account?username=username.
This doesn't look profesional and I've tried nearly everything to get it to the url I'm looking to get.
(Please be aware; I'm very new to this website and cannot use it properly, If I have done anything wrong, please notify me and I will justify it.)
The code:
//get config
$config = $base->loadConfig();
full code:
https://pastebin.com/UmAmF9Rt
<?php
require('../includes/config.php');
require('../structure/base.php');
require('../structure/forum.php');
require('../structure/forum.index.php');
require('../structure/forum.thread.php');
require('../structure/forum.post.php');
require('../structure/database.php');
require('../structure/user.php');
$database = new database($db_host, $db_name, $db_user, $db_password);
$base = new base($database);
$user = new user($database);
$forum = new forum($database);
$forum_index = new forum_index($database);
$thread = new thread($database);
$post = new post($database);
$user->updateLastActive();
//get config
$config = $base->loadConfig();
//set some variables that are used a lot throughout the page
if (!empty($_GET['username'])) {
$profile_name = htmlspecialchars($_GET["username"]);
}
else{
$profile_name = $user->getUsername($_COOKIE['user'], 2);
}
$username = $user->getUsername($_COOKIE['user'], 2);
$rank = $user->getRank($username);
$f = $_GET['forum'];
$i = $_GET['id'];
//assign data to details[] array
$details['lock'] = $detail_query[0]['lock'];
$details['sticky'] = $detail_query[0]['sticky'];
$details['title'] = stripslashes(htmlentities($detail_query[0]['title']));
$details['username'] = $detail_query[0]['username'];
$details['status'] = $detail_query[0]['status'];
$details['content'] = $detail_query[0]['content'];
$details['date'] = $detail_query[0]['date'];
$details['lastedit'] = $detail_query[0]['lastedit'];
$details['qfc'] = $detail_query[0]['qfc'];
$details['moved'] = $detail_query[0]['moved'];
$details['hidden'] = $detail_query[0]['hidden'];
$details['autohiding'] = $detail_query[0]['autohiding'];
//get forum details
$forum_details = $database->processQuery("SELECT `title` FROM `forums` WHERE `id` = ?", array($f), true);
if(isset($_GET['username'])){
if($user->doesExist($_GET['username'])){;
}
}else{
if(!$user->isLoggedIn()){
$base->redirect('../login.php');
}else{
$user_s = $username;
}
}
$messages = array();
$avatar = $user->getAvatar($profile_user);
$usr = $user->getUsername($profile_user);
if($username == $profile_user && $user->isLoggedIn() && isset($_REQUEST['cust_title'])) {
$user->setTitle($username, htmlentities($_REQUEST['cust_title']));
}
if($user_s == $username && $user->isLoggedIn() && isset($_FILES['uploaded'])) {
if(isset($_REQUEST['delete'])) {
$user->setAvatar($username, '');
$messages[] = "Your avatar has been removed.";
} else {
$ok = false;
$info = getimagesize($_FILES['uploaded']['tmp_name']);
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
$messages[] = ("Upload failed with error code " . $_FILES['uploaded']['error']);
} else if($info === FALSE) {
$messages[] = ("Unable to determine image type of uploaded file");
} else if(($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
$messages[] = ("Not a gif/jpeg/png");
} else if($_FILES['uploaded']['size'] > 350000) {
$messages[] = "Your file is too large.";
} else if($_FILES['uploaded']['type'] == "text/php") {
$messages[] = "No PHP files";
} else {
$ok = true;
}
$target = md5(strtolower(trim($username))) .'.'. pathinfo($_FILES['uploaded']['name'])['extension'];
if($ok) {
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], "../images/avatar/" . $target)){
$messages[] = "Your avatar has been uploaded. Please allow atleast 10 minutes for it to update.";
$user->setAvatar($username, $target);
} else {
$messages[] = "Sorry, there was a problem uploading your file.";
}
}
}
}
//retrieve posts/threads
$posts = $database->processQuery("SELECT `id`,`thread`,`username`,`timestamp`,`content` FROM `posts` WHERE `username` = ? AND ". time() ." - `timestamp` < 1209600 ORDER BY `id` DESC", array($user_s), true);
$threads = $database->processQuery("SELECT `id`,`parent`,`title`,`username`,`timestamp`,`content` FROM `threads` WHERE `username` = ? AND ". time() ." - `timestamp` < 1209600 ORDER BY `id` DESC", array($user_s), true);
//type:id:forum:timestamp:(if post)thread
$list = array();
foreach($posts as $post){
//get the thread's forum/parent
$t = $database->processQuery("SELECT `parent` FROM `threads` WHERE `id` = ? LIMIT 1", array($post['thread']), true);
$list[$post['timestamp']] = 'p:'.$post['id'].':'. $t[0]['parent'] .':'.$post['timestamp'].':'.$post['thread'].':'.$post['content'];
}
//add threads
foreach($threads as $thread){
$list[$thread['timestamp']] = 't:'.$thread['id'].':'.$thread['parent'].':'.$thread['timestamp'].':'.$thread['content'];
}
//now sort them
krsort($list, SORT_NUMERIC);
$r = $database->processQuery("SELECT * FROM `users` WHERE `username` = ?", array($profile_name), true);
?>
Your best bet is to use:
.htaccess route with mod_rewrite
Try Adding a file called .htaccess in your root folder, and add something like this:
RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /account.php?username=$username
This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want:
Refer to this answer by Niels Keurentjes: https://stackoverflow.com/a/16389034/3367509
If you are new to .htaccess look up this question: What is .htaccess file?
I have a table of student details. and i have two csv files,these files contains updated information of existing students and new students data.if data not in student table which means the student left the school.
update new details for existing students
If student left school update status the to zero
If new student,then add as new row(with details from both csv)
Below is my code but in this second file information not getting updated.
i am attaching my code.if anybody have simple solution,please suggest
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit'])) {
$sql = "SELECT * FROM e_student";
$result_main = $conn->query($sql);
$filea = $_FILES['filea'];
$ext = pathinfo($_FILES['filea']['name'], PATHINFO_EXTENSION);
if ($ext == "csv" && $_FILES["filea"]["error"] == 0) {
$target = "upload/" . $_FILES["filea"]["name"];
move_uploaded_file($_FILES["filea"]["tmp_name"], $target);
if (($handle = fopen($target, "r")) !== FALSE) {
$array = $fields = array();
$i = 0;
while (($row = fgetcsv($handle, 4096)) !== false) {
if (empty($fields)) {
$fields = $row;
continue;
}
foreach ($row as $k => $value) {
$array[$i][$fields[$k]] = $value;
}
$i++;
}
fclose($handle);
}
}
$ext1 = pathinfo($_FILES['fileb']['name'], PATHINFO_EXTENSION);
if ($ext1 == "csv" && $_FILES["fileb"]["error"] == 0) {
$target1 = "upload/" . $_FILES["fileb"]["name"];
move_uploaded_file($_FILES["fileb"]["tmp_name"], $target1);
if (($handle = fopen($target1, "r")) !== FALSE) {
$array1 = $fields1 = array();
$j = 0;
while (($row1 = fgetcsv($handle, 4096)) !== false) {
if (empty($fields1)) {
$fields1 = $row1;
continue;
}
foreach ($row1 as $k => $value) {
$array1[$j][$fields1[$k]] = $value;
}
$j++;
}
fclose($handle);
}
}
foreach ($result_main as $rel) {
$clk = 'no';
foreach ($array as $arr) {
if(isset($arr1['SCD']))
{
if (strcmp(trim($rel['objId']), trim($arr['BCEID'])) == 0) {
$clk = 'yes';
$name = $arr['FirstName'];
$conditn = $rel['objId'];
$last_name = $arr['LegalSurname'];
$year_level = $arr['YearLevelName'];
$email = $arr['BCEEmail'];
$username = $arr['BCELogin'];
$StEnrollmentStatus = 1;
$sql1 = "UPDATE e_student SET Name = '$name',Lastname='$last_name',stYearLevel='$year_level',email='$email',username='$username' WHERE objId ='$conditn'";
$result = $conn->query($sql1);
if($result)
{
updateparent($rel['objId'], $array1,$conn);
}
}
}
}
if ($clk == 'no') {
$conditn = $rel['objId'];
$status = 0;
$pastoral = "Not Currently Enrolled";
$sql1 = "UPDATE e_student SET stEnrollmentStatus = '$status',stPastoral='$pastoral' WHERE objId ='$conditn'";
$result = $conn->query($sql1);
}
}
foreach ($array as $ar1) {
foreach ($result_main as $rel1) {
if (strcmp(trim($ar1['BCEID']), trim($rel1['objId'])) != 0) {
$name = $ar1['FirstName'];
$last_name = $ar1['LegalSurname'];
$year_level = $ar1['YearLevelName'];
$email = $ar1['BCEEmail'];
$objid = $ar1['BCEID'];
$username = $ar1['BCELogin'];
$StEnrollmentStatus = 1;
$sql3 = "INSERT INTO e_student(Name,Lastname,stYearLevel,email,objId,username,stEnrollmentStatus) VALUES('$name','$last_name','$year_level','$email','$objid','$username','$StEnrollmentStatus')";
$result1 = $conn->query($sql3);
if($result1)
{
updateparent1($objid, $array1,$conn);
}
}
}
}
echo "<h3><center>SUCCESSFULLY UPDATED</center></h3>";
}
function updateparent($objid, $array1,$conn) {
foreach ($array1 as $arr1) {
if(isset($arr1['SCD']))
{
if (strcmp(trim($objid), trim($arr1['SCD'])) == 0) {
$parent = $arr1['PTI1'] . $arr1['PFN1'] . $arr1['PSN1'];
echo $parent;
$email = $arr1['PEM1'];
}
$sql2 = "UPDATE e_student SET stParentName = '$parent',stParentEmail='$email' WHERE objId ='$objid'";
$result = $conn->query($sql2);
}
}
}
function updateparent1($objid, $array1,$conn) {
foreach ($array1 as $arr1) {
if(isset($arr1['SCD']))
{
echo $arr1['SCD'];
if (strcmp(trim($objid), trim($arr1['SCD'])) == 0) {
$parent = $arr1['PTI1'] . $arr1['PFN1'] . $arr1['PSN1'];
$email = $arr1['PEM1'];
}
$sql2 = "UPDATE e_student SET stParentName = '$parent',stParentEmail='$email' WHERE objId ='$objid'";
$result = $conn->query($sql2);
}
}
}
?>
I try to read every word after this word #EXTINF:-1
and the next line from the local file and subsequently add the result to MySQL if it does not exist.
The contents of the file looks like this:
#EXTM3U
#EXTINF:-1,name1
http://www.name1
#EXTINF:-1,name2
http://www.name2
#EXTINF:-1,name3
http://www.name3
#EXTINF:-1,name4
http://www.name4
And my code:
$file = file("file.m3u);
array_shift($file);
$count = count($file);
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
$getname[] = substr($row, $pos + 1);
} else {
$geturl[] = $row;
} } }
$count = count($getname);
for($i=0; $i < $count; $i++){
$name = $getname[$i];
$url = $geturl[$i];
if (empty($name)) { exit; };
if (empty($url)) { exit; }
$get_user = mysql_query("select * from users where (name = '$name')");
$show_user = mysql_fetch_array($get_user);
$userid = $show_user['userid'];
$get_url = mysql_query("select * from urls where url = '$url'");
$show_url = mysql_fetch_array($get_url);
$urlid = $show_url['urlid'];
if (empty($userid) && empty($urlid)) {
$add_user = "INSERT INTO users(name)
VALUES('$name')";
mysql_query($add_user);
$userid = mysql_insert_id();
$add_url = "INSERT INTO urls(userid, url)
VALUES('$userid', '$url')";
mysql_query($add_url);
$urlid = mysql_insert_id();
}
}
My code cannot read file correctly, because when I try check the line that I had read from file, it does not work.
The info that I try to read:
name = name1
url = http://www.name1
is for every user.
This might have something to do with it
$file = file("file.m3u);
It should be
$file = file("file.m3u");