I have a program that displays authors book code and book title using php and
AJAX technology, but for some reason the data is not appearing in the table. I know my SQL code is correct as our instructor gave us the code for that, but something is preventing the data from appearing in the table. Any tips or suggestions would be appreciated!
<body>
<?php
$authorid = 0;
$authorid = (int) $_GET['authorid'];
if ($authorid > 0) {
require_once('dbtest.php');
$query = "SELECT * FROM author";
$r = mysqli_query($dbc, $query);
if (mysqli_num_rows($r) > 0) {
$row = mysqli_fetch_array($r);
} else {
echo "Title Not Returned<br>";
}
echo "<table border='1'><caption>Titles for </caption>";
echo "<tr>";
echo "<th>Book Code</th>";
echo "<th>Book Title</th>";
echo "</tr>";
$q2 ="SELECT wrote.author_number As ANo, wrote.book_code As BookCd, book.book_title As Title ";
$q2 .= " FROM wrote, book ";
$q2 .= " WHERE wrote.book_code=book.book_code ";
$q2 .= " AND wrote.author_number = ' ' ";
$q2 .= " ORDER BY book.book_title";
$r2 = mysqli_query($dbc, $q2);
$row = mysqli_fetch_array($r2);
while ($row) {
echo "<tr>";
echo "<td>" .$row['BookCd']. "</td>";
echo "<td>" .$row['Title']. "</td>";
echo "</tr>";
$row = mysqli_fetch_array($r2);
}
echo "</table>";
} else {
echo "<p>No Author ID from prior page</p>";
}
?>
</form>
</body>
The suspicious line is: AND wrote.author_number = ' '
Why is it empty?
Put a check after the second query:
$r2 = mysqli_query($dbc, $q2);
if (mysqli_num_rows($r2) > 0) {
echo "rows are Returned<br>";
} else {
echo "rows are Not Returned<br>";
}
$row = mysqli_fetch_array($r2);
Related
I want to use query and query2 two different select queries together.
How to use it and execute?
Here is my code
$query2 = "SELECT advance FROM transaction WHERE adv_date=now()";
$query = "SELECT SUM(s.total) AS totalamount FROM sale s JOIN product p ON ( s.pr_id = p.pr_id ) WHERE s.customer_name = '$customer'";
$result = mysqli_query($connect, $query);
$result2 = mysqli_query($connect, $query2);
$output = '';
if (mysqli_num_rows($result) > 0) {
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$output .= '<h4 style="display: inline;" align="right"> ' . $row["totalamount"] . '</h4><br> ';
$output .= ' ';
$i++;
}
} else {
$output .= '<tr>
<td colspan="5">No Order Found</td>
</tr>';
}
$output .= '<h4 style="display:inline;" align="right"> ' . $row["total"] . '</h4><br> ';
echo $output; ?>
try this one it will help you
$sql = "SELECT Lastname FROM Persons ORDER BY LastName;";
$sql .= "SELECT Country FROM Customers";
// Execute multi query
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
printf("%s\n",$row[0]);
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
I'm not sure if i understood your question right, but i created a function to execute both of your queries, by passing them through the parameter of the function.
function commitQuery($query){
$result = mysqli_query($connect, $query);
$output = '';
if(mysqli_num_rows($result) > 0) {
$i=0;
while($row = mysqli_fetch_array($result)) {
$output .= '<h4 style="display:inline;" align="right"> '. $row["totalamount"] .'</h4><br>';
$output .= '';
$i++;
}
} else {
$output .= '
<tr>
<td colspan="5">No Order Found</td>
</tr>';
}
$output .= '<h4 style="display:inline;" align="right"> '. $row["total"] .'</h4><br>';
echo $output;
}
}
commitQuery("SELECT advance FROM transaction WHERE adv_date=now()");
commitQuery("SELECT SUM(s.total) AS totalamount FROM sale s JOIN product p ON ( s.pr_id = p.pr_id ) WHERE s.customer_name = '$customer'");
Hi i'm making a project using php i just wonder how i can add checkbox on a table that indicate being selected. As I didn't find any question asked before, on how to toggle checkbox on click of a table row, so I'd like to share my approach to this.
here are my codes:
$list_equipments = array();
$con = new data_abstraction("resource_booking", "it_equipment_type");
if ($result = $con - > make_query() - > result) {
while ($data = $result - > fetch_assoc()) {
$list_equipments[] = $data;
}
} else {
die("SQL Error:".$con - > error);
}
$html - > draw_container_div_start();
$html - > draw_fieldset_header('');
$html - > draw_fieldset_body_start();
echo "<table width='600px' style='border-width:1px; border-style:solid;'>";
$counter = 0;
$no_columns = 2; //initialize 3 columns
$column_width = 110 / $no_columns; +
foreach($list_equipments as $key => $equipment) {
if ($counter % $no_columns == 0)
echo "<tr>";
echo "<td width='".$column_width.
"%' style='border-width:1px; border-style:solid'>";
draw_equipment($equipment);
echo "</td>";
if ($counter % $no_columns == $no_columns - 1)
echo "</tr>";
$counter++;
}
echo "</table>";
$html - > draw_fieldset_body_end();
$html - > draw_fieldset_footer_start();
$html - > draw_submit_cancel(true, '2', 'btn_submit', 'RESERVE');
$html - > draw_fieldset_footer_end();
$html - > draw_container_div_end();
$html - > draw_footer();
function draw_equipment($equipment) {
$equipment_name = $equipment['img_link'];
echo "<div style='text-align:left;width:120%'>";
echo "<img src='img/$equipment_name' alt='$equipment_name' width='155px'/><br/>";
echo $equipment['equip_type'];
}
echo "</form>";
return ob_get_clean();
While creating table you can add a td in which you can add a checkbox for each row like below
<td><input type= "checkbox" class="toggleCheckbox"></td>
And then using jquery you can handle click event on this like below
$("table tr").click(function(){
($(this).children(":last").trigger("click");
})
finally i have a solution on my question
<?php
$list_equipments = array();
$con = new data_abstraction("resource_booking", "it_equipment_type");
if ($result = $con->make_query()->result) {
while ($data = $result->fetch_assoc()) {
$list_equipments[] = $data;
}
} else {
die("SQL Error:" . $con->error);
}
$html->draw_container_div_start();
$html->draw_fieldset_header('');
$html->draw_fieldset_body_start();
echo "<table width='600px' style='border-width:1px; border-style:solid;'>";
$counter = 0;
$no_columns = 2; //initialize 3 columns
$column_width = 110 / $no_columns;
foreach ($list_equipments as $key => $equipment) {
if ($counter % $no_columns == 0)
echo "<tr>";
echo "<td width='" . $column_width . "%' style='border-width:1px; border-style:solid'>";
draw_equipment($equipment);
echo "</td>";
if ($counter % $no_columns == $no_columns - 1)
echo "</tr>";
$counter++;
}
echo "</table>";
$html->draw_fieldset_body_end();
$html->draw_fieldset_footer_start();
$html->draw_submit_cancel(true, '2', 'btn_submit', 'RESERVE');
$html->draw_fieldset_footer_end();
$html->draw_container_div_end();
$html->draw_footer();
function draw_equipment($equipment)
{
$equipment_name = $equipment['img_link'];
echo "<div style='text-align:left;width:120%'>";
echo "<input type='checkbox' class='toggleCheckbox'>";
echo "<img src='img/$equipment_name' alt='$equipment_name' width='120px'/><br/>";
echo $equipment['equip_type'];
}
echo "</form>";
return ob_get_clean();
Inside a php class I am defining a table which displays a list of clients which one need to contact. In column 7 I have integrated a checkbox so when the user call the client, he/she ticks into this checkbox.
The problem is that the JS function runs the first-time and then the second time it says: default.php?page=_PhoneBankingP1:1 Uncaught ReferenceError: contacted is not defined(…)
The modules in use are listed below:
public function phonebank($townCode,$streetCode){
$query = "SELECT clientId, clientFirstname1, clientLastname1, clientAddress, ";
$query .= " clientMailshot, clientPhone1, clientMobile1, clientContacted, min(clientDoB) ";
$query .= "FROM _clients ";
$query .= "WHERE _clients.streetCode = '{$streetCode}' and ";
$query .= " _clients.townCode = '{$townCode}' and ";
$query .= " _clients.GE = 'Y' ";
$query .= "GROUP BY clientAddress ";
$result = $this->db->query($query);
$output = "";
if ( $result->num_rows > 0 ){
$output .= "<div class='alert alert-info'><strong>Information!</strong> All the residents shown below have been extracted from the last Electoral Register.</div>";
$output .= "<table class='table table-striped' style='font-size:10pt;' id='myTable' >";
$output .= "<thead>";
$output .= "<tr>";
$output .= "<th>ID #</th>";
$output .= "<th>Name</th>";
$output .= "<th>Address</th>";
$output .= "<th>T</th>";
$output .= "<th>Phone</th>";
$output .= "<th>Mobile</th>";
$output .= "<th class='text-center'>Contacted</th>";
$output .= "</tr>";
$output .= "</thead>";
$output .= "<tbody>";
while ( $record = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$output .= "<tr>";
$output .= "<td><a href='default.php?page=_clientDetails&id=".$record['clientId']."&mode=edit' style='color: #000;'><span class='pb-clientId'>".$record['clientId']."</span></a></td>";
$output .= "<td><span class='pb-fullname'>".$record['clientFirstname1']." ".$record['clientLastname1']."</span></td>";
$output .= "<td>".$record['clientAddress']."</td>";
$output .= "<td>".$record['clientMailshot']."</td>";
$output .= "<td>".$record['clientPhone1']."</td>";
$output .= "<td>".$record['clientMobile1']."</td>";
// Makes a checkbox selected
if ( $record['clientContacted'] == 'Y'){
$optContacted = ' checked ';
} else {
$optContacted = '';
}
//$output .= "<td class='text-center' ><button id='btn-contacted-".$record['clientId']."' onclick='street.clientContacted("{$record['clientId']}","{$record['clientContacted']}")' class='btn btn-success'>Contacted</button></td>";
$output .= "<td align='center'>";
$output .= "<input type='checkbox' id='col7-".$record['clientId']."' onclick='contacted("".$record['clientId']."");' value='1' ".$optContacted." />";
$output .= "</td>";
$output .= "</tr>";
}
$output .= "</tbody>";
$output .= "</table>";
$output .= "<br/>";
echo $output;
} else {
echo "No Clients Found in this street";
}
}
Then the test JS function required to update the MYSQL is:
function contacted(id) {
var clientId = id;
var col7 = "col7-"+clientId;
var col7value = $("#"+col7).is(':checked');
var data = id+"\n"+col7+"\n"+col7value;
alert(data);
//Read checkbox state
if (col7value =='false'){
contacted = 'N';
} else {
contacted = 'Y';
}
$.ajax({
type: "POST",
url: "_backend/_core/_database/update_Phonebank.php",
data: {
"id": clientId,
"contacted": contacted
},
dataType: "text",
success: function(data){
}
})
}
I will appreciate if you can help me out to decide my the function is not being read the second time.
You define a function:
function contacted(id) {
//...
}
But within that function, you overwrite the function with a value:
contacted = 'N';
So the next time you try to invoke contacted() you're trying to call a string as if it was a function.
Give your variables unique names:
var wasContacted = '';
//...
wasContacted = 'N';
// etc.
That way you're not overwriting things you don't want to overwrite.
Additionally, using the var keyword to declare your variables will define them within that specific scope (such as within that function), instead of just putting them on the window object. (You can have variables of the same name in different scopes without affecting each other.)
<?php
include_once("db.php");
$result=mysql_query("SELECT * FROM stu WHERE receiver='DM4'");
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['ptype'] . "</td>";
echo "<td>" . $row['source'] . "</td>";
echo "<td>" . $row['letterno'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['descrip'] . "</td>";
echo "<td>" . $row['receiver'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td><a href='vex.php?uid={$row['letterno']}' id='id' onClick='addfavourite()'>.{$row['title']}.</a></td>";
//echo "<td><a href='update.php?id={$row['id']}'>Update</a></td>";
echo"<td><img style='width:100px;higth:150px;' src='upload/{$row[image]}'></td>";
addfavourite();
echo addfavourite();
function addfavourite() {
$ide=$_GET['uid'];
//echo $ide;
$sql = "SELECT * FROM stu WHERE letterno = '$ide'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if($row){
$newfav = "UPDATE stu SET open = 1 WHERE letterno = '$ide'";
$createfav = mysql_query($newfav);}
else{
$newfav = "UPDATE stu SET open = 0 WHERE letterno = '$ide'";
$createfav = mysql_query($newfav);}
}
}
echo $ide;
?>
This is my error code.In this code,there is a fault with mysql query statement.it is not supported with the databse. but onclick() function is working.
You cannot directly execute a PHP function from a JavaScript event. Simply, cannot mix server side and client side logic but you can make two of them interact with each other.
In this case, you can create a JavaScript function which sends an AJAX request to a PHP page on your server containing the code of addfavourite().
A Demo
I haven't tested the code below but assuming that your code logic and rest stuff is correct, this might just work
demo.php
<script>
function addfavourite(uid){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
var url = "addfavourite.php"; // URL of your PHP file
var vars = "uid="+uid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
<?php
include_once("db.php");
$result=mysql_query("SELECT * FROM stu WHERE receiver='DM4'");
echo "<table>";
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['ptype'] . "</td>";
echo "<td>" . $row['source'] . "</td>";
echo "<td>" . $row['letterno'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['descrip'] . "</td>";
echo "<td>" . $row['receiver'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td><a href='#' id='id' onClick='addfavourite({$row['letterno']})'>.{$row['title']}.</a></td>";
echo"<td><img style='width:100px;higth:150px;' src='upload/{$row[image]}'></td>";
}
echo "</table>";
?>
<div id='status'></div>
addfavourite.php
<?php
if(!isset($_POST['uid'])) {
$ide = $_POST['uid'];
$sql = "SELECT * FROM stu WHERE letterno = '$ide'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row) {
$newfav = "UPDATE stu SET open = 1 WHERE letterno = '$ide'";
$createfav = mysql_query($newfav);
} else {
$newfav = "UPDATE stu SET open = 0 WHERE letterno = '$ide'";
$createfav = mysql_query($newfav);
}
if ($createfav) {
echo "<script>alert('Added to favourite successfully...')";
} else {
echo "<script>alert('Something went wrong...')";
}
}else{
echo "POST variable not set!";
}
?>
Some notes
You should use mysqli insted of mysql functions as it is deprecated and no longer supported
This here is a good video tutorial on AJAX https://www.developphp.com/video/JavaScript/Ajax-Post-to-PHP-File-XMLHttpRequest-Object-Return-Data-Tutorial
i have a ajax function that is returning a set of values from php page.
i need to get the values to that is only required. how can i do this
ajax.js
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
ajax.php
<?php
require_once('config.php');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM thr';
mysql_select_db($dbname);
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo "<table border='1'>";
while($row = mysql_fetch_assoc($retval))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['ther_name'] . "</td>";
echo "<td>" . $row['region'] . "</td>";
echo "<td>" . $row['phone_no'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td id='lat'>" . $row['corrd_lattitude'] . "</td>";
echo "<td id='lon'>" . $row['corrd_longitude'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($conn);
?>
i need only values of
$row['corrd_lattitude']
$row['corrd_longitude']
how to get the values of this
first you can fetch only required values from table..if i understood correctly you can use following query.
$sql = 'SELECT corrd_lattitude,corrd_longitude FROM thr';
it will return only tw0 column value from table.
$json = json_encode(array($row['corrd_lattitude'], $row['corrd_longitude']));
echo $json;
You could specify parameters with your request.
In GET method:
ajax.php?corrd_lattitude=true&corrd_longitude=true
and in php file you can check this in $_GET array ie:
<?php
[...]
echo "<table border='1'>";
while($row = mysql_fetch_assoc($retval))
{
echo "<tr>";
if ($_GET['id'] == true) {
echo "<td>" . $row['id'] . "</td>";
}
if ($_GET['ther_name'] == true) {
echo "<td>" . $row['ther_name'] . "</td>";
}
if ($_GET['region'] == true) {
echo "<td>" . $row['region'] . "</td>";
}
if ($_GET['phone_no'] == true) {
echo "<td>" . $row['phone_no'] . "</td>";
}
if ($_GET['address'] == true) {
echo "<td>" . $row['address'] . "</td>";
}
if ($_GET['corrd_lattitude'] == true) {
echo "<td id='lat'>" . $row['corrd_lattitude'] . "</td>";
}
if ($_GET['corrd_longitude'] == true) {
echo "<td id='lon'>" . $row['corrd_longitude'] . "</td>";
}
echo "</tr>";
}
echo "</table>";
mysql_close($conn);
?>
Better is use json (or plain values) instead of html - your js should pack values into html. It's better for server, client side should build html. Sry for my english.
use json:-----------
=========================================
$sql = "SELECT * FROM thr";
$rs = mysql_query($sql);
$res = mysql_fetch_assoc($rs);
if(mysql_num_rows($rs)>0){
echo json_encode(array('lats'=>$res['corrd_lattitude'],'lngs'=>$res['corrd_longitude']));
}else{
echo json_encode(array('lats'=>'','lngs'=''));
}
here lats and lngs are simply varaiable name to store values inside them and get the value on other page from lats and lngs varaibale.