Trying to bring back a time id and time itself into listbox stored in mysql. run the sql in myadmin runs fine, try it in the code ... not so fine. bring back indefined index error.
thanks.
<?php
function get_times(&$a_class, &$db){
$str_sql =<<<EOT
SELECT timeId, DATE_FORMAT(tSel, '%H:%i')
FROM tb_time24
ORDER BY timeId
EOT;
if ($query_result = mysql_query($str_sql, $db)) {
while ($a_result = mysql_fetch_assoc($query_result)) {
$a = array();
$a['timeId'] = $a_result['timeId'];
$a['tSel'] = $a_result['tSel'];
array_push($a_class, $a);
}
}
else {
$i_result = mysql_errno($db);
}
if(isset($i_result)){
return $i_result;
}
}
?>
calling it here.
Start Time:<select name="startTime" id="StartTime">
<?php
$a_class = array();
get_times($a_class, $db_handle);
foreach ($a_class as $a_class) {
print "<option value='".$a_class['timeId']."'>{$a_class['tSel']}</option>\n";
}
?>
</select>
Give a name to the formatted column:
$str_sql =<<<EOT
SELECT timeId, DATE_FORMAT(tSel, '%H:%i') tSel
FROM tb_time24
ORDER BY timeId
EOT;
Otherwise the keys in the array returned by mysql_fetch_assoc would be timeId and DATE_FORMAT(tSel, '%H:%i').
Related
I have this script executing as a cron job everyday to update days remaining to pay invoices. I first query every row of my table and attempt to store the data in a multidimensional array but this seems to be storing everything I query in the first element of my array.
Here's my script:
<?php
include '../inc/dbinfo.inc';
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_log( "################################################# UpdateVendorInvoiceDays.php #################################################" );
$three = 3;
$fetchAllInvoices = "SELECT VENDORINVOICEID, VdrInvoiceReceived, PaymentDue, COUNT(*), DATEDIFF(PaymentDue, NOW()) FROM tblVendorInvoices WHERE VdrInvoiceStatusID != ?";
$getInvoices = $conn->prepare($fetchAllInvoices);
$getInvoices->bind_param("i", $three);
$getInvoices->execute();
$result = $getInvoices->get_result();
$rows = array();
$j = 0;
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]); //Only outputs one row
//UPDATE DAYS REMAINING IN EACH ENTRY THAT ISNT PAID
$updateDaysRemaining = "UPDATE tblVendorInvoices SET DaysRemaining = ? WHERE VENDORINVOICEID = ? AND VdrInvoiceStatusID ! = ?";
$setDays = $conn->prepare($updateDaysRemaining);
$k = 0; //incrementor
$numberOfEntries = $rows['COUNT(*)'];
for($k;$k<$numberOfEntries;$k++){
$setDays->bind_param("iii", $rows[$k]["DATEDIFF(PaymentDue, NOW())"],
$rows[$k]['VENDORINVOICEID'], $three);
if($setDays->execute()){
error_log('Cron success');
}else{
error_log('Cron fail');
}
}
?>
Currently the output from my first query is:
[[{"VENDORINVOICEID":88,"VdrInvoiceReceived":"2018-08-21","PaymentDue":"2018-07-27","COUNT(*)":2,"DATEDIFF(PaymentDue, NOW())":-25}]]
and my error log only gives me a notice for $rows['COUNT(*)'] being undefined (which makes sense)
I've looked at other answers here but they don't seem to have the same structure as I do.
EDIT: I also have 2 rows in my database but this only puts out one. I forgot to mention this.
There are a couple of simplifications to get all of the rows. Instead of...
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]);
You can just return all rows using fetch_all()...
$rows = $result->fetch_all (MYSQLI_ASSOC);
echo json_encode($rows);
Then encode the whole array and not just the one element - which is what $rows[0][0] was showing you.
As for you other problem - change in your select statement to
COUNT(*) as rowCount
and then you can use this alias for the field reference...
$rows['COUNT(*)']
becomes
$rows['rowCount']
I have a MySQL query that requests a list of items.
I fetch for them and want to display every item with a for loop, but it shows me just the first item repeated, instead of every item.
Why?
<?php
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$query = " SELECT cursoID, nombreCurso, estadoCurso
FROM cursos
WHERE estadoCurso='abierto'";
$buscarCurso = mysqli_query($conectar,$query);
$curso=mysqli_fetch_assoc($buscarCurso);
$totalRows = mysqli_num_rows($buscarCurso); //There are 3 rows of results
echo $totalRows;
for ($i=0; $i < $totalRows; $i++) {
echo '<br>';
echo $curso['nombreCurso'];
echo '<br>';
}
?>
The intended result is:
Curso 1
Curso 2
Curso 3
And instead I get
Curso 1
Curso 1
Curso 1
Your loop should be fetching from the result set on every iteration. The standard way (as in many examples given in the PHP documentation) is that you do this in the while condition:
$totalRows = mysqli_num_rows($buscarCurso); //There are 3 rows of results
echo $totalRows;
while ($curso=mysqli_fetch_assoc($buscarCurso)) {
echo '<br>';
echo $curso['nombreCurso'];
echo '<br>';
}
You need a loop for the query result. In this case, you'll get just one result and loop through that result 3 times.
<?php
while($curso = mysqli_fetch_assoc($buscarCurso)) {
// Do some stuff
echo '<br />' . $curso['nombreCurso'] . '<br />';
}
?>
First use prepared statement for block SQL injection than check this code
<?php
$conn = mysqli_connect(HOST, USER, PASS, DATABASE);
$select_cursos = $conn->prepare(" SELECT
cursoID, nombreCurso, estadoCurso
FROM cursos
WHERE estadoCurso = ? ORDER BY nombreCurso ASC
");
$select_cursos->bind_param('s', $nombreCurso);
$nombreCurso = 'abierto'; // This you can get from a $_POST too
if (!$select_cursos->execute()) { // ERROR
echo('Error');
} else { // OK
$select_cursos_result = $select_cursos->get_result();
$select_cursos_count = select_cursos_result->num_rows;
echo('Found: '.$select_cursos_count);
if ($select_cursos_count > 0) {
while ($data = $select_cursos_result->fetch_assoc()) {
echo ($data['nombreCurso'].'<br>');
}
} else {
echo ('No data!!');
}
}
?>
Cheers!!!
I'm currently using the following code to use PHP to grab data from an SQLite database. This extracts all data from column1 where the date is greater than a date I specify. The output goes into $output, where I can then stick the data in a table.
class MyDB extends SQLite3
{
function __construct()
{
$this->open('database_name.sdb');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully<br /><br />";
}
$sql =<<<EOF
SELECT * FROM "archive" WHERE "dateTime" > $specified_time;
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
$output = $row['column1'];
}
I now want to get the average of values in 'column 2' (where the date is greater than a certain date) and put it into a PHP variable. This is the code I'm using but it's returning a blank. I've tried a few other things too, but to no avail.
$sql =<<<EOF
SELECT AVG("column2") FROM "archive" WHERE "dateTime" > $specifiedtime;
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
$output = $row['AVG("column2")'];
}
Any ideas?
Thanks.
Use an alias for your calculated column
SELECT AVG(column2) as avg_col2 FROM ...
Then you can name that column in PHP
$output = $row["avg_col2"];
I need to run a mysql query that selects records from several tables. the names of the tables are received via post and are stored in an array.
What I have done is this that does not work:
//--> Check if anything is posted from the client
if(isset($_POST['code'])){
$emps = array();
foreach(($_POST['code']) as $c) {
$emps[] = $c;
}
#$res = mysql_query("select code,fname,faname from (".implode(',',$emps).")") where emp_code='11330' ;
while($r = mysql_fetch_array($res)){
//do something...
}
}
Replace
mysql_query("select code,fname,faname from (".implode(',',$emps).")") where emp_code='11330' ;
with
mysql_query("select code,fname,faname from (".implode(',',$emps).") where emp_code='11330'") ;
try this
for($i=0;$i<count($emps);$i++)
{
$query=$query."select code,fname,faname from ".$emps[$i]." where
".$emps[$i].".emp_code='11330' UNION " ;
}
#$res=mysql_query($query);
I'm working on an online booking system, so I have a php script that receives a date and will output an array of possible timeslots that are free on that date. I'm trying to make it so that when closing the datepicker it sends the variables to the file and retrieves the result. At the moment the submit button also leads to the php file, and will show me available slots when I choose a date. The php part works, but when I add events to the datepicker it won't submit any variables to the php file. I think this is also the cause that when I add another load.('input_date.php'); I get the full timeslot list caused by the if(isset... Can anyone tell me why jQuery is ruining my variable posting? Thanks in advance..
$(document).ready(function() {
$("#dates").load('input_date.php');
$("#datepicker").datepicker({onClose: function() {
$.post("input_date.php", $('#datepicker').serialize());
alert(1);
}});
});
This is the php file:
<?php
include('connection.php');
error_reporting(0);
$treatment = $_POST['treatment'];
$bookdate = $_POST['bookdate'];
if(isset($treatment) && isset($bookdate)){
$exp = explode("-", $bookdate);
//determine what day of the week it is
$timestamp = mktime(0,0,0,$exp[1],$exp[0],$exp[2]);
$dw = date( "w", $timestamp); // sun0,mon1,tue2,wed3,thur4,fri5,sat6
echo $dw."weekday"; //week day
echo"<br/>";
//find bookings with same date
$q = mysql_query("SELECT BOOK_SLOT_ID FROM BOOKINGS WHERE BOOK_DATE='$bookdate'");
//make array of booking slots
$array1 = array();
while ($s = mysql_fetch_array($q)) {
$array1[] = $s['BOOK_SLOT_ID'];
}
$q2 = mysql_query("SELECT SL_ID FROM SLOTS");
//make array of all slots
$array2 = array();
while ($s2 = mysql_fetch_array($q2)) {
$array2[] = $s2['SL_ID'];
}
//remove bookings from all slots
$arr_res = array_diff($array2, $array1);
//make selectable options of results
echo "<SELECT>";
foreach($arr_res as $op){
$r = mysql_query("SELECT SL_TIME FROM SLOTS WHERE SL_ID='$op'");
$q3 = mysql_fetch_array($r);
echo "<OPTION value=".$op.">".$q3['SL_TIME']."</OPTION>";
}
echo "</SELECT>";
}else{
$else = mysql_query("SELECT * FROM SLOTS");
echo "<SELECT>";
while($array_else = mysql_fetch_array($else)){
echo "<OPTION value=".$array_else['SL_ID'].">".$array_else['SL_TIME']."</OPTION>";
}
echo "</SELECT>";
}
?>
I believe it is because you have this line of code:
$('#datepicker').serialize()
This should be changed to the id of the form not the datapicker. In your PHP you are trying to get two seperate values:
$treatment = $_POST['treatment'];
$bookdate = $_POST['bookdate'];
Right now you are just sending the value of the input field #datepicker.