...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
March 16, 2012

CSV into MySQL using PHP

Question by user1183307

I’m trying to import data from my students.csv file into mysql using php. The entries in the csv file is in such a way that column (student_number, fname, lname, level) will be inserted into biodata table..

I’m also uploading the student.csv file from my computer.

When I run the page I dont get anything out on the screen.

session_start();
require('includes/dbconnect.php');
require 'includes/header.inc.php';

//check for file upload
if (isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])) {
    //upload directory
    $upload_dir = "C:UsersDOTMANDocumentsstudents.csv";
    //create file name
    $file_path = $upload_dir . $_FILES['csv_file']['name'];
    //move uploaded file to upload dir
    if (!move_uploaded_file($_FILES['csv_file']['tmp_name'], $file_path)) {
        //error moving upload file
        echo "Error moving file upload";
    }
    //open the csv file for reading
    $handle = fopen($file_path, 'r');
    //turn off autocommit and deletethe bio data
    mysql_query("SET AUTOCOMMIT=0");
    mysql_query("BEGIN");
    mysql_query("TRUNCATE TABLE biodata") or die(mysql_error());
    while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
        //Access field data in $data array ex.
        $student_number = $data[0];
        $fname = $data[1];
        $lname = $data[2];
        $level = $data[3];
        //Use data to insert into db
        $query = "INSERT INTO biodata (student_number, fname, lname, level)
                  VALUES ('$student_number', '$fname', '$lname', '$level')";
        mysql_query($query) or die (mysql_error());
    }
}

Answer by Starx

Solution using PHP

$file = 'path/to.csv'; 

$lines = file($file);
$firstLine = $lines[0];
foreach ($lines as $line_num => $line) {
    if($line_num==0) { continue; } //escape the header column
    $arr = explode(",",$line);
    $column1= $arr[0];
    $column2= $arr[1];

    echo $column1.$column2."<br />";
        //put the mysql insert statement here
}
Read more

PHP – Session lost/emptied on form post

Question by Tommy Plummer

So after debugging my session array while logging into my website, I find that when posting a form, all session data is lost. The session data is wiped when the updateDetails and changePassword methods are called. Why is this?

  • session_start() is called before any data processing
  • Upon a POST request, session data is set and unset (but not the entire $_SESSION variable)
  • I use the following code to check for POST requests:

    if($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
    }

  • It only happens once: Once the session has been lost, the methods can be called without the issue occuring any further (until they lose the session through expiration or closing their browser).

index.php (part)

session_start();

$page = $_GET['p'];
$query = $_GET['q'];
$req = $_GET['req'];

$user = new User();
switch($page) {
    case 'account':

        if($req=="logout") {
            if($user->isLoggedIn())
                $user->logout();

            header("Location: /?p=account");
            exit();

        }
        else if($req=="signup") {
            if($user->isLoggedIn()) {
                header("Location: /?p=account");
                exit();
            }
            else {

                if($_SERVER['REQUEST_METHOD'] == 'POST') {

                    $form_data = array('username' => $_POST['username'],
                        'password' => $_POST['password'],
                        'password_repeat' => $_POST['password_repeat'],
                        'title' => $_POST['title'],
                        'first_name' => $_POST['first_name'],
                        'surname' => $_POST['surname'],
                        'dob_day' => $_POST['dob_day'],
                        'dob_month' => $_POST['dob_month'],
                        'dob_year' => $_POST['dob_year'],
                        'gender' => $_POST['gender'],
                        'email' => strtolower($_POST['email']),
                        'email_repeat' => strtolower($_POST['email_repeat']));

                    if($user->signup($form_data)) {
                        header("Location: /?p=account");
                        exit();
                    }
                }
            }
        }
        else {
            if($user->isLoggedIn()==true) {                 
                if($_SERVER['REQUEST_METHOD'] == 'POST') {

                    if($req=='editdetails') {

                        $form_data = array(
                            'title' => $_POST['title'],
                            'first_name' => $_POST['first_name'],
                            'surname' => $_POST['surname'],
                            'gender' => $_POST['gender'],
                            'phone' => $_POST['phone'],
                            'email' => strtolower($_POST['email']),
                            'password' => $_POST['password']
                            );

                        if($user->updateDetails($form_data)) {
                            header("Location: /?p=account");
                            exit();
                        }
                    }
                    else if($req=='changepassword') {
                        $form_data = array(
                            'old_password' => $_POST['old_password'],
                            'password' => $_POST['password'],
                            'password_repeat' => $_POST['password_repeat'],
                            );

                        if($user->changePassword($form_data)) {
                            header("Location: /?p=account");
                            exit();
                        }
                    }
                }
                $user->retrieveUserDetails();
                $details=$user->getUserDetails();
            }
            else {
                if($req) {
                    header("Location: /?p=account");
                    exit();
                }
                else if($_SERVER['REQUEST_METHOD'] == 'POST') {

                    $form_data = array('username' => $_POST['username'], 'password' => $_POST['password']);

                    if($user->login($form_data)) {
                        $user->retrieveUserDetails();
                        $details=$user->getUserDetails();
                    }
                }

            }
        }
        break;
}

user.php (part)

class User {

private $auth;
private $details;
private $session_alert;

function User() {

    if(isset($_SESSION['alert'])) 
        $this->session_alert = $_SESSION['alert'];

    $this->auth = isset($_SESSION['auth']) ? $_SESSION['auth'] : null;

    if(isset($this->auth)) {
        $database= new Database;
        if($database->checkUserSession($this->auth['user_id'],session_id())) {
            $this->logged_in=true;
        }
        else {
            $this->addSessionAlert('global','Your login session has possibly timed out, you may login again by <a href="/?p=account">clicking here</a>.',true);
            unset($_SESSION['auth']);
        }
    }
}   

function login($data) {
    $return = false;
    $this->form = new Form($data,0);    

    if(!$this->form->getError()) {
        $database= new Database;
        $error_msg = "The username/password entered was invalid. Please check to see if they are correct and try again, or use the relevant links to recover your account.";

        $salt = $database->getSaltByUsername($data['username']);

        if($salt) {
            $hash = $this->hashpwd($data['password'],$salt);

            // Do login
            $this->auth = array();
            $this->auth['user_id'] = $database->checkUserByHash($data['username'],$hash);

            if($this->auth['user_id']) {
                session_regenerate_id();

                if($database->doLogin($this->auth['user_id'],session_id())) {
                    $details=$database->getUserDetailsById($this->auth['user_id']);
                    $this->auth['first_name'] = $details['first_name'];

                    $_SESSION['auth']=$this->auth;

                    $this->logged_in=true;
                    $return = true;
                }
                else
                    $this->form->pushError('Something went wrong, please try again.');
            }
            else
                $this->form->pushError($error_msg);
        }
        else
            $this->form->pushError($error_msg);
    }
    return $return;
}
function logout() {
    $return = false;

    if(isset($this->auth)) {
        $database= new Database;

        if($database->clearUserSession($this->auth['user_id'],session_id())) {
            unset($_SESSION['auth']);
            $this->logged_in=false;
            session_regenerate_id();
            $return = true;
        }
    }

    return $return;
}
function signup($data) {
    $return = false;
    $this->form = new Form($data,1);    

    if(!$this->form->getError()) {
        $database= new Database;

        if($database->checkUserByUsername($data['username']))
            $this->form->pushError("The username entered already exists, please try again.");

        else if($database->checkUserByEmail($data['email']))
            $this->form->pushError("The e-mail address entered is already in use, please try again.");

        else {
            $dbarray = $data;

            unset($dbarray['password'],$dbarray['password_repeat'],$dbarray['dob_month'],$dbarray['dob_day'],$dbarray['dob_year']);

            $dbarray['dob']=date("Y-m-d", mktime(0,0,0,$data['dob_month'], $data['dob_day'], $data['dob_year']));

            $dbarray['salt']=strtoupper(md5(mt_rand()));
            $dbarray['hash'] = $this->hashpwd($data['password'],$dbarray['salt']);

            // Do signup
            $this->auth = array();
            $this->auth['user_id'] = $database->newUser($dbarray);
            if($this->auth['user_id']) { 
                session_regenerate_id();

                if($database->doLogin($this->auth['user_id'],session_id())) {
                    $details=$database->getUserDetailsById($this->auth['user_id']);
                    $this->auth['first_name'] = $details['first_name'];
                    $_SESSION['auth']=$this->auth;

                    $this->logged_in=true;
                }
                $return=true;
            }
            else {
                $this->form->pushError("Something went wrong, please try again.");
            }
        }
    }
    return $return;
}
function updateDetails($data) {
    $return = false;
    $this->form = new Form($data,2);    

    if(!$this->form->getError()) {
        $database= new Database;

        if( $database->checkUserByEmailNotById($data['email'],$this->auth['user_id']) ) {
            $this->form->pushError("The e-mail address entered is already in use, please try again.");
        }

        else {

            $salt = $database->getSaltById($this->auth['user_id']);
            if($salt) {
                $hash = $this->hashpwd($data['password'],$salt);
                if($database->checkUserIdByHash($this->auth['user_id'],$hash)) {
                    $database->updateUserById($this->auth['user_id'],$data);
                    $return = true;

                }
                else 
                    $this->form->pushError("The password entered was incorrect, please try again.");
            }

        }
    }

    return $return;
}

function changePassword($data) {
    $return = false;
    $this->form = new Form($data,3);    

    if(!$this->form->getError()) {
        $database= new Database;

        $salt = $database->getSaltById($this->auth['user_id']);
        if($salt) {

            $hash = $this->hashpwd($data['old_password'],$salt);

            if($database->checkUserIdByHash($this->auth['user_id'],$hash)) {
                $salt=strtoupper(md5(mt_rand()));
                $hash = $this->hashpwd($data['password'],$salt);

                if($database->updateSaltHashById($this->auth['user_id'],$salt,$hash)) $this->addSessionAlert('yourdetails','Your password has been changed successfully.',false);
                $return = true;

            }
            else 
                $this->form->pushError("The old password entered was incorrect, please try again.");
        }
    }

    return $return;
}

function isLoggedIn() {
    return $this->logged_in;
}
function getUserDetails() {
    return $this->details;
}

}

Answer by Starx

Starting a session inside a class’s contructor method, just does not sound nice.

Use session_start(); at the top of the index.php page instead.

Read more
March 15, 2012

Display a list inline

Question by Startup Crazy

I have a code that I tried to display inline all the contents in a list but the first item is displaying in a line and after that all the other items are displayed in other line. I am confused with the problem. Here is my code,

 <ul style="display:inline; list-style-type: none;">

 <li style="background:url("no-color.png") repeat !important; padding:5px; display:inline;"> FEATURED</li>
 <li style="background:none repeat scroll 0 0 rgba(255, 57, 65, 0.9) !important;padding:5px;display:inline;">IPHONE4S </li>
 <li style="background:none repeat scroll 0 0 rgba(255, 103, 57, 0.9) !important;padding:5px;display:inline;">APPLE STOCKS </li> 
 <li style="background:none repeat scroll 0 0 rgba(255, 218, 57, 0.9) !important;padding:5px;display:inline;">IPAD HD </li> 
 <li style="background:none repeat scroll 0 0 rgba(193, 241, 78, 0.9) !important;padding:5px;display:inline;">ITUNES </li> 
 <li style="background:none repeat scroll 0 0 rgba(29, 195, 246, 0.9) !important;padding:5px;display:inline;">STEVE JOBS </li>
 <li style="background:none repeat scroll 0 0 rgba(29, 195, 246, 0.9) !important;padding:5px;display:inline;">ICLOUD</li>

</ul>
</p>

Also, you can see it on jsfiddle.

Please help me out how can I display all in one line. Thanks

Answer by Madara Uchiha

You’ve tried to use the background url("") feature to change the background to an image, but you’ve forgotten that you are within the style= attribute of HTML, so the first " closes the style element, without ever reaching to the display: inline part.

Changing your quotes to single-quotes ' helps.

<li style="background:url('no-color.png') repeat !important; padding:5px; display:inline;"> FEATURED</li>

Answer by Starx

It is list item that should be in-lined not the list.

You codes perfects, with a minor update

ul li { display: inline; }

check a demo

Read more

Jquery Datepicker add 2 years to year not based on month/day

Question by user1272083

I have implemented the jQuery datepicker to allow the selection of dates on a form, it should allow the selection of date based on the current date + 2 years however in the final year it will not proceed past the current date or month.

As such if today is 15/03/2012 the maximum available date would be 15/03/14. However, I require the entire of 2014 to be selectable. As such, the maximum should be 31/12/14.

How would I best go about this to enable it to auto update as it currently does?

<script type="text/javascript">
    <!-- 
         $(function() {
           $('.datepicker').datepicker({
                numberOfMonths: 3,
                showButtonPanel: true,
                defaultDate: "+1w",
                changeMonth: true,
                changeYear: true,
                numberOfMonths: 3,
                minDate: "-0",
                maxDate: "2y",
                dateFormat: 'dd-mm-yy'
    });
    });
    -->

Answer by Starx

Use yearRange options. Use it like

yearRange: 'c:c+2'

Here, c represnts current year and c+2 the next two years.

$('.datepicker').datepicker({
    numberOfMonths: 3,
    showButtonPanel: true,
    defaultDate: "+1w",
    changeMonth: true,
    changeYear: true,
    numberOfMonths: 3,
    yearRange: 'c:c+2',
    dateFormat: 'dd-mm-yy'
});

Here is a demo for the above example.

Read more

jQuery Auto Scroll to DIV ID

Question by H. Ferrence

I have a div id a third of the way down a web page

HTML

<div id="scrollHere"></div>

JavaScript

    <script>
$(document).ready(function(){

var elem = $('#scrollHere');
if(elem) {
    $(window).scrollTop(elem.offset().top).scrollLeft(elem.offset().left);
}

/*
var destination = $('#scrollHere').offset().top;
    $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination-75}, 800 );
    return false;
*/
/*
var elem = $('#scrollHere');
if(elem) {

$(window).scrollTop(elem.offset().top).scrollLeft(elem.offset().left);
    //$('html').scrollTop(elem.offset().top);
    //$('html').scrollLeft(elem.offset().left);
}
*/


/*
    var elem = $('#scrollHere');
    if(elem) {
        //$.scrollTo(elem.left, elem.top);
        //$(document).stop().scrollTo( elem.offset().left, elem.offset().top );
    }
*/

}); // end .ready()
    </script>

CSS

#scrollHere{
    position:relative;
    top:500px;
    left:1000px;
    border:1px solid black;
    width:50px;
    height:50px;
}

But I can’t get autoscroll to take me to the div id on page refresh.

Am I using the wrong JavaScript commands?

Answer by Starx

The most efficient way to achieving this by changing the scrollTop and scrollLeft of the DOM window.

$(window).scrollTop(elem.offset().top).scrollLeft(elem.offset().left);

Demo

Read more

jQuery based checkbox not working

Question by Alex Mathew

$(document).ready(function() {
    var dataString="hy";
    var htmlnew="<input type='checkbox' name='formDoor' value='A' class='list' enable='true'>Check 1";

    alert(htmlnew);

    $(".list").change(function()
    {
        $("#regTitle").append(htmlnew);
    });
 });

The above is which i used when each time i check the checkbox with class list. i get a new one in #regTitle div, but the problem i am facing is the newly generated check boxes are not able to checked,can you guys tell me whats the problem?

Answer by Starx

Your checkbox’s change event does not attach to the dynamically generated elements. You will have to delegate the bind. Using .on() is very good for this purpose.

$("body").on("change", ".list",function() {
    $("#regTitle").append(htmlnew);
});
Read more

Text input margins in Firefox

Question by simion314

I am having problems with the text input in firefox, it has some margins and I can;t get rid of them, maybe that space is not a margin?(it is outside the border of the input so it looks like a margin).

enter image description here

In the image above the width of the input is set to 100%,,margin and padding is 0, also i tried setting -moz-box-sizing: border-box;

I would like some resources or an explanation to make me understand what is that space and how can I get rid of it?
Thanks.

Edit1:
Here is my current test page
https://www.designersbookshop.com/support/test.html
also i made a copy in …test_2.html (i will try the suggestions on the test.html),
Check the inputs on left side.

Edit2:
My Firefox version is 10.0.2
Here is how an input element looks like in firebug, it is clear that a margin or something similar is painted outside the border(or i am stupid but I want to learn)
view with firebug
in the image above the border of the input is the small line(1px) visible on left and right of the input.

Edit3 I figure it out, is the border, I am on Ubuntu but I has similar on Mac,so it is the theme engine that adds that white border?

Answer by Starx

May be it is outline or border

Try

input {
   padding:0;
   margin: 0;
   border: none;
   outline: none;
}

Update: I cannot duplicate your problem on my system. This is what i see

enter image description here

Read more

csv to mysql loading

Question by Tzook Bar Noy

Im trying to upload this csv file to mysql on my hosting.

The csv is built by two collums:
alias, id

and than each row contains the data.
here is an image
a screenshot of my csv file

But the mysql rejects me.
why is that?

Answer by sam yi

You can also open up csv from excel and generate series of insert statements. Not the best solution but might be useful if you’re looking for something quick and dirty.

Answer by Starx

Solution using PHP

$file = 'path/to.csv'; 

$lines = file($file);
$firstLine = $lines[0];
foreach ($lines as $line_num => $line) {
    if($line_num==0) { continue; } //escape the header column
    $arr = explode(",",$line);
    $column1= $arr[0];
    $column2= $arr[1];

    echo $column1.$column2."<br />";
        //put the mysql insert statement here
}
Read more

can I use ul li instead of select dropdown and with jquery make it part of a form?

Question by sandrophoto

I went really long way trying to rewrite select to ul li and style it accordingly. But I’m getting really annoyed with the weight of code and minor annoyances on the way.

So I’m thinking to ditch the idea completely, and just use normal ul li menu and some kind of javascript to make it function like select (for form submission etc).

So is this possible? any example code you can give me?

My concerns is Cross browser compatibility.

Answer by Starx

Lovely idea. I just made one in the fiddle check it out here.

Read more

Certain properties don't transfer over from external style sheet

Question by Adam

So I’m currently designing a website, and I’m using the same CSS for every page. Originally, I had it included in each individual document, however it got annoying having to change it on every page, so instead I set them all to work off an external style sheet. Now, it worked for the most part, however a couple properties stopped working, namely text-align and float. What’s weird is that if you include those properties in an internal style sheet, it starts working again. I’m guessing it has to do with some sort of priority thing, but I’m wondering why those specific properties don’t work, and if there’s any way of specifying those properties in an external style sheet. Thanks!

CSS:

    div.box1
    {
        border-width:0px;
        text-align:left
    }
    img.floatLeft
    { 
        float: left; 
        margin: 5px;  
    }

    img.floatRight
    { 
        float: right;  
        margin: 5px;  
     }

HTML:

<div class="box1">
<font face="helvetica">
    TEXT TEXT TEXT <br><br><br>
    <b>NAME</b>
    <br>
    <img src="NAME" class="floatRight">
    TEXT TEXT TEXT<br><br>
    <b>NAME2</b>
    <br>
    <img src="NAME2" width="214" height="130" class="floatLeft">
    TEXT TEX TEXT
</font>
</div>

Answer by Starx

There is a typo at text-align:left. You are missing a semicolon ; to terminate the statement. Rest is fine.

Your left floated image does not have any attribute src, height or width so it will basically not show itself in the DOM.

See a working demo

Read more
...

Please fill the form - I will response as fast as I can!