Inserting Script Output TinyMCE and Jquery - php

I have a script that creates a basic table layout structure and I'm trying to use AJAX with jQuery to input the output of that script into a TinyMCE textarea. I wrote the script in PHP and it works perfectly well if I open up the script directly.
What I'm trying to do is let the user choose something from a dropdown (in this case, a product) and it return a table filled with the relevant data for that product. I use the following script to insert it into the textarea:
$('#product_id').change(function(e) {
product_id = $(this).val();
$.ajax({
url: 'http://<? echo $_SERVER['HTTP_HOST']; ?>/includes/ajax.php',
type: 'POST',
data: { product_choice: true, product_id: product_id },
success: function(data) {
$('#mce_1').val(data);
}
});
});
'data' does return but when it's placed in the tinyMCE textarea, it shows the following error(the script carries on and outputs the table):
Warning: Invalid argument supplied for foreach() in /home/sites/very-dev.co.uk/public_html/cms/includes/ajax.php on line 71Warning: Invalid argument supplied for foreach() in /home/sites/very-dev.co.uk/public_html/cms/includes/ajax.php on line 100
Those two foreachs which error are:
foreach($product_data as $key=>$product): and foreach($product_data as $product):
// Connect to database
$link = mysqli_connect(DBHOST,DBUSER,DBPASS,DBNAME);
// check connection //
if (mysqli_connect_errno()):
return printf("Connect failed: %s\n", mysqli_connect_error());
endif;
$col_qry = mysqli_query($link,"
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'cms_plugins_products_models'
AND column_name != 'id'
AND column_name != 'product_id';")
or die(mysqli_error($link)
);
while($col_row = mysqli_fetch_object($col_qry)):
$col_names_array[] = $col_row->column_name;
endwhile;
$qry = "SELECT product.name AS product_name, product.id, model.*, image.src AS thumb
FROM cms_plugins_products AS product
LEFT JOIN cms_plugins_products_models AS model
ON (product.id=model.product_id)
LEFT JOIN cms_plugins_products_images AS image
ON (product.id=image.product_id)
AND (image.is_thumb=1)
WHERE product.id='" . $_GET['product_id'] . "'";
$result = mysqli_query($link, $qry) or die(mysqli_error($link));
while($row = mysqli_fetch_object($result)):
foreach($col_names_array as $column):
$columns = explode('_', $column);
if($column != 'name' && $column != 'description'):
$components_qry = "SELECT name
FROM cms_plugins_products_components_" . $columns[0] . "
WHERE id='" . $row->$column . "'";
$components_result = mysqli_query($link, $components_qry) or die(mysqli_error($link));
$components_row = mysqli_fetch_object($components_result);
endif;
if($columns[0] == 'name'):
$product_data[$row->product_name][$row->name][$columns[0]] = $row->name;
elseif($columns[0] == 'description'):
$product_data[$row->product_name][$row->name][$columns[0]] = $row->description;
else:
$product_data[$row->product_name][$row->name][$columns[0]] = $components_row->name;
endif;
endforeach;
$thumb = $row->thumb;
endwhile; ?>
<table>
<thead>
<tr>
<th></th> <?
$i = 0;
foreach($product_data as $key=>$product):
foreach($product_data[$key] as $key2=>$model): ?>
<th <? if($i == 1): echo 'id="recommended"'; endif; ?>> <?
switch($i):
case 0:
echo 'Basic';
break;
case 1:
echo 'Mid';
break;
case 2:
echo 'Pro';
break;
endswitch; ?>
<div>
<img alt="<? echo $key; ?>" src="http://cms.very-dev.co.uk<? echo $thumb; ?>">
</div>
<h5><? echo $key2; ?></h5>
<p><? echo $product_data[$key][$key2]['description']; ?></p>
<a>Customise?</a>
</th> <?
$i++;
endforeach;
endforeach; ?>
</tr>
</thead>
<tbody> <?
foreach($product_data as $product):
$i = 0;
foreach($product as $model):
foreach($model as $key2=>$component): ?>
<tr> <?
if($key2 != 'name' && $key2 != 'description'): ?>
<td><? echo $key2; ?></td> <?
foreach($product as $key=>$model): ?>
<td><? echo $product[$key][$key2]; ?></td> <?
endforeach;
endif; ?>
</tr> <?
endforeach;
if($i == 0): exit(); endif;
$i++;
endforeach;
endforeach; ?>
</tbody>
</table>
It's probably quite a simple problem that I'm not seeing, any help on this one?

After looking at the code more carefully, it was a simple error. I was using a GET for the product_id but upon include that of course isn't set so it's breaking down but doesn't error out because of it being an include. Fixed simply by sending the GET variable along.

Related

How to turn a table vertical using PHP

I am just learning PHP ,and I want to create a table that display echo data that I submit to my database , the problem I have that the table displayed horizontally by default as you see Horizontal default table this my script
<table >
<tr>
<th>Name</th>
<th>Age</th>
<th>Height</th>
</tr>
<?php
$conn = mysqli_connect("localhost", "root", "", "class");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Name, Age, Height FROM student order by Name desc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Name"]. "</td><td>" . $row["Age"] . "</td><td>"
. $row["Height"]. "</td></tr>";
}
echo "</table>";
} else //{ echo "0 results"; }//
$conn->close();
?>
</table>
but I want it to be echoed vertically instead like this VERTICAL RESULT I WANT and I tried to change html in echo in my PHP code but I can't get the result at all and the shape of the table is far away from what I want and this is the full script of my page .
Like everyone else said, you should convert your horizontal array into a vertical one.
Of course it should be a universal function to convert any query result, as opposed to hardcoding the row headings. The idea is to get each row's array keys and use them as the keys for the new array and then add each corresponding value to the new array item.
Here is how it's done in mysqli:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect('127.0.0.1','root','','test');
$mysqli->query("set names 'UTF8'");
$data = [];
$res = $mysqli->query("SELECT Name, Age, Height FROM student order by Name desc");
while ($row = $res->fetch_assoc()) {
foreach(array_keys($row) as $key) {
$data[$key][] = $row[$key];
}
}
and then you get an array with desired structure which you can output using the code from ROOT's answer:
<table border="1">
<?php foreach($data as $key => $val): ?>
<tr>
<td><?= $key ?></td>
<?php foreach($val as $field): ?>
<td><?= $field ?></td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
I mocked your data into normal array, I used a while loop to create a new Array and create the format that we need to be able to flip the columns into rows, here is what I think you want:
<?php
$users = [
[
'name'=> 'James',
'height'=> 1.75,
'age'=> 18,
],
[
'name'=> 'Bill',
'height'=> 170,
'age'=> 16,
]
];
$newArr = [];
foreach($users as $key => $val) {
$newArr['name'][$i] = $val['name'];
$newArr['age'][$i] = $val['age'];
$newArr['height'][$i] = $val['height'];
$i++;
}
?>
<table border="1">
<?php foreach($newArr as $key => $val): ?>
<tr>
<td><?php echo $key; ?></td>
<?php foreach($val as $field): ?>
<td><?php echo $field; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach ?>
</table>
It's not a good idea ! if you have a lot of ROW you will generate a long table not visible for user in screen.
if you want to do it after all you can change table structure but you will not respect html table structure.
I will give you a
Dirty code
<table>
<tr>
<th>Name</th>
<?php foreach ($row as $value) { ?><td><?php echo$value["Name"]; ?></td>
<?php } ?>
</tr>
<tr>
<th>Age</th>
<?php foreach ($row as $value) { ?>
<td><?php echo $value["Age"]; ?></td>
<?php } ?>
</tr>
<tr>
<th>Height</th>
<?php foreach ($row as $value) { ?>
<td><?php echo $value["Height"]; ?></td>
<?php } ?>
</tr>
</table>
I recommand to USE CSS instead a table

PHP Undefined index when attempting to access key in array that exists

I have a number of rows (ingredients) in a table in my database, I'm using the following code to iterate and populate my view with the name of each, but I want to be able to display the children/parents (columns in the DB) of each item, I'm able to log out the values correctly but when I try to echo as below I'm receiving "Message: Undefined index: parents" & "Message: Undefined index: children";
<?php foreach ($ingredient as $row => $key) { ?>
<tr>
<td><?php echo $row + 1; ?> </td>
<td><?php echo $key['name']; ?> </td>
<?php ChromePhp::log($key['parents']); ?>
<td><?php echo $key['parents']; ?> </td>
<?php ChromePhp::log($key['children']); ?>
<td><?php echo $key['children']; ?> </td>
<td>
</tr>
<?php } ?>
I'm confused as I have no issue logging it out.
I assumed it may be due to null values so I assigned child/parent a string value for each row as follows;
but the error persists.
Here is the logged output in the browser;
Output of <?php ChromePhp::log($key); ?>
EDIT: Here is how I'm building the $ingredients array;
<?php
function get_ingredient()
{
$qry = "SELECT CONCAT(UPPER(LEFT(i.name, 1)), LCASE(SUBSTRING(`name`, 2))) as name,i.id as id,'ingredient' as type, i.parents as parents, i.children as children FROM `ingredient` i WHERE i.is_del=0 order by i.name asc";
$qry = $this->db->query($qry);
if ($qry->num_rows() > 0) {
$ingr = $qry->result_array();
} else {
$ingr = array();
}
}
?>
I assume I'm missing something fundamental, any advise would be most appreciated. Cheers.
My array had two sets of data, I have resolved this by limiting the array to one set.
<?php foreach ($ingredient as $row => $key) { ?>
<tr>
<td><?php echo $row + 1; ?> </td>
<?php if(isset($key['name']) && !empty($key['name'])):?>
<td><?php echo $key['name']; ?> </td>
<?php endif;?>
<?php if(isset($key['parents']) && !empty($key['parents'])):?>
<?php ChromePhp::log($key['parents']); ?>
<td><?php echo $key['parents']; ?> </td>
<?php endif;?>
<?php if(isset($key['children']) && !empty($key['children'])):?>
<?php ChromePhp::log($key['children']); ?>
<td><?php echo $key['children']; ?> </td>
<?php endif;?>
</tr>
$key looks like an object so you have to access it with -> so to get value of name use $key->name,$key->parents

How to show $classname only once

I am trying to echo $classname only once.
So it shows like this for example.
Puppy Dog
1st blah blah
2nd whoever
3rd extra
at present it shows like:
Puppy Dog
1st blah blah
Puppy Dog
2nd whoever
Puppy Dog
3rd extra
<?php
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT c.* , p.* FROM result c,dogs p WHERE c.dog_id=p.dog_id";
$result = mysqli_query($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ". mysqli_error
($connection), E_USER_ERROR);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$placement = $row['placement'];
$classname = $row['class_name'];
$dog_name = $row['dog_name'];
$award = $row['award'];
?>
<table>
<tr>
<td><strong><?php echo $classname ?></strong> </td><br>
</tr>
<tr>
<td><strong><?php echo $placement, $award ?></strong> <?php echo $dog_name ?></td>
</tr>
</table>
<?php }}} ?>
Use counter to check if it is already displayed:
$ctr = 0;
while{
$classname = $row['class_name'];
if($ctr == 0){
echo $classname;
$ctr++;
}
//display the rest
...
}
So, don't know why are you using <table> inside the while loop, this will print as per your no's of rows.
Here is the basic example, you can store the values in an array than use it with your HTML:
Example:
<?php
if ($result) {
$myarr = array();
while ($row = mysqli_fetch_assoc($result)) {
$myarr[$row['class_name']][] = $row; //store values into an array against each class in group
}
}
foreach ($myarr as $key => $value) {
echo "Class Name: ". $key."<br/>"; // will print class name
foreach ($value as $fvalue) {
echo "Placement: ".$row['placement']."<br/>";; // placement
echo "Dog Name: ".$row['dog_name']."<br/>"; // dog name
echo "Award: ".$row['award']."<br/>";; // award
}
}
?>
Other solution is using incremental variable in while loop as mentioned in other answers.
You can keep track record by index in while loop like :
<?php
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT c.* , p.* FROM result c,dogs p WHERE c.dog_id=p.dog_id";
$result = mysqli_query($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ". mysqli_error
($connection), E_USER_ERROR);
if ($result) {
$i = 1;
while ($row = mysqli_fetch_assoc($result)) {
$placement = $row['placement'];
$classname = $row['class_name'];
$dog_name = $row['dog_name'];
$award = $row['award'];
?>
<table>
<tr>
<td><strong><?php if($i==1) { echo $classname; } ?></strong> </td><br>
</tr>
<tr>
<td><strong><?php echo $placement, $award ?></strong> <?php echo $dog_name ?></td>
</tr>
</table>
<?php $i++; }}} ?>
The Opening and Closing <Table> Tags should be outside your Loop if you expect to have just one Table. Even the <tr> Tags should encompass the <td> Tags if you wish to have rows containing 2 Cells like the Code below shows:
<?php
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT c.* , p.* FROM result c,dogs p WHERE c.dog_id=p.dog_id";
$result = mysqli_query ($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ".
mysqli_error($connection), E_USER_ERROR);
?>
<table>
<?php
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$placement = $row['placement'];
$classname = $row['class_name'];
$dog_name = $row['dog_name'];
$award = $row['award'];
?>
<tr>
<td>
<strong><?php echo $classname ?></strong>
<!-- DO YOU NEED THIS <BR>TAG HERE? <br> -->
</td>
<td>
<strong><?php echo $placement, $award ?></strong><?php echo $dog_name ?>
</td>
</tr>
<!-- EXCEPT IF YOU WISH TO HAVE ONE COLUMN, THE ROW BELOW IS UNNECESSARY -->
<!--
<tr>
<td>
<strong><?php echo $placement, $award ?></strong> <?php echo $dog_name ?>
</td>
</tr>
-->
<?php
} // CLOSE THE WHILE LOOP;
} // CLOSE THE IF STATMENT;
?>
</table>

php foreach break table

Im using tables to store content that's dynamically loaded. It's for a reservation form which will be responsive. What I'm looking to do is break each table row into two if there are more than 5 columns in order for the mobile version to fit on screen.
I'm sure this can be achieved by extending what I already have but can't get it to work.
Here's my current code:
<table>
<tr>
<?php foreach ($hostel->getAvailableDates() as $date): ?>
<th><?php echo $date->getDayOfTheWeek(); ?></th>
<?php endforeach ?>
</tr>
<tr>
<?php foreach ($hostel->getAvailableDates() as $date): ?>
<td>
<?php if($date->getAvailable()) { ?>
<b class="avail tick">Available</b>
<?php } else { ?>
<b class="avail cross">Unavailable</b>
<?php }?>
</td>
<?php endforeach ?>
</tr>
</table>
I'd need to break the loop for each row tr after 5 loops, then add a new row underneath.
I've been experimenting with
$max_loop = 5;
$count = 0;
But no luck so far.
I prefer to reorganize data:
<?php
$availDates = array();
foreach ($hostel->getAvailableDates() as $date) {
$availDates[] = $date;
}
$maxCols = 5;
$chunked = array_chunk( $availDates, $maxCols );
?>
<table>
<?php
foreach ($chunked as $chunk) {
?><tr>
<?php foreach ($chunk as $date): ?>
<th><?php echo $date->getDayOfTheWeek(); ?></th>
<?php endforeach; ?>
</tr>
<tr>
<?php foreach ($chunk as $date): ?>
<td>
<?php if($date->getAvailable()) { ?>
<b class="avail tick">Available</b>
<?php } else { ?>
<b class="avail cross">Unavailable</b>
<?php }?>
</td>
<?php endforeach; ?>
</tr><?php
}
?>
</table>
Look at the mod operator. It should give you what you need.
if($count % $max_loop == 0)
I hope this may help you. thanks.
<?php
$avDates = $hostel->getAvailableDates();
echo "<table><tr>";
foreach($avDates as $i=>$date){ {
if ($i == $max_loop) {
echo "</tr><tr>";
}
echo "<td>".($date->getAvailable() ? '<b class="avail tick">Available</b>' : '<b class="avail cross">Unavailable</b>')."</td>";
}
echo "</tr></table>";
?>
If the value returned by getAvailableDates is an array, you could use a for loop instead of a foreach, and check if the current index is a multiple of five, so you don't have to keep track of the count variable
$avDates = $hostel->getAvailableDates();
for ($i = 0; $i < count($avDates); $i++) {
$date = $avDates[$i];
//do your staff
//if multiple of five add another tr
if ($i % 5 == 0) {
}
}

Show only MySQL columns that exist in queried table

I have several MySQL tables that are dynamically generated into a html table one table at a time through the code below. However, the tables don't have the same columns. i.e. One table has a description column, whereas the other does not.
Is the following code the best way to have all the possible MySQL columns among the various tables in the script but only show the MySQL columns that exist for the selected table? I feel like I'm redundant by writing "isset" for every column. Thanks!
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) {
?>
<table>
<tr>
<?php if(isset($row['name'])){ ?>
<td><?php echo $row['name'];?></td>
<?php } ?>
<?php if(isset($row['description'])){ ?>
<td><?php echo $row['description']?></td>
<?php } ?>
</tr>
</table>
You might want to make your code adapt to the fields in the result set:
<?php
$result = mysqli_query($con,$query);
$fields = mysqli_fetch_fields($result);
$myaliases = array(
'column_id' => 'id'
);
?>
<table>
<tr>
<?php foreach ($fields as $field): ?>
<th><?php echo $myaliases[$field->name] ?: $field->name; ?></th>
<?php endforeach; ?>
</tr>
<?php while($row = mysqli_fetch_array($result)): ?>
<tr>
<?php foreach ($fields as $field): ?>
<td><?php echo $row[$field->name]; ?></td>
<?php endforeach; ?>
</tr>
<?php endwhile; ?>
</table>
Re comments:
I've added code above to print a table row for column headings.
I've also included an example of mapping a field name column_id to a table heading id in the output. If I define no alias for a given column, it defaults to the original field name by using the PHP 5.3 operator ?:
You could alternatively define column aliases in your SQL query like SELECT column_id AS id ...
See http://www.php.net/manual/en/mysqli-result.fetch-fields.php
You can foreach the array instead.
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
?>
<table>
<?php while($row = mysqli_fetch_array($query_select, MYSQLI_ASSOC)) { ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><?=$value?></td>
<?php } //Endforeach ?>
</tr>
<?php } //Endwhile ?>
</table>
If you need to print labels you can also use an associative array and an additional iteration to do that as well.
<?php
$query = " SELECT * FROM $tablename ";
$keys = array('name' => 'Name Label', 'description' => 'Description Label');
$query_select = mysqli_query($con,$query);
$i = 0;
?>
<table>
<?php while($row = mysqli_fetch_array($query_select, MYSQLI_ASSOC)) { ?>
<?php if($i == 0) { ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><b><?=$keys[$key]?></b></td>
<?php } //Endforeach ?>
</tr>
<?php } $i++; //Endif ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><?=$value?></td>
<?php } //Endforeach ?>
</tr>
<?php } //Endwhile ?>
</table>
You could just loop through the results. However, that would not perform any checks. Most likely, you'll have to do something like this, depending on what you're actually getting from the database.
<?php foreach ($row as $field): ?>
<?php if ($field): ?>
<td><?php echo $field; ?></td>
<?php endif; ?>
<?php endforeach; ?>
Edit: In keeping in line with the comment you added above, you could simply remove the if clause.
not sure if this is what you need,
but you can use indexes instead for the column instead of names:
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) {
echo $row[0] ." ".$row[1]." ".$row[2]
}
?>
mysql_fetch_array
possible formating:
<table>
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) { ?>
<tr>
<?php for(var $i=0; $i < count($row); $i++){
echo "<td>". $row[i] ."</td>";
} ?>
</tr>
<?php } ?>
</table>

Categories