I try to make a diagram with RGraph(JS). I have a user counter on my site. And now I want to make a user-statistic with this diagram.
However I created a list which should be used for every query (made a form to choose month and year).
My problem is that the code doesnt enter the loop to create the new values (Day and Count).
Any idea?
Here the code:
$days = 0;
$day_value = array();
//check months which have 30 days
if (in_array($month, array(4,6,9,11))) {
$days = 30;
}
//leapyear?
if ($month == 2) {
if ($year%4 == 0) {
$days = 29;
} else {
$days = 28;
}
}
//Count users for each day
for ($i=1; $i<=$days; $i++) {
$sql = "SELECT
Anzahl
FROM
Counter
WHERE
YEAR(Datum) = '".$year."' AND
MONTH(Datum) = '".$month."' AND
DAYOFMONTH(Datum) = '".$i."'";
if (!$result = $db->query($sql)) {
return $db->error;
}
$row = $result->fetch_assoc();
$day_value[$i] = (int)$row['Anzahl'];
}
//delete list for new month/year
$sql = "DELETE
FROM
Statistics
";
if (!$result = $db->query($sql)) {
return $db->error;
}
//Create list with values for each day
for ($j=1; $j<=$days; $j++) {
$sql = "INSERT INTO
Statistics(Day,Count)
VALUES
(?, ?)";
$stmt = $db->prepare($sql);
if (!$stmt) {
return $db->error;
}
$stmt->bind_param('ii', $j, $day_value[$j]);
if (!$stmt->execute()) {
return $stmt->error;
}
$stmt->close();
}
$days is set to 0, it only changes if $months is 2,4,6,9,11 so for every other value of $month $days will be 0 and not enter the for loop.
if (in_array($month, array(4,6,9,11))) {
//code
}
elseif ($month == 2) {
//code
}
else{
//code
}
Related
I am trying to query two tables from a database, while using fetch_assoc() (instead of fetch_row()). The code is below and I am not getting any data from this query. I managed to query the first table, then added some code to query the second one and now I am not getting any output. Any help will be appreciated.
$mysqli = mysqli_connect($servername, $username, $password, "6dwxnmkq", 3314);
if(!$mysqli){
die('Connection failed!');
}
$sql = "SELECT IndexJedlo, Jedlo, Cena, Priloha FROM `jedalny_listok`";
$sql .= "SELECT index, polievka, cena FROM `polievky`";
$jedla = array(8);
$ceny = array(8);
$index = array(8);
$polievky = array(2);
$polievkyCeny = array(2);
$polievkyIndex = array(2);
$i = 0;
if ($mysqli->multi_query($sql)) {
do {
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
if($i == 0){
array_push($jedla, $row['Jedlo']);
array_push($ceny, $row['Cena']);
array_push($index, $row['IndexJedlo']);
}else{
array_push($polievky, $row['polievka']);
array_push($polievkyCeny, $row['cena']);
array_push($polievkyIndex, $row['index']);
}
}
$result->free();
}
if ($mysqli->more_results()) {
$i = $i + 1;
}
} while ($mysqli->next_result());
}
$mysqli->close();
I have to save more than one row of data into database table.
I wrote this code for that. But when i run this code, two rows will be saved into two rows of db table, but every other row is same as the last row data.
i.e. that is the last row data is overwriting every other row data.
$values = array();
if (isset($_POST['sub_save'])) {
$row_count = $_POST['rowcount'];
while ($row_count > 0) {
for ($r = 1; $r <= 2; $r++) {
$val = $_POST['txt'.$row_count.$r];
$values[] = $val;
}
$row_count = $row_count - 1;
$sql = "insert into timesheet_entry (name, address) values ('$values[0]', '$values[1]')";
if (mysql_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
}
}
You aren't resetting your values array inside the loop so values[0] and values[1] will always have the first to values.
if (isset($_POST['sub_save'])) {
$row_count = $_POST['rowcount'];
while ($row_count > 0) {
$values = array();
for ($r = 1; $r <= 2; $r++) {
$val = $_POST['txt'.$row_count.$r];
$values[] = $val;
}
$row_count = $row_count - 1;
$sql = "insert into timesheet_entry (name, address) values ('$values[0]', '$values[1]')";
if (mysql_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
}
}
On a sidenote I would recommend looking into the PDO extension and parameterised queries as mysql_ is deprecated and the above code is vulnerable to SQL injection
You are mixing mysql and mysqli:
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db("dbname");
if (mysqli_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
When I am fetching data from database in array it's showing only one element of each column. I am using below query:
$stmt = $conn_obj->select(' user ',' * ',' status = "updated" ', $order=NULL, $group=null, $fromRecordNum.','.$recordsPerPage);
and select function is below:
private function tableExists($table) {
//$this->con = $this->createconnection();
$query = 'SHOW TABLES FROM ' . $this->db . ' LIKE "'.trim($table).'"';
//echo ''.$query;
$tablesInDb = mysqli_query($this->con, $query);
if ($tablesInDb) {
if (mysqli_num_rows($tablesInDb) == 1) {
//echo ''.mysqli_num_rows($tablesInDb);
return true;
}
else {
return false;
}
}
}
public function select($table, $row = '*', $where= null,$order=null,$group=null, $limit=null, $join=null){
//$this->con = $this->createconnection();
//echo $join;
$q = 'select'.$row.' from '.$table;
//print_r($q);
if($join != null){
$q .= ' join '.$join;
}
if($where != null){
$q .= ' where '.$where;
print_r($q);
}
if($group != null){
$q .= 'group by'.$group;
//print_r($q);
}
if($order != null){
$q .= 'order by'.$order;
}
if($limit != null){
$q .= 'limit '.$limit;
print_r($q);
}
if ($this->tableExists($table)) {
$query = mysqli_query($this->con, $q) or die(mysql_error());
//print_r($query);
if ($query) {
$this->numResults = mysqli_num_rows($query);
//echo $this->numResults;
for ($i = 0; $i < $this->numResults; $i++) {
$r = mysqli_fetch_array($query);
$key = array_keys($r);
for ($x = 0; $x < count($key); $x++) {
// Sanitizes keys so only alphavalues are allowed
if (!is_int($key[$x])) {
if (mysqli_num_rows($query) > 1)
$this->result[$i][$key[$x]] = $r[$key[$x]];
else if (mysqli_num_rows($query) < 1)
$this->result = null;
else
$this->result[$key[$x]] = $r[$key[$x]];
}
}
}
//print_r($this->result);
return $this->result;
} else {
return false;
}
} else{
return false;
}
}
I am fetching it with foreach loop as follow:
foreach($stmt as $row)
{
echo $row['user_Id'];
}
output is= 7 t : 2 2 2 u W u 2
and if I print whole array with print_r($row) then
output is= test ::1 2015-07-30 11:42:09am 2015-07-29 12:42:09pm 2015-07-30 12:28:57pm updated call_activated uninstall 2015-07-30 12:31:07pm.
If database has only one row with specified query then above problem is creating.
But in the case of two row with the specified query, its working fine as I want.
For multiple results, you are getting an array of arrays of elements.
For a single result, you are getting an array of elements.
So, for a single element, you have one foreach loop too many.
if in your example:
foreach($stmt as $row) {
echo $row['user_Id'];
}
Assuming $stmt contains the return value of your query:
foreach($stmt as $row) {
if (isset($row['user_Id'])) {
// do something with one single result record
} else {
foreach ($row AS $innerRow) {
// do something with each result record
}
}
}
I'm developing a system that is used for booking resources per hour. For example booking a conference room by the hour or whatever. I've pretty much got all the functionality working but some things are far from perfect and there's one function that I've got that's bugging me. It's booking a resource for an entire week. My code for it is below but any help on making it more efficient would be greatly appreciated.
Thanks!
Steve
function bookweek($week) {
global $deskid, $date, $time, $member_id, $bookingTimes, $day0, $day1, $day2, $day3, $day4, $day5, $day6, $day7, $day8, $day9, $day10, $day11, $day12, $day13;
dbconnect();
switch($week) {
case 1:
$dupecheck = mysql_query("SELECT * FROM booked where deskid='$deskid' AND date>='$day0' AND date <'$day7'");
if (mysql_num_rows($dupecheck) == 0)
{
for($j = 0; $j< 7; $j++)
{
$daynumber=$j;
$testing = "day".$daynumber;
$daytotal= $$testing;
for($i = 1; $i < count($bookingTimes)+1; $i++)
{
$sql="INSERT INTO booked (date, time, deskid, member_id) VALUES ('$daytotal', '$i', '$deskid', '$member_id')";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
}
}
break;
case 2:
$dupecheck = mysql_query("SELECT * FROM booked where deskid='$deskid' AND date > '$day6'");
if (mysql_num_rows($dupecheck) == 0)
{
for($j = 0; $j< 7; $j++)
{
$daynumber=$j+7;
$testing = "day".$daynumber;
$daytotal= $$testing;
for($i = 1; $i < count($bookingTimes)+1; $i++)
{
$sql="INSERT INTO booked (date, time, deskid, member_id) VALUES ('$daytotal', '$i', '$deskid', '$member_id')";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
}
}
break;
}
}
That will be hard to maintain if used for any case the whole sql block.
Make it more efficient.
function bookweek($week) {
global $deskid, $date, $time, $member_id, $bookingTimes, $day0, $day1, $day2, $day3, $day4, $day5, $day6, $day7, $day8, $day9, $day10, $day11, $day12, $day13;
$queryP = "SELECT * FROM booked where deskid='".$deskid."' AND date>";
dbconnect();
switch($week) {
case 1:
$dupecheck = mysql_query($queryP."='".$day0."' AND date <'".$day7."'");
break;
case 2:
$dupecheck = mysql_query($queryP."'".$day6."'");
break;
}
if (mysql_num_rows($dupecheck) == 0)
[...]
And give mysqli a try
Now the code is more clear and it is immediately apparent that things can be improved.
$queryP = "SELECT * FROM booked where deskid='".$deskid."' AND date>";
dbconnect();
switch($week) {
case 1:
$queryP .= "='".$day0."' AND date <'".$day7."'";
break;
case 2:
$queryP .= "'".$day6."'";
break;
}
$dupecheck = mysql_query($queryP);
if (mysql_num_rows($dupecheck) == 0)
[...]
Let's come to the loop.
In order to better test on errors. I would change only the inner loop.
if (mysql_num_rows($dupecheck) == 0)
{
for($j = 0; $j< 7; $j++)
{
$testing = "day".$j;
$daytotal= $$testing;
$sql = "INSERT INTO booked (date, time, deskid, member_id) VALUES ";
$sqlTest = $sql;
for($i = 1; $i < count($bookingTimes)+1; $i++)
{
$sql .= "('".$daytotal."', '".$i."', '".$deskid."', '".$member_id."'),";
}
if ($sql == $sqlTest) {
// nothing to be done or die
} else {
$sql = rtrim($sql,",");
result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
}
}
I think that if you use prepared statements you will save much MySQL resources.
So I have this function that takes all the users from an MySql table and stores them in an array:
public function graphVals() {
$sql = "SELECT user_username FROM users WHERE user_register_date > CURDATE() - 2592000";
if ($stmt = $this->connect->prepare($sql)) {
$stmt->execute();
$stmt->bind_result($username);
while ($row = $stmt->fetch()) {
$stmt->bind_result($username);
$data[] = $username;
}
$stmt->close();
foreach($data as $key) {
$length[] = sizeof($key);
}
print_r($data);
} else {
$error = true;
$message['error'] = true;
$message['message'] = CANNOT_PREPARE_DATABASE_CONNECTION_MESSAGE;
return json_encode($message);
}
}
After that, as you can see I want to return an array which contains the length of the usernames array.
But my question is, as you can see I'm fetching an array with all usernames, each one at one index, what I actually want to do is take all users registered on one date and store them in a single index, all users registered on the date after the previous one and store them in the next index, etc.
How would I do that ? Can I adjust this function to do that ?
This is easy to do :
public function graphVals() {
$sql = "SELECT user_username FROM users WHERE user_register_date > CURDATE() - 2592000 ORDER BY user_register_date ASC";
$data = array();
if ($stmt = $this->connect->prepare($sql)) {
$stmt->execute();
$stmt->bind_result($username);
$stmt->bind_result($date);
while ($row = $stmt->fetch()) {
$stmt->bind_result($username);
if (!isset($data[$date])) {
// when the date is the first time in the array. Add that date as index for the array
$data[$date] = array();
}
$data[$date][] = $username;
}
$stmt->close();
foreach($data as $key) {
$length[] = sizeof($key);
}
print_r($data);
} else {
$error = true;
$message['error'] = true;
$message['message'] = CANNOT_PREPARE_DATABASE_CONNECTION_MESSAGE;
return json_encode($message);
}
}
Hope this helps :)
Start by adding an ORDER BY to your query. This isn't mandatory but will simplify things for you
SELECT user_username FROM users
WHERE user_register_date > CURDATE() - 2592000
ORDER BY user_register_date
Then check the date in your loop iteration, like so:
while ($row = $stmt->fetch()) {
$stmt->bind_result($username);
$stmt->bind_result($date);
if (!isset($data[$date])) {
// first time we encounter this date, creating a new array for it
$data[$date] = array();
}
$data[$date][] = $username;
}
So this is what I came up with after seeing your example code. Now I get it by date, as date the index, the only thing is that I had before NOW() instead of CURDATE() when registering, and I get the hour, min and sec too. But I think this is the solution. Let me know what you think, if I should do anything else.
$sql = "SELECT user_username, user_register_date FROM users WHERE user_register_date > CURDATE() - 2592000 ORDER BY user_register_date";
if ($stmt = $this->connect->prepare($sql)) {
$stmt->execute();
$stmt->bind_result($username,$date);
while ($row = $stmt->fetch()) {
$stmt->bind_result($username, $date);
if (!isset($data[$date])) {
$data[$date] = array();
}
$data[$date][] = $username;
}
$stmt->close();
foreach($data as $key) {
$length[] = sizeof($key);
}
print_r($data);
} else {
$error = true;
$message['error'] = true;
$message['message'] = CANNOT_PREPARE_DATABASE_CONNECTION_MESSAGE;
return json_encode($message);
}