I want all serialNo from registration table and then send it back to device. I try this:
date_default_timezone_set ('Asia/Phnom_Penh');
// Create a header with the current time
header('Last-Modified: ' . date("D, d M Y H:i:s", time()) . ' GMT+7');
$query1 = mysql_query("select serialNo from registration");
$row = mysql_fetch_array($query1);
$serialsArray = Array($row['serialNo']);
$tag = '';
if(!empty($_GET['passesUpadatedSince'])){
$tag = strtotime($_GET['passesUpadatedSince']);
error_log('Tag: ' .$tag,0);
}
$query1 = mysql_query("select MAX(updateTag) as updateTag from digiCardPass");
$row1 = mysql_fetch_array($query1);
$updateTag = $row1['updateTag'];
error_log("get serial method");
//if (!empty($serialsArray) && $updateTag != $tag) {
if (!empty($serialsArray)) {
echo json_encode(array('lastUpdated' => (string)time(),
'serialNumbers' => $serialsArray));
}else {
response(204);
}
}
?>
But when I send serial, I see only 1 serial. This is the result: May 7 17:01:05 ML-iphone-5 passd[4234] <Warning>: Get serial numbers task completed with update tag 1367920864, serial numbers (
1
)
How can I get all serial ?
You should be using mysqli as the mysql_* is deprecated, but anyway...
You only see one result because you use:
$row1 = mysql_fetch_array($query1);
$updateTag = $row1['updateTag'];
You need something like this:
while ($row = mysql_fetch_row($query1))
{
// do something sensible with each one here
echo $row['updateTag'];
}
Because each device has own deviceID, so I just change : $query1 = mysql_query("select serialNo from registration where deviceID = '$deviceID'");
and now everything works like what I want !
Related
I want to compare two times (H:M:S)...
Here's the thing... I want to compare a time saved in a table on my database to the current time that PHP returns to me with date(). However, no comparisons are being made as the session variables (ClassName, ClassStartTime and ClassBlock) return me an undefined index (I believe that is because they are not saving anything so I'm trying to access something that doesn't exist).
How do I compare the times?
NOTE: The time in my database is being saved as data-type TIME, that's why I'm not performing a strtotime() on the variable today_time. Perhaps, that may be my mistake...
<?php
// Obtener hora de registro
date_default_timezone_set('America/Mexico_City');
$today_dW = date('w'); // Get number to know the day of the week. Formatted as {Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6}
$today_time = date('G:i:s'); // Get time. Formatted as {HH : MM : SS}
/*
*/
$class_id_query = "SELECT id_materia, bloque FROM horarios WHERE matricula_prof = '" . $_SESSION['TeacherID'] . "' dia_semana = " . $today_dW . " AND hora_inicio >= " . strtotime($today_time) . "";
// Save query result, if any was found, on var
$class_id_result = $connection->query($class_id_query);
// Check if matching result was found to be posted
if ($class_id_result->num_rows > 0)
{
// Fetch the associated data if any was found
while($row = $class_id_result->fetch_assoc())
{
$_SESSION['ClassID'] = $row['id_materia'];
$_SESSION['ClassStartTime'] = $row['hora_inicio'];
$_SESSION['ClassBlock'] = $row['bloque'];
}
}
Assuming the column hora_inicio is of the type TIME, you do not need strtotime.
$class_id_query = "SELECT id_materia, bloque FROM horarios WHERE matricula_prof = '" . $_SESSION['TeacherID'] . "' dia_semana = " . $today_dW . " AND hora_inicio >= '" . $today_time . "'"
I believe I found an answer...
Thanks to #csb I simulated the query using MySQL function TIME, to extract whatever string that was formatted as a time variable to be returned as time...
Since I'm testing with time, all I'm doing right now is filling up certain tables so more information can be returned. I'll keep you updated with the results, tomorrow.
NOTE: I've found another problem... Certain variables inside the session array DO NOT CHANGE even if the query didn't run or returned another result...
<?php
// Get register time
date_default_timezone_set('America/Mexico_City');
$_SESSION['DayOfWeek'] = date('w');
// Get number to know the day of the week. Formatted as {Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6}
/*
This query must return the class ID, to read its information from the classes table
*/
$class_id_query = "SELECT id_materia, bloque, hora_inicio FROM horarios WHERE matricula_prof = '" . $_SESSION['TeacherID'] . "' AND dia_semana = " . $_SESSION['DayOfWeek'] . "AND TIME(hora_inicio) <= TIME(NOW())";
// Save query result, if any was found, on var
$class_id_result = $connection->query($class_id_query);
// Check if matching result was found to be posted
if ($class_id_result->num_rows > 0)
{
// Fetch the associated data if any was found
while($row = $class_id_result->fetch_assoc())
{
$_SESSION['ClassID'] = $row['id_materia'];
$_SESSION['ClassStartTime'] = $row['hora_inicio'];
$_SESSION['ClassBlock'] = $row['bloque'];
}
}
else
{
$_SESSION['ClassID'] = "";
$_SESSION['ClassStartTime'] = "";
$_SESSION['ClassBlock'] = "";
echo "Query for class ID cannot be performed";
exit();
}
/*
Career logo query.
Logo on ny part of the system
*/
// Query for the class information
$career_logo_query = "SELECT nombre, carrera, cuatrimestre FROM materias WHERE id = '" . $_SESSION['ClassID'] . "'";
// Save query result, if any was found, on var
$career_logo_result = $connection->query($career_logo_query);
// Check if matching result was found to be posted
if ($career_logo_result->num_rows > 0)
{
// Fetch the associated data if any was found
while($row = $career_logo_result->fetch_assoc())
{
$_SESSION['ClassName'] = $row['nombre'];
$_SESSION['CareerName'] = $row['carrera'];
$_SESSION['ClassPeriod'] = $row['cuatrimestre'];
// Show result at index on screen
echo $_SESSION['CareerName'];
}
}
?>_logo.png" alt = "Logotipo de <?php echo $_SESSION['CareerName']; ?>">
Here's an update of the code, I'll update tomorrow showing the results.
Thanks again #csb and #Lilthilion for your help and tips.
I finally got it!
All I needed to do was to transform the time and the query ran, the result i shown below
The result of the query, changing with the time
Now, all that lasts to be done is to get the students list for the form.
Thanks a lot, everybody.
Do you have to compare it with PHP time? What about the database time?
$class_id_query = "SELECT id_materia, bloque FROM horarios WHERE matricula_prof = '" . $_SESSION['TeacherID'] . "' dia_semana = " . $today_dW . " AND hora_inicio >= NOW()"
In past, when I want to display a text-content (textarea -> mySQL Database) in HTML, I used nl2br to display the content correctly in HTML.
Now I want to do this after decrypting the database-content, but it doens´t work.
$note = openssl_decrypt($note, "AES-256-CBC", "$encode_key", 0 , "$encode_key");
$outputNote = str_replace("\r\n", "test", "$note");
echo $outputNote;
What´s is wrong in this solution?
ok. Thats the full code generating note
$sql_notes = "SELECT content FROM gn_notes WHERE userid = '$sessionID' ORDER BY tstamp DESC";
$result = mysqli_query($db_link, $sql_notes);
$number=mysqli_num_rows($result);
if($number > 0) {
while ($record = mysqli_fetch_assoc($result)) {
$date = date("d.m.Y", $record['tstamp']);
$time = date("H:i", $record['tstamp']);
$note = $record['content'];
/* LOOKING FOR ENCODE_KEY */
$encode_key = getValue('encode_key', 'gn_user', $sessionID, $db_link);
$note = openssl_decrypt($note, "AES-256-CBC", "$encode_key", 0 , "$encode_key");
echo nl2br($note);
}
}
That is the output in the website:
Screenshot ouput
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Algorithm for generating a random number
Hi i need to assign a randomly generated number to some entries into the database and it must be unique.
I use:
$random_number = mt_rand();
mysqli_query($db_connection, "INSERT INTO my_table (rand_num, blabla) VALUES ('$random_number', '$blabla')");
But ofc there could always be a slightly low chance that 2 random numbers will be the same.
Then i could do something like:
function random_check($random_number) {
require_once('db_access.php');
$random_check = mysqli_query($db_connection, "SELECT rand_num FROM my_table");
mysqli_close($db_connection);
$result = 1;
while($row = mysqli_fetch_array($random_check)){
if ($row['rand_num'] == $random_number) {
$result=0
}
}
return $result;
};
$random_number = mt_rand();
$random_check = random_check($random_number);
if ($random_check == 0) {
$random_number = mt_rand();
}
But this would only check the number once and there will still be a chance that the new generated number already exists into the db.
Any suggestions?
Thanks
Here is a method which you can use:
<?php
$num= mt_rand();
$con = mysql_connect("localhost","uname","password");
mysql_select_db("dbname",$con);
$sel_query = "SELECT * FROM my_table WHERE rand_num =%d"; // query to select value
$ins_query = "INSERT INTO my_table(rand_num) VALUES(%d)"; // query to insert value
$result = mysql_query(sprintf($sel_query,$num),$con);
while( mysql_num_rows($result) != 0 ) { // loops till an unique value is found
$num = mt_rand();
$result = mysql_query(sprintf($sel_query,$num),$con);
}
mysql_query(sprintf($ins_query,$num),$con); // inserts value
?>
Doing a SELECT rand_num FROM my_table and checking the resulting values is very, very inefficient. Use a WHERE clause:
do {
$random_number = mt_rand();
$query_object = mysqli_query($db_connection, "SELECT 1 FROM my_table WHERE rand_num = $random_number");
$query_record = mysqli_fetch_array($query_object);
if(! $query_record) {
break;
}
} while(1);
It is possible to write this code in lesser lines.
function random_check($random_number) {
require_once('db_access.php');
$random_check = mysqli_query($db_connection, "SELECT rand_num FROM my_table");
mysqli_close($db_connection);
while($row = mysqli_fetch_array($random_check)){
if ($row['rand_num'] == $random_number) {
return false;
}
}
return true;
};
while(!random_check(mt_rand()){
$myNumbber = random_check(mt_rand();
}
--> Now u got unique number in "myNumber"
md5( strtotime("now").$_SERVER['REMOTE_ADDR'] );
strtotime("now") would give you a unique number, but ifyou are using this script to process forms/uploads etc from multiple users, the ip address will just make certain of that (on the off chance that at the exact same second two entries are made... can that even happen?? hmm...)
md5() cos i felt like it :D
I need help to convert the following Visual Basic statement into a PHP equivalent:
If Not IsNumeric(siteid) Then
dr = GetDataReader("SELECT siteid FROM nwsite WITH (NOLOCK) WHERE mac_address = '" & siteid & "'")
If Not dr.HasRows Then
Response.Write(sep & siteid & "=" & siteid)
sep = ","
End If
If Not dr Is Nothing Then
dr.Close()
End If
End If
I need help with the If statements more than anything.
Thanks
See here for the docs you need to check, also here
Seems like you also need to learn how to use mySQL in PHP
The code is relatively easy, in its simplest step- almost line for line from what you have to help you see the transformation to PHP (there are better implementations):
$siteid = 1; // where 1 is the value of siteid, PHP vars are prefixed with '$'
// you also could do
// if(!isset($siteid){
// if(!$siteid){
if(!is_numeric($siteid){
// there is no site ID, so get it from the DB
// Make a MySQL Connection
mysql_connect("localhost", "user", "password") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());
// Run your query
$result = mysql_query("SELECT siteid FROM nwsite WITH (NOLOCK) WHERE mac_address = ".$siteid)
or die(mysql_error());
if(mysql_num_rows($result)>0){
// rows returned
//assuming only one row is returned, with your siteid value
$row = mysql_fetch_array( $result );
$siteid=$row['siteid'];
}else{
// no rows returned
// do something
}
}else{
// $siteid is already a valid value
}
AN if statement goes something like this:
if(someexpression){
$yourcode = "your things";
}
quick mockup of your code:
if(!is_numeric($siteid){
//sql call
$result = yourdb->query('SELECT');
if(!$result){
echo "error";
}
}
if(!$this->IsNumeric($siteid))
{
$dr = $this->GetDataReader("SELECT siteid FROM nwsite WITH (NOLOCK) WHERE mac_address = $siteid");
if(!$dr->hasRows())
{
echo "$sep$siteid = $siteid";
$sep = " , ";
}
if(!is_null($dr))
{
$dr->close();
}
}
Following code may help you:
if (!is_numeric($siteid)) {
$res = mysql_query("SELECT siteid FROM nwsite WHERE mac_address = " . mysql_real_escape_string($siteid));
$rows = mysql_fetch_assoc($res);
if (count($rows) == 0) {
print($sep . $siteid . "=" . $siteid);
$sep = ',';
}
}
for ($i=0; $i<$count; $i++) {
$appid = $chk[$i];
include "dbconnect.php";
$selectquery = mysql_query("SELECT * FROM regform_admin WHERE tid = '$appid'");
$fetch = mysql_fetch_array($selectquery);
$tid = $fetch['tid']; $username = $fetch['username']; $c_month = $fetch['month']; $c_day =$fetch['day']; $c_year = $fetch['year'];
$c_month2 = $fetch['month2']; $c_day2 =$fetch['day2']; $c_year2 = $fetch['year2'];
$pickup = "".$c_month."/".$c_day."/".$c_year."";
$return = "".$c_month2."/".$c_day2."/".$c_year2."";
$pickuploc = "".$fetch['pickupret']." "." ".$fetch['speclocation']."";
$desti = "".$fetch['destination']." "." ".$fetch['location']."";
$vehicle1 = $fetch['vehicle1'];
$datesent = date("n j, Y; G:i"); ;
$rand = rand(98765432,23456789);
include "vehicledbconnect.php";
$vquery = mysql_query("SELECT * FROM vehicletbl WHERE vehicle = '$vehicle1'");
$getvquery = mysql_fetch_array($vquery);
$maxcars = $getvquery['maxcars'];
$carsleft = $getvquery['carsleft'];
if ($carsleft == 0) {
echo '
<script language="JavaScript">
alert("Cannot move reservation to Pending for payment status. No available vehicles left for this reservation.");
</script>';
echo "$vehicle1";
}
Hi guys my problem here is that the $vehicle is not returning its values if it is inserted in a database query ($vquery = mysql_query("SELECT * FROM vehicletbl WHERE vehicle = '$vehicle1'");) but if it is echoed, it return its value. The logic here is that it will select all the values from vehicletbl wherein the value of any values in 'vehicle' column will be equal to the $vehicle1. Thanks for the help!
You've got ZERO error handling on your queries. Try adding some debugging to the query calls:
$result = mysql_query(...) or die(mysql_error());
The rest of the code is ugly, but looks "ok", so start looking at WHY you're not getting anything back from the queries.
Never ever assume a query succeeds.
try this to debug :
$sql = "SELECT * FROM vehicletbl WHERE vehicle = '" . $vehicle1 . "'";
$vquery = mysql_query($sql) or die(mysql_error() . "\n<br>$sql");
thats what i do to find errors in my sql.
Noob programmer ? Here are some things to know :
for ($i=0; $i<$count; $i++) {
$appid = $chk[$i];
// Replaced By ...
foreach($chk as $appid){
http://php.net/manual/en/control-structures.foreach.php
// Include the file before the loop ! You're including 20 times your file, but you just need to do it once ! Another thing to know:
include_once("dbconnect.php");
http://php.net/manual/en/function.include-once.php
$desti = "".$fetch['destination']." "." ".$fetch['location']."";
// WHY ?? Isn't that easier to do this ?
$desti = $fetch['destination']." ".$fetch['location'];
And security :
// Don't forget to escape your variables before putting it in mysql queries
$appid = mysql_real_escape_string($appid);
$selectquery = mysql_query("SELECT * FROM regform_admin WHERE tid = '$appid'");
Best way to defend against mysql injection and cross site scripting
There are other remarks, but try to improve those points first !