passing php variable in javascript function - php

I am new to php and javscript.I am working on some project of question and answer system.I want to send question id to javascript function.
here is my php code
<?php
if ($result->num_rows > 0)
{
$i = 1;
while($row = $result->fetch_assoc())
{
$p = $row["description"] ;
echo '<div onclick="myOverFunction(<?= $p ?>)" align="left" class="j" role="group" aria-label="..." > <button id = "btnl<?=$i?>" type="button" class="btn btn-default btn-xs btn-round" style="border-radius:10px;">';
echo $i;
echo '</button>';
echo '<p class="question" style ="display:inline; ">';
echo $p;
echo '</p>';
echo '</div>';
}
}
?>
My javacript function is:
<script>
function myOverFunction(x) {
document.getElementById("demo").innerHTML = x;
document.getElementById("btnl"+x).style.backgroundColor = "#d9534f";
}
</script>
my code does not working ..please help me ...

Your problem is:
echo '<div onclick="myOverFunction(<?= $p ?>)"
Change it to:
echo '<div onclick="myOverFunction('. $p .')".
Same goes for the other occurrences.
You can't echo from inside an echo
Your final echo should look like this:
echo '<div onclick="myOverFunction(\''. $p .'\')" align="left" class="j" role="group" aria-label="..." > <button id = "btnl'.$i.'" type="button" class="btn btn-default btn-xs btn-round" style="border-radius:10px;">';
Note: If $p is a string, it needs quotes. And quotes inside quotes need escaping

You are breaking this line by trying to re-open php tags within the echo:
echo '<div onclick="myOverFunction(<?= $p ?>)" align="left" class="j" role="group" aria-label="..." > <button id = "btnl<?=$i?>" type="button" class="btn btn-default btn-xs btn-round" style="border-radius:10px;">';
Try this:
echo '<div onclick="myOverFunction('.$p.')" align="left" class="j" role="group" aria-label="..." > <button id = "btnl'.$i.'" type="button" class="btn btn-default btn-xs btn-round" style="border-radius:10px;">';

Related

Running PHP inside of PHP?

I am still learning and I found that I can't run PHP within PHP, after reading into it makes sense why you cannot do it (D'oh!), what I am struggling to find is the correct way to do this.
I have two buttons which link to different modals, if I do not use them within a IF Statement they work as expected as soon as I add to the IF Statement it breaks the page. (obviously because I am trying to run php within php)
What I'm trying to get working is to show a different button depending on the result of a column called "status" in the MySQL table, if it equals 1 it will show the edit button if anything else it will show a check-out button. I need to pass the <?php echo $fetch['id']?> to the data-target I'm not sure how to go about that.
<?php
$status_code = $fetch["status"];
if("$status_code" == "1")
{ echo '<button type="button" class="button-7" data-toggle="modal" data-target="#update_modal<?
php echo $fetch['id']?>"><span class="glyphicon glyphicon-plus"></span>edit</button>';
} else
{ echo '<button type="button" class="button-7" data-toggle="modal" data-target="#checkout_modal<?
php echo $fetch['id']?>"></span>Check-Out</button>';
} ?>
Any help is much appreciated.
You just need simple concatenation with the . (dot) operator.
E.g.
echo '<button type="button" class="button-7" data-toggle="modal" data-target="#update_modal'.$fetch['id'].'"><span class="glyphicon glyphicon-plus"></span>edit</button>';
...etc.
This is used to join any two string values (whether hard-coded literals or variables) together. What's happening here is your code is building a string from several components and then echoing it.
Documentation: https://www.php.net/manual/en/language.operators.string.php
You don't need to run PHP inside PHP.
You may use a comma (or a dot):
<?php
if ($status_code == "1") {
echo '<button type="button" class="button-7" data-toggle="modal" data-target="#update_modal<'
, $fetch['id']
, '"><span class="glyphicon glyphicon-plus"></span>edit</button>';
} else {
echo '<button type="button" class="button-7" data-toggle="modal" data-target="#checkout_modal'
, $fetch['id']
, '">Check-Out</button>';
}
Or using short tags:
<?php if ($status_code === '1') : ?>
<button type="button" class="button-7" data-toggle="modal" data-target="#update_modal<?= $fetch['id'] ?>">
<span class="glyphicon glyphicon-plus"></span>edit</button>'
<?php else: ?>
<button type="button" class="button-7" data-toggle="modal" data-target="#checkout_modal<?= $fetch['id'] ?>">Check-Out</button>'
<?php endif; ?>
You can have conditions (and other expressions) in short tags:
<button
type="button"
class="button-7"
data-toggle="modal"
data-target="#<?=
$status_code === '1'
? 'update_modal'
: 'checkout_modal'
?><?= $fetch['id'] ?>">
<?php if ($status_code === '1') : ?>
<span class="glyphicon glyphicon-plus"></span>edit
<?php else: ?>
Check-Out
<?php endif; ?>
</button>
And concatenate strings with dots:
<?php
$dataTargetPrefix =
$status_code === '1'
? 'update_modal'
: 'checkout_modal';
?>
<button
type="button"
class="button-7"
data-toggle="modal"
data-target="#<?= $dataTargetPrefix . $fetch['id'] ?>">
<?php if ($status_code === '1') : ?>
<span class="glyphicon glyphicon-plus"></span>edit
<?php else: ?>
Check-Out
<?php endif; ?>
</button>

Bootstrap Table select all and update cell value through modal

I currently have a Bootstrap Table displaying some data from a SQL DB with the ability to edit each row seperately with the options Consign, Edit and Delete. Consign simply changes the consign value in the DB from No to Yes.
It's more likely that multiple rows will be consigned at once so the aim is to be able to select mutiple using the built in checkboxes and then click the Consign button on the toolbar. This would then open a modal to confirm the action and then apply the changes to the DB - i.e. change all the selected rows consign value from No to Yes.
I've managed to get the button to only work when the checkboxes are selected and I've also created a modal which appears when clicking the button if it's active. There are a couple of hidden inputs in there for the DB update (a select option showing Yes and today's date).
I guess I'm stuck at the point of how do I get the IDs (called no here) of my rows over to allow the DB to be updated. I've tried to MacGyver a few suggestions on here together but nothing has worked so far, so any suggestions would be immensly appreciated.
This is the code I have so far.
HYML Table - records.php
<div class="datatable-dashv1-list custom-datatable-overright">
<div id="toolbar">
<button id="consigned" class="btn btn-warning btn-md" data-toggle="modal" data-target="#modal_form" disabled><i class="glyphicon glyphicon-check"></i> Consign Selected</button>
</div>
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Consign Multiple Entries</h4>
</div>
<form action="#" id="form" class="form-horizontal">
<div class="modal-body form">
<input type="hidden" value="" name="no"/>
<div class="form-body">
<div class="form-group">
<p class="text-center">Are you sure you want to consign the selected items?</p>
<div class="col-md-9">
<select class="form-control" name="consigned" style="visibility:hidden;" required readonly>
<option value="Yes">Yes</option>
</select>
</div>
</div>
<div class="form-group">
<!-- below list_check shows the IDs of the rows selected -->
<label class="control-label col-md-3">* This is supposed to be hidden value</label>
<div class="col-md-9">
<input name='list_check'>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
<button type="submit" id="btnConsign" class="btn btn-success"><span class="glyphicon glyphicon-check"></span> Consign</button>
</div>
</form>
</div>
</div>
</div>
<table id="table" data-toggle="table" data-id-field="no" data-select-item-name="no" data-sort-name="no" data-sort-order="asc" data-pagination="true" data-page-list="[10, 25, 50, 100, 200, All]" data-search="true" data-searchable="true" data-show-columns="true" data-show-pagination-switch="true" data-key-events="true" data-show-toggle="true" data-resizable="true" data-cookie="true"
data-cookie-id-table="saveId" data-show-columns-toggle-all="true" data-show-export="true" data-export-types="['xlsx', 'pdf']" data-export-options="{}" data-click-to-select="true" data-filter-control="true" data-filter-control-visible="true" data-filter-show-clear="true" data-show-refresh="false" data-maintain-meta-data="true" data-cookie="true" data-cookie-id-table="wasteId" data-cookie-expire="3h" data-toolbar="#toolbar">
<thead>
<tr>
<th data-field="selected" data-checkbox="true">Select</th>
<th data-field="no" data-sortable="true" data-sorter="dateSorter" data-visible="false">No</th>
<th data-field="location" data-sortable="true" data-filter-control="select" data-filter-control-placeholder="Select Location">Location</th>
<th data-field="name" data-visible="false">Name</th>
<th data-field="area" data-visible="false">Area</th>
<th data-field="sendto" data-visible="false">Send To</th>
<th data-field="reference">Reference</th>
<th data-field="consigned" data-filter-control="select" data-filter-default="No">Consigned</th>
<th data-field="date_consigned" data-visible="false">Date Consigned</th>
<th data-field="action" class="col-lg-2">Action</th>
</tr>
</thead>
<tbody>
<?php
include 'include/fetch-data.php';
?>
</tbody>
</table>
</div>
PHP fetch-data.php
<?php
include 'include/dbconnect.php';
$sql = "SELECT * FROM Sendlist";
$result = $conn->query( $sql );
if ( $result->num_rows > 0 ) {
while ( $row = $result->fetch_assoc() ) {
echo '<tr>';
echo '<td></td>';
echo '<td>' . $row[ "no" ] . '</td>';
echo '<td>' . $row[ "location" ] . '</td>';
echo '<td>' . $row[ "name" ] . '</td>';
echo '<td>' . $row[ "area" ] . '</td>';
echo '<td>' . $row[ "sendto" ] . '</td>';
echo '<td>' . $row[ "reference" ] . '</td>';
echo '<td>' . $row[ "consigned" ] . '</td>';
echo '<td>' . $row[ "date_consigned" ] . '</td>';
if ( $row[ 'consigned' ] == 'Yes' ) {
echo "<td>
<a href='#consign_" . $row[ 'no' ] . "' class='btn btn-warning btn-sm hide' data-toggle='modal' id='consign' name='consign'><span class='glyphicon glyphicon-check'></span> Consign</a>
<a href='#unconsign_" . $row[ 'no' ] . "' class='btn btn-warning btn-sm' data-toggle='modal' id='unconsign' name='unconsign'><span class='glyphicon glyphicon-check'></span> Unconsign</a>
<a href='#edit_" . $row[ 'no' ] . "' class='btn btn-success btn-sm' data-toggle='modal'><span class='glyphicon glyphicon-edit'></span> Edit</a>
<a href='#delete_" . $row[ 'no' ] . "' class='btn btn-danger btn-sm' data-toggle='modal'><span class='glyphicon glyphicon-trash'></span> Delete</a>
</td>";
}
echo "</tr>";
include( 'include/edit-delete-modal.php' );
echo "</tr>";
}
}
?>
<script>
var $table = $('#table')
var $consigned = $('#consigned')
$(function() {
$table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function () {
$consigned.prop('disabled', !$table.bootstrapTable('getSelections').length)
})
$consigned.click(function () {
var ids = $.map($table.bootstrapTable('getSelections'), function (row) {
return row.id
})
$table.bootstrapTable('getSelections', {
field: 'no',
values: ids
})
$consigned.prop('disabled', true)
})
})
</script>
Just so others can find the answer if needed in the future, I used the following script to get the IDs of my selected rows to pass them through a hidden input in the modal which will then be later used (with explode) to update SQL entries.
<script type="text/javascript">
var $table = $('#table');
function getRowSelections() {
return $.map($table.bootstrapTable('getSelections'), function(row) {
return row;
})
}
$('#consigned').click(function() {
var selectedRows = getRowSelections();
var selectedItems = '\n';
$.each(selectedRows, function(index, value) {
selectedItems += value.no + ',';
});
$('#modal_form').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggers the modal
var recipient = button.data('whatever'); // Extract info from data-* attributes
var modal = $(this);
modal.find(".modal-body input[name='list_check']").val(selectedItems);
});
});
</script>

php while loop not displaying rows after 15 rows

Hello I have Two files one file contain the main posts and second file contain load more posts code
Following are the code of main file but in this file i have a problem that i have to loop my all mysql rows in php and i can do it using while loop but when i try this i am getting all rows but after 15 rows it shows only those that are after 15 rows like only 16 row
My main.php code
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$nv_name_split = str_replace('_', ' ', $row['novel_name']);
echo '<br><a href="episode?novel='.$row['novel_name'].'&episode='.$row['episode_num'].'"><figure class="snip1253"><div class="image"><img width="100%"src="images/sneakpeaks/'.$row['sneak_peak'].'" alt="sample59"/></div><figcaption>'.
'<div class="date"><span class="day">'.$row['day'].'</span><span class="month">'.$row['month'].'</span></div><h3>Episode # '.$row['episode_num'].'</h3> <footer>
<div class="writer text-center"><i class="fa fa-book"> '.$nv_name_split.'</i></div>
<div class="love"><i class="fa fa-thumbs-up"></i>'.$row['likes'].'</div>
<div class="comments"><i class="fa fa-comments"></i>'.$row['comments'].'</div></footer></figure></a></figcaption><br><br>';
}
?>
<?php
$stmt_count = $novel_list->runQuery("SELECT episode_num
FROM posts
WHERE just_skpk='0'");
$stmt_count->execute();
while ($rows = $stmt_count->fetch(PDO::FETCH_ASSOC)) {
$count_row = $rows['episode_num'];
}
if ($limit < $count_row) {
echo'<form id="frm_more_post">
<center>
<button type="submit" class="form-control btn btn-load_more" id="frm_btn_more">Load More Posts</button>
</center>
</form>
<br>
<br>';
}else{
echo'<form id="frm_more_post">
<center>
<button type="submit" disabled class="disabled form-control btn btn-load_more" id="frm_btn_more">No More Posts</button>
</center>
</form>
<br>
<br>';
}
and this is my load_more.php code where i post limit of posts using ajax
load_more.php code
$novel_list = new USER();
if (isset($_POST['page'])) {
$limit = $_POST['page']+3;
$stmt = $novel_list->runQuery("SELECT *
FROM posts
WHERE just_skpk='0'
ORDER BY id DESC
LIMIT $limit");
$stmt->execute();
if ($stmt->rowCount(0)) {
echo '<input class="hidden" id="pages" value="'.$limit.'"/>';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$nv_name_split = str_replace('_', ' ', $row['novel_name']);
echo '<br><a data-pages="'.$limit.'" href="episode?novel='.$row['novel_name'].'&episode='.$row['episode_num'].'"><figure class="snip1253"><div class="image"><img width="100%"src="images/sneakpeaks/'.$row['sneak_peak'].'" alt="sample59"/></div><figcaption>'.
'<div class="date"><span class="day">'.$row['day'].'</span><span class="month">'.$row['month'].'</span></div><h3>Episode # '.$row['episode_num'].'</h3> <footer>
<div class="writer text-center"><i class="fa fa-book"> '.$nv_name_split.'</i></div>
<div class="love"><i class="fa fa-thumbs-up"></i>'.$row['likes'].'</div>
<div class="comments"><i class="fa fa-comments"></i>'.$row['comments'].'</div></footer></figure></a></figcaption><br><br>';
}
$stmt_count = $novel_list->runQuery("SELECT episode_num
FROM posts
WHERE just_skpk='0'");
$stmt_count->execute();
while ($rows == $stmt_count->fetch(PDO::FETCH_ASSOC)) {
$count_row = $rows['episode_num'];
}
if ($limit < $count_row) {
echo '<form id="frm_more_post">
<center>
<button type="submit" class="form-control btn btn-load_more" id="frm_btn_more">Load More Posts</button>
</center>
</form>
<br>
<br>';
}else{
echo '<form id="frm_more_post">
<center>
<button type="submit" disabled class="disabled form-control btn btn-load_more" id="frm_btn_more">No More Posts</button>
</center>
</form>
<br>
<br>';
}
}else{
echo 0 ;
}
}
i solve first problem in main.php while loop using double == in while loop but in load_more.php file i cant show more posts button it shows disabled but when i have less than 15 rows in database its working perfectly please help me to show load more posts button in load_more.php.
ThankYou,
Any help will be appreciated.
In your code you are getting episode_num as $count_row, but it should be no of rows. Try below code
$novel_list = new USER();
if (isset($_POST['page'])) {
$limit = $_POST['page']+3;
$stmt = $novel_list->runQuery("SELECT *
FROM posts
WHERE just_skpk='0'
ORDER BY id DESC
LIMIT $limit");
$stmt->execute();
if ($stmt->rowCount(0)) {
echo '<input class="hidden" id="pages" value="'.$limit.'"/>';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$nv_name_split = str_replace('_', ' ', $row['novel_name']);
echo '<br><a data-pages="'.$limit.'" href="episode?novel='.$row['novel_name'].'&episode='.$row['episode_num'].'"><figure class="snip1253"><div class="image"><img width="100%"src="images/sneakpeaks/'.$row['sneak_peak'].'" alt="sample59"/></div><figcaption>'.
'<div class="date"><span class="day">'.$row['day'].'</span><span class="month">'.$row['month'].'</span></div><h3>Episode # '.$row['episode_num'].'</h3> <footer>
<div class="writer text-center"><i class="fa fa-book"> '.$nv_name_split.'</i></div>
<div class="love"><i class="fa fa-thumbs-up"></i>'.$row['likes'].'</div>
<div class="comments"><i class="fa fa-comments"></i>'.$row['comments'].'</div></footer></figure></a></figcaption><br><br>';
}
$stmt_count = $novel_list->runQuery("SELECT count(*) as cnt
FROM posts
WHERE just_skpk='0'");
$stmt_count->execute();
while ($rows = $stmt_count->fetch(PDO::FETCH_ASSOC)) {
$count_row = $rows['cnt'];
}
if ($limit < $count_row) {
echo '<form id="frm_more_post">
<center>
<button type="submit" class="form-control btn btn-load_more" id="frm_btn_more">Load More Posts</button>
</center>
</form>
<br>
<br>';
}else{
echo '<form id="frm_more_post">
<center>
<button type="submit" disabled class="disabled form-control btn btn-load_more" id="frm_btn_more">No More Posts</button>
</center>
</form>
<br>
<br>';
}
}else{
echo 0 ;
}
}
I think this because of the pagination. In the file load_more.php, you are setting a limit
$limit = $_POST['page']+3;
and in the file, main.php
if ($limit < $count_row)
this is the check.

Code Igniter foreach loop function only returns one row

what I'm trying to do seems very easy but for the life of me, I can't figure out what I'm doing wrong.
What I want to achieve is to call a function which contains a loop with a return statement in another function in my model. For some reason beyond me, the loop function only returns the first row in the db table, even when there are more than 1.
Here is the loop function:
public function download_contents($id) {
$the_contents = $this->db->get_where('contents', array('request_id' => $id));
$count = 1;
foreach ($the_contents->result() as $y) {
$file_name = $y->file_name;
$download_path = base_url('assets/client/contents/'.$file_name);
return '<p>' .$count++. '. ' .$file_name. '
<a class="btn btn-primary btn-xs" href="' .$download_path. '" title="Download Content">Download</a></p>';
}
}
Now I want to echo the results of the function above in the function below:
public function modal_content_download($id) {
$y = $this->db->get_where('website_requests', array('id' => $id))->row();
$the_contents = $this->db->get_where('contents', array('request_id' => $id));
if ( $the_contents->num_rows() > 0 ) {
return '<button class="btn btn-primary btn-sm modal-toggle-btn" data-toggle="modal" data-target="#contents' .$id. '" title="Download Contents"> <i class="fa fa-download"></i></button>
<div class="modal fade" id="contents' .$id. '" role="dialog">
<div class="modal-dialog">
<div class="modal-content modal-width">
<div class="modal-header">
<div class="pull-right">
<button class="btn btn-danger btn-xs" data-dismiss="modal" title="Close dialog"> Close </button>
</div>
<h5 class="modal-title"> <i class="fa fa-download"></i> Download Contents: ' .$y->project_name. '</h5>
</div><!--/.modal-header-->
<div class="modal-body">'
.$this->download_contents($id). //calling the first function
'</div>
</div>
</div>
</div>';
} else {
return '<b style="color: red">No content uploaded yet.</b>';
}
}
The second function is passed to the controller and loaded to the view (with some other info). Now I know about code igniter's query logic and result() should return more than 1 row. What am I missing?
Try this
public function download_contents($id) {
$the_contents = $this->db->get_where('contents', array('request_id' => $id));
$count = 1;
$loop_result="";
foreach ($the_contents->result() as $y) {
$file_name = $y->file_name;
$download_path = base_url('assets/client/contents/'.$file_name);
$loop_result .= '<p>' .$count++. '. ' .$file_name. '
<a class="btn btn-primary btn-xs" href="' .$download_path. '" title="Download Content">Download</a></p>';
}
return $loop_result;
}

Multi-dimensional arrays, but I cannot retrieve data PHP

More errors from my most recent project (posted about another thing earlier).
I've been struggling with this error for a few days now. PHP is not my main programming language, nor am I that great at it.
I'm aware that mysql_* should not be used, also.
Anyways. Here's the code snip.
<?php
$query = "SELECT * FROM events";
$result = mysql_query($query);
$content = array();
$num = mysql_num_rows($result);
if ($num > 0) {
while($row = mysql_fetch_assoc($result)) {
$content[$row['ID']] = $row;
}
}
if ($num > 0) {
?>
<thead>
<tr>
<th><?php echo implode('</th><th>', array_keys(current($content)));?></th><th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($content as $tablerow): ?>
<tr>
<td><?php echo implode('</td><td>', $tablerow);?>
</td><td><div class="btn-group" role="group" aria-label="Actions"><a class="btn btn-primary" role="button" href="#">New Session</a><a class="btn btn-success" role="button" href="#">Continue Latest</a><a class="btn btn-warning" role="button" href="#">Settings</a><?php echo "<a class='btn btn-danger' role='button' href='/manager/delete?id=".$row."'>Delete</a>"; ?>
</tr>
<?php endforeach; ?>
</tbody>
Sorry for derp formatting. Anyways.
I'm trying to get that delete button to link to ../manager/delete?id=x, where x is the ID for the row. My database is formatted in the way where the ID is in a column labeled "ID". I'm trying to reference each of these rows by this ID... why is this not working?
I've also tried (in the place of row), content[row['ID']], content['ID'], 'row['ID']`, with different case on the ID (uppercase/lowercase).
Fred -ii- was correct in his above comment.
I had tried everything other than $tablerow['ID'].... now you know I guess.
Thank you for the help everyone. One of the dumbest things I've ever missed while debugging....
he was partially correct, however i think your id is the key, so you might just reference the key so its a bit cleaner
<?php foreach ($content as $idKey => $tablerow): ?>
<tr>
<td><?php echo implode('</td><td>', $tablerow);?>
</td><td><div class="btn-group" role="group" aria-label="Actions"><a class="btn btn-primary" role="button" href="#">New Session</a><a class="btn btn-success" role="button" href="#">Continue Latest</a><a class="btn btn-warning" role="button" href="#">Settings</a><?php echo "<a class='btn btn-danger' role='button' href='/manager/delete?id=".$idKey."'>Delete</a>"; ?>
</tr>
<?php endforeach; ?>

Categories