Link to home
Start Free TrialLog in
Avatar of doctorbill
doctorbillFlag for United Kingdom of Great Britain and Northern Ireland

asked on

php and styles

I have the following code which is working perfectly well:

<?php
use Phppot\DataSource; require_once 'DataSource-dev.php'; $db = new DataSource(); $conn = $db->getConnection(); if (isset($_POST["import"])) {          $fileName = $_FILES["file"]["tmp_name"];          if ($_FILES["file"]["size"] > 0) {                  $file = fopen($fileName, "r");                  while (($column = fgetcsv($file, 10000, ",")) !== FALSE) {                          $userId = "";             if (isset($column[0])) {                 $userId = mysqli_real_escape_string($conn, $column[0]);             }             $userName = "";             if (isset($column[1])) {                 $userName = mysqli_real_escape_string($conn, $column[1]);             }             $password = "";             if (isset($column[2])) {                 $password = mysqli_real_escape_string($conn, $column[2]);             }             $firstName = "";             if (isset($column[3])) {                 $firstName = mysqli_real_escape_string($conn, $column[3]);             }             $lastName = "";             if (isset($column[4])) {                 $lastName = mysqli_real_escape_string($conn, $column[4]);             }             $Dev1 = "";             if (isset($column[5])) {                 $Dev1 = mysqli_real_escape_string($conn, $column[5]);             }          $NewField = "";             if (isset($column[6])) {                 $NewField = mysqli_real_escape_string($conn, $column[6]);             }                                          $sqlInsert = "INSERT into development (userId,userName,password,firstName,lastName,dev1,newfield)                    values (?,?,?,?,?,?,?)";             $paramType = "issssss";             $paramArray = array(                 $userId,                 $userName,                 $password,                 $firstName,                 $lastName,                 $Dev1,             $NewField                    );             $insertId = $db->insert($sqlInsert, $paramType, $paramArray);                          if (! empty($insertId)) {                 $type = "success";                 $message = "CSV Data Imported into the Database";             } else {                 $type = "error";                 $message = "Problem in Importing CSV Data";             }         }     } } ?> <!DOCTYPE html> <html> <head> <script src="jquery-3.2.1.min.js"></script> <style> body {     font-family: Arial;     width: 850px; } .outer-scontainer {     background: #F0F0F0;     border: #e0dfdf 1px solid;     padding: 20px;     border-radius: 2px; } .input-row {     margin-top: 0px;     margin-bottom: 20px; } .btn-submit {     background: #333;     border: #1d1d1d 1px solid;     color: #f0f0f0;     font-size: 0.9em;     width: 100px;     border-radius: 2px;     cursor: pointer; } .outer-scontainer table {     border-collapse: collapse;     width: 100%; } .outer-scontainer th {     border: 1px solid #dddddd;     padding: 8px;     text-align: left; } .outer-scontainer td {     border: 1px solid #dddddd;     padding: 8px;     text-align: left; } #response {     padding: 10px;     margin-bottom: 10px;     border-radius: 2px;     display: none; } .success {     background: #c7efd9;     border: #bbe2cd 1px solid; } .error {     background: #fbcfcf;     border: #f3c6c7 1px solid; } div#response.display-block {     display: block; } </style> <script type="text/javascript"> $(document).ready(function() {     $("#frmCSVImport").on("submit", function () {        $("#response").attr("class", "");         $("#response").html("");         var fileType = ".csv";         var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + fileType + ")$");         if (!regex.test($("#file").val().toLowerCase())) {                $("#response").addClass("error");                $("#response").addClass("display-block");             $("#response").html("Invalid File. Upload : <b>" + fileType + "</b> Files.");             return false;         }         return true;     }); }); </script> </head> <body>     <h2>Import CSV file into Mysql using PHP</h2>     <div id="response"         class="<?php if(!empty($type)) { echo $type . " display-block"; } ?>">         <?php if(!empty($message)) { echo $message; } ?>         </div>     <div class="outer-scontainer">         <div class="row">             <form class="form-horizontal" action="" method="post"                 name="frmCSVImport" id="frmCSVImport"                 enctype="multipart/form-data">                 <div class="input-row">                     <label class="col-md-4 control-label">Choose CSV                         File</label> <input type="file" name="file"                         id="file" accept=".csv">                     <button type="submit" id="submit" name="import"                         class="btn-submit">Import</button>                     <br />                 </div>             </form>         </div>                <?php             $sqlSelect = "SELECT * FROM development";             $result = $db->select($sqlSelect);             if (! empty($result)) {                 ?>             <table id='userTable'>             <thead>                 <tr>                     <th>User ID</th>           <th>User Name</th>                     <th>User PW</th>                     <th>First Name</th>                     <th>Last Name</th>           <th>Dev Details</th>          <th>New Field</th>                 </tr>             </thead> <?php                                  foreach ($result as $row) {                     ?>                                      <tbody>                 <tr>                     <td><?php  echo $row['userId']; ?></td>                     <td><?php  echo $row['userName']; ?></td>                     <td><?php  echo $row['password']; ?></td>                     <td><?php  echo $row['firstName']; ?></td>                     <td><?php  echo $row['lastName']; ?></td>                     <td><?php  echo $row['dev1']; ?></td>                <td><?php  echo $row['newfield']; ?></td>                 </tr>                     <?php                 }                 ?>                 </tbody>         </table>         <?php } ?>     </div> </body> </html>

Open in new window

I am trying to achieve the following:

I need the colour (style) of the table cell to change depending on the value of the following:

<?php  echo $row['newfield']; ?>

So, for example, if the value is "New Field Data 36", the colour will be set, if it is "New Field Data 30" , the colour will be different etc...

I have the following code but it causes the page to hang:

<?php while ($row = $result->fetch_assoc()):$style = "";
       if ($row['newfield'] == 'New Field Data 36') {     $style2 = "style='background:#ddd000;'"; }         else {             $style2 = "style='background: transparent;'";         }        if ($row['newfield'] == 'New Field Data 30'){     $style3 = "style='background:#FFa500;'"; }         else {             $style3 = "style='background: transparent;'";         }         if ($row['newfield'] == 'New Field Data 18'){     $style4 = "style='background:rgb(255,100,0);'"; }         else {             $style4 = "style='background: transparent;'";         }       if ($row['newfield'] == 'New Field Data 24'){      $style5 = "style='background:rgb(255,20,147);'";        }         else {     $style5 = "style='background: transparent;'"; }                ?>           <tbody>           <tr>                     <td><?php  echo $row['userId']; ?></td>                     <td><?php  echo $row['userName']; ?></td>                     <td><?php  echo $row['password']; ?></td>                     <td><?php  echo $row['firstName']; ?></td>                     <td><?php  echo $row['lastName']; ?></td>                     <td><?php  echo $row['dev1']; ?></td>                     <td <?php echo $style2 ?>></td>                     <td <?php echo $style3 ?>></td>                     <td <?php echo $style4 ?>></td>            <td><?php echo $style5 ?>><?php  echo $row['newfield']; ?></td>                 </tr>                    <?php                 }                 ?>                 </tbody>         </table>         <?php } ?>

Open in new window



ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of doctorbill

ASKER

I get this error:
Fatal error: Uncaught Error: Call to undefined function ImportCsv() in C:\wamp64\www\Development\import-csv\development_edit_newfield.php:12 Stack trace: #0 {main} thrown in C:\wamp64\www\Development\import-csv\development_edit_newfield.php on line 12 
ImportCsv.php
<?php
use Phppot\DataSource;

require_once 'DataSource-dev.php';
$db = new DataSource();
$conn = $db->getConnection();

if (isset($_POST["import"])) {
    
    $fileName = $_FILES["file"]["tmp_name"];
    
    if ($_FILES["file"]["size"] > 0) {
        
        $file = fopen($fileName, "r");
        
        while (($column = fgetcsv($file, 10000, ",")) !== FALSE) {
            
            $userId = "";
            if (isset($column[0])) {
                $userId = mysqli_real_escape_string($conn, $column[0]);
            }
            $userName = "";
            if (isset($column[1])) {
                $userName = mysqli_real_escape_string($conn, $column[1]);
            }
            $password = "";
            if (isset($column[2])) {
                $password = mysqli_real_escape_string($conn, $column[2]);
            }
            $firstName = "";
            if (isset($column[3])) {
                $firstName = mysqli_real_escape_string($conn, $column[3]);
            }
            $lastName = "";
            if (isset($column[4])) {
                $lastName = mysqli_real_escape_string($conn, $column[4]);
            }
            $Dev1 = "";
            if (isset($column[5])) {
                $Dev1 = mysqli_real_escape_string($conn, $column[5]);
            }
         $NewField = "";
            if (isset($column[6])) {
                $NewField = mysqli_real_escape_string($conn, $column[6]);
            }           
                 
            $sqlInsert = "INSERT into development (userId,userName,password,firstName,lastName,dev1,newfield)
                   values (?,?,?,?,?,?,?)";
            $paramType = "issssss";
            $paramArray = array(
                $userId,
                $userName,
                $password,
                $firstName,
                $lastName,
                $Dev1,
            $NewField
      
            );
            $insertId = $db->insert($sqlInsert, $paramType, $paramArray);
            
            if (! empty($insertId)) {
                $type = "success";
                $message = "CSV Data Imported into the Database";
            } else {
                $type = "error";
                $message = "Problem in Importing CSV Data";
            }
        }
    }
}
?>

Open in new window

Read line 4ff. in my code outline again.
4ff ?
Not sure where 4ff is
ff. from Latin folium, abl. folio. The next page. In general meaning "and the following". Thus line 4 and the following lines.
Still unclear what I am supposed to be looking at/correcting
Line 4 and the following lines - what am  I suppose to be correcting?
// ToDo: Implement ImportCsv() function in file ImportCsv.php.
Yes - I see that but I am unsure how to format the function in the ImportCsv.php file
How do I change the posted code (above) into a function?
You'll find all you need to know at Functions.
Sorry - really doesn't help
I am not familiar with creating functions
Could you give me pointers on how I change the posted code above (ImportCsv.php) into a function
ok
Managed to get the code working but the css is not changing the colours. The CSS is working for the other fields:
CSS:
<style>
body {
    font-family: Arial;
    width: 850px;
}

.outer-scontainer {
    background: #F0F0F0;
    border: #e0dfdf 1px solid;
    padding: 20px;
    border-radius: 2px;
}

.input-row {
    margin-top: 0px;
    margin-bottom: 20px;
}

.btn-submit {
    background: #333;
    border: #1d1d1d 1px solid;
    color: #f0f0f0;
    font-size: 0.9em;
    width: 100px;
    border-radius: 2px;
    cursor: pointer;
}

.outer-scontainer table {
    border-collapse: collapse;
    width: 100%;
}

.outer-scontainer th {
    border: 1px solid #dddddd;
    padding: 8px;
    text-align: left;
}

.outer-scontainer td {
    border: 1px solid #dddddd;
    padding: 8px;
    text-align: left;
}

#response {
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 2px;
    display: none;
}

.success {
    background: #c7efd9;
    border: #bbe2cd 1px solid;
}

.error {
    background: #fbcfcf;
    border: #f3c6c7 1px solid;
}

div#response.display-block {
    display: block;
}
.cssStyle36 {
    background: #ffffff;
    border: #e0dfdf 1px solid;
    padding: 20px;
    border-radius: 2px;
}
</style>

Am I correct in calling the css ".cssStyle36" ".cssStyle30" etc.....
Yup.
Then I have no idea why it is not working
The rest of the CSS in the stylesheet is working
When I import the data (which works), the "newfield" value of  "New Data Field 36" does not change colour in the table
I am just using this as an example
Post a concise and complete example.
This is the code for the form page:
<?php
use Phppot\DataSource;

require_once 'DataSource-dev.php';
// ToDo: Implement ImportCsv() function in file ImportCsv.php.
require_once 'ImportCsv.php';

if (isset($_POST["import"])) {
    $fileName = $_FILES["file"]["tmp_name"];
    if ($_FILES["file"]["size"] > 0) {
        // $type and $message are output parameter of the ImportCsv() function.
        ImportCsv($fileName, $type, $message);
    }
}

// Multiline string for better readbility.
// ToDo: Define the CSS stlyes in your CSS style file included in line 42.
$sqlSelect = <<<EOD
    SELECT  userId,
            userName,
            password,
            firstName,
            lastName,
            dev1,
            newfield,
            CASE newfield
                WHEN 'New Field Data 36' THEN 'cssStyle36'
                WHEN 'New Field Data 30' THEN 'cssStyle30'
                WHEN 'New Field Data 18' THEN 'cssStyle18'
                WHEN 'New Field Data 24' THEN 'cssStyle24'
                ELSE 'cssStyleDefault'
            END As cssStyle
    FROM    development
    ORDER BY lastName,
            firstName;
EOD;
$data = $db->select($sqlSelect);

?>
<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" type="text/css"href="mystyle.css">
    <script src="jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#frmCSVImport").on("submit", function () {
                $("#response").attr("class", "");
                $("#response").html("");
                var fileType = ".csv";
                var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + fileType + ")$");
                var result = regex.test($("#file").val().toLowerCase());
                if (!result) {
                    $("#response").addClass("error");
                    $("#response").addClass("display-block");
                    $("#response").html("Invalid File. Upload : <b>" + fileType + "</b> Files.");
                }

                return result;
            });
        });
    </script>
</head>

<body>
    <h2>Import CSV file into Mysql using PHP</h2>
    <div id="response"
        class="<?php if(!empty($type)) { echo $type . " display-block"; } ?>">
        <?php if(!empty($message)) { echo $message; } ?>
    </div>

    <div class="outer-scontainer">
        <div class="row">
            <form class="form-horizontal" action="" method="post"
                name="frmCSVImport" id="frmCSVImport"
                enctype="multipart/form-data">
                <div class="input-row">
                    <label class="col-md-4 control-label">Choose CSV
                        File</label> <input type="file" name="file"
                        id="file" accept=".csv">
                    <button type="submit" id="submit" name="import"
                        class="btn-submit">Import</button>
                    <br />

                </div>
            </form>
        </div>

<?php
if (!empty($data)) {
?>
        <table id='userTable'>
            <thead>
                <tr>
                    <th>User ID</th>
                    <th>User Name</th>
                    <th>User PW</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Dev Details</th>
                    <th>New Field</th>
                </tr>
            </thead>
<?php
    foreach ($data as $row) {
?>

            <tbody>
                <tr style="<?php echo $row['cssStyle']; ?>">
                    <td><?php echo $row['userId']; ?></td>
                    <td><?php echo $row['userName']; ?></td>
                    <td><?php echo $row['password']; ?></td>
                    <td><?php echo $row['firstName']; ?></td>
                    <td><?php echo $row['lastName']; ?></td>
                    <td><?php echo $row['dev1']; ?></td>
                    <td><?php echo $row['newfield']; ?></td>
                </tr>
<?php
    } /* foreach */
?>
            </tbody>
        </table>
<?php
} /* if */
?>
    </div>

</body>
</html>

Open in new window

This is the CSS:
body {
    font-family: Arial;
    width: 850px;
}

.outer-scontainer {
    background: #F0F0F0;
    border: #e0dfdf 1px solid;
    padding: 20px;
    border-radius: 2px;
 width: 850px;
}

.input-row {
    margin-top: 0px;
    margin-bottom: 20px;
}

.btn-submit {
    background: #333;
    border: #1d1d1d 1px solid;
    color: #f0f0f0;
    font-size: 0.9em;
    width: 100px;
    border-radius: 2px;
    cursor: pointer;
}

.outer-scontainer table {
    border-collapse: collapse;
    width: 100%;
}

.outer-scontainer th {
    border: 1px solid #dddddd;
    padding: 8px;
    text-align: left;
}

.outer-scontainer td {
    border: 1px solid #dddddd;
    padding: 8px;
    text-align: left;
}

#response {
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 2px;
    display: none;
}

.success {
    background: #c7efd9;
    border: #bbe2cd 1px solid;
    width: 870px;
}

.error {
    background: #fbcfcf;
    border: #f3c6c7 1px solid;
    width: 870px;
}

div#response.display-block {
    display: block;
}
.cssStyle36 {
    background: #fbcfcf;
    border: #e0dfdf 12px solid;
    padding: 20px;
    border-radius: 2px;
}


Open in new window


SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Changed to:
<tr style="<?php echo $row['cssStyle36']; ?>">

Still not working 
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Perfect
Thanks so much for your patience and excellent code
The code you supplied at the start was working pretty much perfectly - just me missing some obvious points
Since this is all front end, let's put aside what is happing in your php for a moment.

Output your html and let's take a look at that. There is probably an error in the generated html/css that will be easier to view looking at the rendered code.  

Can you post a link to your test page?  Or recreate the rendered html in codepen, jsfiddle or something else? Or you can do this on your own by running the page, look at your browser console by hitting f12 or right click on the portion of output that is not working and select, "inspect". That will take you to the code and show the css that is affected.

If you are only concerned with colors, I personally would take that out of the back end and especially not use a select statement to calculate this.  If you do choose server side, it would be faster (with a lot of data/usage) to do this via php. Figuring out the color in javascript will be the fastest though.

If you do want to do php, I would put it in a switch statement or maybe searching an array_search().

For now, let's check out your rendered html and go with what you have at this moment.