I’m trying to write a if code, but can't figure out how.
In my database table i have the primary key id.
In the table i have objekt_nr & element_nr.
Now, before i call an INSTERT i need to check if objekt_nr with element_nr already exist.
If objekt_nr With element_nr exist. Then UPDATE instead of INSTERT. Only id can be unique.
example of table:
id......objekt_nr......element_nr
1.......1...............1
2.......1...............2
3.......1...............3
4.......2...............1
5.......2...............2
PHP:
if(isset($_POST["Import"])){
echo 'Fortsätt...<br />';
echo $path=$_FILES["file"]["tmp_name"];
//Load file into PHPExcel
$objPHPExcel = PHPExcel_IOFactory::load($path);
//Loop threw file to get data
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = 'J'; //$worksheet->getHighestColumn(''); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
//Echo file info
echo "<br>The worksheet ".$worksheetTitle." has ";
echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
echo ' and ' . $highestRow . ' row.';
echo '<br>Data: <table border="1"><tr>';
//Loop threw colum, rows and cells
for ($row = 2; $row <= $highestRow; ++ $row) {
echo '<tr>';
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getCalculatedValue();
//$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
echo '<td>' . $val . '<br></td>';
}
echo '</tr>';
}
echo '</table>';
}
for ($row = 2; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getCalculatedValue();
}
// Prepare Query
$query = "INSERT INTO phpexcel(
objekt_nr,
objekt_rev,
element_nr,
element_hojd,
element_typ,
element_langd,
element_oppningar,
element_vikt,
element_ritare,
element_status)
VALUES (
:objekt_nr,
:objekt_rev,
:element_nr,
:element_hojd,
:element_typ,
:element_langd,
:element_oppningar,
:element_vikt,
:element_ritare,
:element_status
)";
// Security measures
$query_params = array(
':objekt_nr' => $val[0],
':objekt_rev' => $val[1],
':element_nr' => $val[2],
':element_hojd' => $val[3],
':element_typ' => $val[4],
':element_langd' => $val[5],
':element_oppningar' => $val[6],
':element_vikt' => $val[7],
':element_ritare' => $val[8],
':element_status' => $val[9]
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
//echo $query."\n";
}
}
Two options here.
1) Make "objekt_nr" field a PRIMARY or UNIQUE key and use REPLACE instead of INSERT (http://dev.mysql.com/doc/refman/5.0/en/replace.html). This is pretty much #hd 's answer in the comments.
2) Check for an existing "objekt_nr" and "element_nr" and run the appropriate query
$check_duplicate_query = "SELECT COUNT(*) FROM phpexcel WHERE objekt_nr = ':objekt_nr' AND element_nr = ':element_nr'";
$stmt = $db->prepare($check_duplicate_query);
$result = $stmt->execute($query_params);
$rows = $stmt->fetch(PDO::FETCH_NUM);
if($rows[0] > 0) {
//UPDATE
} else {
//INSERT
}
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
EDIT:
Just thought of a 3rd option
Create another field "objekt_element_nr" and set this field to unique.
This field gets assigned objekt and element number combination, which from your example should be unique.
e.g. 1_1, 1_2, 1_3, 2_1, 2_2, etc.
Then simply use the REPLACE function I linked to above.
Your $query_params would look like
$query_params = array(
':objekt_nr' => $val[0],
':objekt_rev' => $val[1],
':element_nr' => $val[2],
':objekt_element_nr' => $val[0].'_'.$val[2]
':element_hojd' => $val[3],
':element_typ' => $val[4],
':element_langd' => $val[5],
':element_oppningar' => $val[6],
':element_vikt' => $val[7],
':element_ritare' => $val[8],
':element_status' => $val[9]
);
Related
I need help with this. I must pass a PHP MySQL function to CodeIgniter, but it does not show me the data, it stops right in if(array_key_exists($pos, $rs))
Does the query well but does not enter the conditional if
Any solution?
This is my Code in CodeIgniter
public function table($hour, $row)
{
global $rs;
if ($rs === null)
{
$this->db->select("CONCAT(t.tbl_row, '_', t.tbl_col) as pos, t.tbl_id, t.sub_id, s.sub_name", false);
$this->db->join('redips_timetable AS t', 't.sub_id = s.sub_id');
$rs = $this->db->get('redips_subject AS s')->result();
}
echo '<tr>';
echo '<td class="mark dark">' . $hour . '</td>';
for ($col = 1; $col <= 5; $col++)
{
echo '<td>';
$pos = $row . '_' . $col;
if(array_key_exists($pos, $rs))
{
$elements = $rs[$pos];
$id = $elements['sub_id'] . 'b' . $elements['tbl_id'];
$name = $elements['sub_name'];
$class = substr($id, 0, 2);
echo "<div id=\"$id\" class=\"redips-drag $class\">$name</div>";
}
echo '</td>';
}
echo "</tr>\n";
}
Original MySQL code
function table($hour, $row) {
global $rs;
// if $rs is null then query database (this should be executed only once - first time)
if ($rs === null)
{
// first column of the query is used as key in returned array
$rs = sqlQuery("select concat(t.tbl_row,'_',t.tbl_col) as pos, t.tbl_id, t.sub_id, s.sub_name
from redips_timetable t, redips_subject s
where t.sub_id = s.sub_id", 0);
}
print '<tr>';
print '<td class="mark dark">' . $hour . '</td>';
// column loop starts from 1 because column 0 is for hours
for ($col = 1; $col <= 5; $col++) {
// create table cell
print '<td>';
// prepare position key in the same way as the array key looks
$pos = $row . '_' . $col;
// if content for the current table cell exists
if (array_key_exists($pos, $rs)) {
// prepare elements for defined position (it can be more than one element per table cell)
$elements = $rs[$pos];
// id of DIV element will start with sub_id and followed with 'b' (because cloned elements on the page have 'c') and with tbl_id
// this way content from the database will not be in collision with new content dragged from the left table and each id stays unique
$id = $elements[2] . 'b' . $elements[1];
$name = $elements[3];
$class = substr($id, 0, 2); // class name is only first 2 letters from ID
print "<div id=\"$id\" class=\"redips-drag $class\">$name</div>";
}
// close table cell
print '</td>';
}
print "</tr>\n";
}
/*
if you need find array key
you got object in $rs varible
( $rs = $this->db->get('redips_subject AS s')->result(); )
so need convert obj to array in for each loop
*/
public function table($hour, $row)
{
global $rs;
if ($rs === null)
{
$this->db->select("CONCAT(t.tbl_row, '_', t.tbl_col) as pos, t.tbl_id, t.sub_id, s.sub_name", false);
$this->db->join('redips_timetable AS t', 't.sub_id = s.sub_id');
$rs = $this->db->get('redips_subject AS s')->result();
}
echo '<tr>';
echo '<td class="mark dark">' . $hour . '</td>';
for ($col = 1; $col <= 5; $col++)
{
$arr = get_object_vars($rs[$col]);
echo '<td>';
$pos = $row . '_' . $col;
if(array_key_exists($pos, $arr))
{
$elements = $arr[$pos];
$id = $elements['sub_id'] . 'b' . $elements['tbl_id'];
$name = $elements['sub_name'];
$class = substr($id, 0, 2);
echo "<div id=\"$id\" class=\"redips-drag $class\">$name</div>";
}
echo '</td>';
}
echo "</tr>\n";
}
I want to reorder table rows according to a given php array.
$table = $_POST["table"];
$rlist = json_decode( $_POST['b'], true );
foreach ($rlist as $value) {
$i = array_search($value, $rlist);
$i+=1;
echo "<div>" . $i . "</div>";
}
This works fine. Result is 1 2 3 4 5 ...
But:
foreach ($rlist as $value) {
$i = array_search($value, $rlist);
$i+=1;
try {
$stmt = $db->prepare('UPDATE ' . $table. ' SET sort = :sort WHERE title = :title') ;
$stmt->execute(array(
':sort' => $i,
':title' => $value,
));
exit;
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
This doesn't work completely. The result in the sort column is: 1 1 3 4 5...
Does this work as expected?
foreach ($rlist as $iPos => $value) {
try {
$stmt = $db->prepare('UPDATE ' . $table. ' SET sort = :sort WHERE title = :title') ;
$stmt->execute(array(
':sort' => $iPos + 1,
':title' => $value,
));
}catch(PDOException $e) {
echo $e->getMessage();
}
}
There's an "exit" statement in the loop that prevents it from iterating. The corrected code should be:
foreach ($rlist as $value) {
$i = array_search($value, $rlist);
$i+=1;
try {
$stmt = $db->prepare('UPDATE ' . $table. ' SET sort = :sort WHERE title = :title') ;
$stmt->execute(array(
':sort' => $i,
':title' => $value,
));
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
I'm using PHPExcel to import xls to mysql.
I recently switched connection to PDO.
But then an error accord.
Fields in my xls that is NULL are no longer accepted.
Why? How can i change my code to accept NULL value?
PHP:
if(isset($_POST["Import"])){
echo 'Fortsätt...<br />';
echo $path=$_FILES["file"]["tmp_name"];
//Load file into PHPExcel
$objPHPExcel = PHPExcel_IOFactory::load($path);
//Loop threw file to get data
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = 'J'; //$worksheet->getHighestColumn(''); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
//Echo file info
echo "<br>The worksheet ".$worksheetTitle." has ";
echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
echo ' and ' . $highestRow . ' row.';
echo '<br>Data: <table border="1"><tr>';
//Loop threw colum, rows and cells
for ($row = 2; $row <= $highestRow; ++ $row) {
echo '<tr>';
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getCalculatedValue();
//$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
echo '<td>' . $val . '<br></td>';
}
echo '</tr>';
}
echo '</table>';
}
for ($row = 2; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getCalculatedValue();
}
// Prepare Query
$query = "INSERT INTO table(
objekt_nr,
objekt_rev,
element_nr,
element_hojd,
element_typ,
element_langd,
element_oppningar,
element_vikt,
element_ritare,
element_status)
VALUES (
:objekt_nr,
:objekt_rev,
:element_nr,
:element_hojd,
:element_typ,
:element_langd,
:element_oppningar,
:element_vikt,
:element_ritare,
:element_status
)";
// Security measures
$query_params = array(
':objekt_nr' => $val[0],
':objekt_rev' => $val[1],
':element_nr' => $val[2],
':element_hojd' => $val[3],
':element_typ' => $val[4],
':element_langd' => $val[5],
':element_oppningar' => $val[6],
':element_vikt' => $val[7],
':element_ritare' => $val[8],
':element_status' => $val[9]
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
To accept a NULL value you have to edit the database table, not the code. Your message error is generated by MySQL, not the PHP.
this scripts reads and excel file and put them into a table and show them . the problem here is i want my data in cell to show green if they are above 0 and red if they are less than 0 this is my script and i dont know why it doesnt work !! every thing is fine untill line 53 !!wich i set if for val above 0 !! can any one help ?? thnkx in advance !!!
`
<?php
require 'Classes/PHPExcel.php';
require_once 'Classes/PHPExcel/IOFactory.php';
$conn = mysql_connect("localhost","datanew","datanew");
mysql_select_db("datanew",$conn);
$path = "1.xlsx";
$objPHPExcel = PHPExcel_IOFactory::load($path);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
echo '<table><tr>';
for ($row = 1; $row <= $highestRow; ++ $row) {
echo '<tr>';
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
echo '<td>' . $val . '<br></td>';
}
echo '</tr>';
}
echo '</table>';
}
for ($row = 2; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getValue();
} }
?>
<?php
if($val > 0) {?>
<td style="color:#06e716;"></td>
<?php } else { ?>
<td style="color:#e70630;"></td>
<?php } ?>`
$val is an array, you need to use count function
try
if(count($val)>0){
}else{
}
Coming up empty on this one and could use some insight.
I'm try to select only certain column_names (not column data) to set as a header for CSV file.
Right now, I can only pull all of the column names with
$result = mysql_query("SHOW COLUMNS FROM ".$table);
The problem is that it pulls all of the column names and I'm only wanting certain columns' data. To get the data values this query is working perfectly:
$values = mysql_query("SELECT ".$columns." FROM ".$table." WHERE channel_id=26");
How do I select or show only the column names for the columns I list out in $columns, for example?
EDIT - I'm adding my full PHP here to provide more context. Line 7 is my problem.
<?php
$table = 'exp_channel_data'; // table we want to export
$columns = 'entry_id, field_id_26, field_id_27, '; // only the columns we want to show
$file = 'registrations-from-web'; // csv name.
$result = mysql_query("SHOW COLUMNS FROM ".$table);
$count = mysql_num_rows($result);
$csv_output = "";
if ($count > 0)
{
while ($row = mysql_fetch_assoc($result))
{
$csv_output .= $row['Field'].", ";
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT ".$columns." FROM ".$table." WHERE channel_id=26");
while ($rowr = mysql_fetch_row($values))
{
for ($j=0; $j<$count; $j++)
{
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("d-m-Y_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>
If you know the name of the columns, you can add them and/or print them directly from an array.
If you want to have access to the ones retrieved from the query anyway, you can $result = mysql_fetch_assoc($values); per row, and the keys will always contain the name of the columns since the resulting array is associative.
Try:
$values = mysql_query('SELECT '. $columns. ' FROM '.
$table. ' WHERE channel_id = 26');
print_r(mysql_fetch_assoc($values));
For an insight of the contents of the resulting array.
Now try:
$first = 1;
echo '<table>';
while ($assoc = mysql_fetch_assoc($values))
{
echo '<tr>';
if ($first)
{
foreach ($assoc as $key => $value)
echo "<th>$key</th>\n";
$first = 0;
}
else
{
foreach ($assoc as $key => $value)
echo "<td>$value</td>\n";
}
echo '</tr>';
}
echo '</table>';
If what you want is to print a CSV file:
$columns = Array();
$values = Array();
$first = 1;
for ($i = 0; $assoc = mysql_fetch_assoc($values); ++$i)
{
if ($first)
{
foreach ($assoc as $key => $value)
$columns[] = $key;
$first = 0;
}
else
{
foreach ($assoc as $key => $value)
$values[$i][] = $value;
}
}
$out = fopen('php://output', 'w');
fputcsv($out, $columns);
foreach ($values as $line)
fputcsv($out, $line);
The foreach is repeated on purpose so this example is more clear.
You can query the USER_TAB_COLUMNS table for table column metadata.
SELECT table_name, column_name, data_type, data_length
FROM USER_TAB_COLUMNS
WHERE table_name = 'yourTableName'
so you might be using SQL server - for SQL server use this...
SELECT [name] AS [Column Name]
FROM syscolumns
WHERE id = (SELECT id FROM sysobjects WHERE type = 'V' AND [Name] = 'Your table name')
Type = 'V' for views Type = 'U' for tables
I don't know why I was missing this, but since I'm already having to list out the columns I need, I just needed to turn that string into an array to make is it work.
$column_names = Array($columns);
then later use
$csv_output .= '"'.$rowr[$j].'",';
That worked perfectly without redoing my entire code.