Choosing a table to save to based on drop down choice - php

I have 12 locations that I'm trying to figure out if I should create 12 tables (1 for each community) to save to or 1 table, add the location as a column, and throw everything in it and just get the data I need based on the location row?
CREATE TABLE `location1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`newsTitle` varchar(50) NOT NULL,
`introParagraph` varchar(500) NOT NULL,
`newsLink` varchar(100) NOT NULL,
`downloadLink` varchar(100) NOT NULL,
`file` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;

You can use a single table for your requirement.
When you need to save the data for locations which is different you can overcome this situation by using php serialize() and unserialize(). When you get data you can do whatever you want after unserializing. You can use the field as text.
CREATE TABLE `location` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`location` varchar(50) NOT NULL,
`location_data` text(32565) NOT NULL
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
Here is how you can save data in table
$location = 'Location A';
$location_data = array('langitude' => 32.123 , 'longitude' => 87.3123 , 'status' => 'active');
$serialized = serialize($location_data);
$query = "INSERT INTO location (location , location_data) VALUES ('$location','$serialized')";
mysqli_query($query);
$location = 'Location B';
$location_data = array('test1' => 123 , 'test2' => 321);
$serialized = serialize($location_data);
$query = "INSERT INTO location (location , location_data) VALUES ('$location','$serialized')";
mysqli_query($query);
And when you get result
$query= "SELECT * FROM location WHERE id=1";
$rs = mysqli_query($query);
$row = mysqli_fetch_assoc($rs);
$location_data = unserialize($row['location_data']);

1 table. If the only difference is which community the row belongs to, then definitely 1 table. If there will be other differences, then depends on use as Mike said.

Related

Reduce MySQL request time with Codeigniter

I use Codeigniter 3.1.11 and have some code which makes one big query to MySQL with an array. The time of a query with a limit of 30000 is about 9 seconds.
How can I reduce the request time? Maybe by using some indexes on my table, or do you know another method? If I need to use indexes, what indexes would I need to use and how can I use these indexes in my query on Codeigniter?
Code from model:
function rows_update() {
$query = $this->db->order_by('rating', 'DESC')->get_where('members', 'game_rating_and_balance_update_last_time <= now() - INTERVAL 1 DAY', '30000', '0');
$arrUpdateBatchData = [];
while ($row = $query->unbuffered_row('array'))
{
// some code here
$arrUpdateData = [
'UserID' => $row['UserID'],
'game_vault_balance' => $new_game_vault_balance,
'game_available_balance' => $new_game_available_balance,
'rating' => $rating_member,
'game_rating_and_balance_update_last_time' => date('Y-m-d H:i:s')
];
$arrUpdateBatchData[] = $arrUpdateData;
if (count($arrUpdateBatchData) > 500)
{
$this->db->update_batch('members', $arrUpdateBatchData, 'UserID');
$arrUpdateBatchData = [];
}
}
//update last items
if (count($arrUpdateBatchData) > 0)
{
$this->db->update_batch('members', $arrUpdateBatchData, 'UserID');
$arrUpdateBatchData = [];
}
return;
}
Raw query to MySQL with update_batch (I simply write only one row from an array):
UPDATE members SET game_vault_balance = CASE WHEN UserID = '9915075' THEN 803.60516004772 ELSE game_vault_balance END, game_available_balance = CASE WHEN UserID = '9915075' THEN 4.1253850908788 ELSE game_available_balance END, rating = CASE WHEN UserID = '9915075' THEN 0.24 ELSE rating END, game_rating_and_balance_update_last_time = CASE WHEN UserID = '9915075' THEN '2020-07-24 22:00:36' ELSE game_rating_and_balance_update_last_time END WHERE UserID IN('9915075')
Table structure:
CREATE TABLE `members` (
`id` int(10) UNSIGNED NOT NULL,
`UserID` varchar(64) NOT NULL,
`telegram_id` varchar(64) DEFAULT NULL,
`first_name` varchar(64) DEFAULT NULL,
`last_name` varchar(64) DEFAULT NULL,
`language` varchar(64) DEFAULT NULL,
`currency` varchar(64) DEFAULT NULL,
`status` varchar(64) DEFAULT NULL,
`rating` varchar(64) DEFAULT NULL,
`game_vault_balance` decimal(32,8) DEFAULT 0.00000000,
`game_available_balance` decimal(32,8) DEFAULT 0.00000000,
`game_rating_and_balance_update_last_time` datetime DEFAULT NULL,
`updated` datetime DEFAULT NULL,
`created` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Indexes of this table:
ALTER TABLE `members`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `UserID` (`UserID`) USING BTREE;
AUTO_INCREMENT for the members table:
ALTER TABLE `members`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
COMMIT;

PHP If else and some logics

I just having some problem of if/else or somewhat logical things in here, I have a fullcalendar that shows all the date that being reserve, I limit the reserve by 5 per date, but when I having a 2 or more reserved on the date and having reserve by other date, It gives me the same result as 4.
global $db;
$data = array();
$query = "SELECT * FROM reserve_master
INNER JOIN reserve_details
on reserve_master.reserve_id = reserve_details.reserve_id
INNER JOIN reserve_indicator
on reserve_master.reserve_id = reserve_indicator.reserve_id
WHERE reserve_indicator.touserid = '$id'
AND reserve_master.type = 'Repair' ";
$res = mysqli_query($db,$query);
$count = mysqli_num_rows($res);
$count = 5 - $count;//count the available slot
$date_changed = "";
$reserve_id = 0;
foreach ($res as $row)
{
date_default_timezone_set('Asia/Manila');
$current_timestamp = strtotime($row["dateend"] . '+1 day');
$time = date("Y/m/d",$current_timestamp);
if($row["datestart"] == $date_changed)
{
//This is for avoiding repeating graph on fullcalendar
}
else
{
if(empty($count))
{
$count = '0';
}
else
{
$count;
}
$data[] = array(
'id' => $row["reserve_id"],
'title' => $count,
'start' => $row["datestart"],
'end' => $time,
'color' =>getColor($row["status"])
);
$date_changed = $row["datestart"];
$reserve_id = $row["reserve_id"];
}
}
echo json_encode($data);
This is image of the error with captions
Database
CREATE TABLE `reserve_master` (
`reserve_id` int(11) NOT NULL AUTO_INCREMENT,
`datestart` date NOT NULL,
`dateend` date NOT NULL,
`type` varchar(255) NOT NULL,
PRIMARY KEY (`reserve_id`)
) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=latin
CREATE TABLE `reserve_indicator` (
`indicator_id` int(11) NOT NULL AUTO_INCREMENT,
`reserve_id` int(11) NOT NULL,
`touserid` int(11) NOT NULL,
`byuserid` int(11) NOT NULL,
PRIMARY KEY (`indicator_id`),
KEY `reserve_id` (`reserve_id`) USING BTREE,
CONSTRAINT `reserve_indicator_ibfk_1` FOREIGN KEY (`reserve_id`) REFERENCES `reserve_master` (`reserve_id`)
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=latin1
CREATE TABLE `reserve_details` (
`details_id` int(11) NOT NULL AUTO_INCREMENT,
`reserve_id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
`status` varchar(255) NOT NULL,
`location` varchar(255) NOT NULL,
PRIMARY KEY (`details_id`),
KEY `reserve_id` (`reserve_id`) USING BTREE,
CONSTRAINT `reserve_details_ibfk_1` FOREIGN KEY (`reserve_id`) REFERENCES `reserve_master` (`reserve_id`)
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=latin1
All i had tried is to get the right available on the 2nd of febuary 2018 and not the others.
The code is mess, I'm very sorry;
Problem is solved already;
I use eventLimit on fullcalendar and set it to 1
Count = 5 not subtracted by the num_rows
and few set on if-statement
Few answer I used rows and res as it is easy to indicate for results and rows, and i used it same as other queries.
Thank you.

How can i display the total no of books belonging to a rack?

Here is my table of books tbl_books
CREATE TABLE IF NOT EXISTS `tbl_books` (
`book_id` int(11) NOT NULL AUTO_INCREMENT,
`book_title` varchar(255) NOT NULL,
`book_author` varchar(255) NOT NULL,
`book_year` varchar(255) NOT NULL,
`book_rack` varchar(255) NOT NULL,
PRIMARY KEY (`book_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
Here is my second table of rack tbl_rack
CREATE TABLE IF NOT EXISTS `tbl_rack` (
`rack_id` int(11) NOT NULL AUTO_INCREMENT,
`rack_name` varchar(255) NOT NULL,
PRIMARY KEY (`rack_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
Problem which i want to solve:
I want to display all the data of rack in a table
Id Name Total no books in this rack ?
How can i display the total no of of books which are belongs to a specific rack..??/
Please help
you can loop through your racks and count each book on that rack ( I take it tbl_books.book_rack = tbl_rack.rack_name and you know how to connect to your database with pdo and your connection is called $db)
$rack = $db->query('select distinct rack_name from tbl_racks');
$rack->execute(); $result = $rack->fetch_all('PDO::FETCH_ASSOC');
foreach($result as $r){
$books = $db->query('count(book_id) as num_books from tbl_books where book_rack = :book_rack');
$books->execute(array("book_rack"=>$r['rack_name']));
$b = $books->fetch('PDO::FETCH_ASSOC');
echo $b['num_books'];
}

Assigning the value of a table row ID with another ID using an SQL statement

So in my database i have two tables. Jokes and Comments. I want the ability to assign the post_id of the comment, to the joke_id of the joke, so it will assign and retrieve the comments relating to that joke. My problem is that i suck at writing SQL statements and haven't the foggiest on how to join two tables to make this happen.
My jokes table looks like this:
CREATE TABLE IF NOT EXISTS `jokes` (
`joke_id` int(11) NOT NULL AUTO_INCREMENT,
`joke` varchar(1024) NOT NULL,
`category_id` int(11) NOT NULL,
`vote` int(255) NOT NULL,
`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`joke_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
and my comments table looks like this:
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`comment` text NOT NULL,
`joke_id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
and for the moment, I am grabbing the data by assigned the $post_id = "1", but i want to change it to something like $post_id = $joke_id (with the joke id being in the same function, but i have no idea how to do it).
I'm using a MVC with codeigniter if thats any help.
Inside my controller, i have a php file called comments which has a function called insertComment, which looks like this:
public function insertComment(){
//extracts the data from the ajax
extract($_POST);
if($_POST['act'] == 'add-com'){
//assigned the db rows with the actual data which was inputted
$data = array(
'name' => htmlentities($name),
'comment' => htmlentities($comment),
//id_post should correlate to the joke_id
'id_post' => $id_post = "1"
);
$this->comments_m->insertComment($data);
}
and my insertComment function, inside the models of comment_m function looks like this:
function insertComment (){
extract($_POST);
if($_POST['act'] == 'add-com'){
$data = array(
'name' => htmlentities($name),
'comment' => htmlentities($comment),
'id_post' => $id_post = "1"
);
if(strlen($data['name']) <= '1'){
$data['name'] = 'Guest';
}
$this->db->insert('comments', $data);
}
}
To finalise, it would be a great help if someone could help with an SQL statement which joins the two tables together, which the joke_id having the same value as the comment's post_id which will make it unique to that joke.
Thank you
The SQL to join these two tables is -
SELECT `jokes`.*, `comments`.*
FROM `jokes`
LEFT OUTER JOIN `comments`
ON `jokes`.`joke_id` = `comments`.`joke_id`
This will return all of the comments for each joke. You can then filter or limit by adding the WHERE clause(s) -
WHERE `jokes`.`joke_id` = 1

Wrong Value showing in echo after request

I am trying to make a team name shown from a URL pulling information from my database regarding that team
<?
$query = "select * from teams where
name='".$mysqli->real_escape_string($_REQUEST['name'])."'";
$result = $mysqli->query( $query );
$row = $result->fetch_assoc();
$id = $row['id'];
$name = $row['name'];
$lon = $row['lon'];
$lat = $row['lat'];
$distance = $row['distance'];
$postcode = $row['postcode'];
$phone = $row['phone'];
?>
This worked fine until I put a second team name in the database and now all pages shows that name
the URL is http://domain.com/team.php?name=Test%20TeamA
and its showing Test TeamB and not the required one above
I have checked this on 2 pc's just to make sure its not something wrong with my form i used to put the data into my database or any values hanging about in my browser
why is this doing it?
SQL DUMP
--
-- Table structure for table `teams`
--
CREATE TABLE IF NOT EXISTS `teams` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`lat` varchar(32) NOT NULL,
`lon` varchar(32) NOT NULL,
`distance` varchar(20) NOT NULL,
`postcode` varchar(20) NOT NULL,
`phone` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `teams`
--
INSERT INTO `teams` (`id`, `name`, `lat`, `lon`, `distance`, `postcode`, `phone`) VALUES
(1, 'Test TeamA', '52.483038', '0.178962', '12.9', 'PE15 0JJ', ''),
(3, 'Test TeamB', '52.45645', '0.823423', '12', '', '01231223');
This is not the idea answer for a question like this but please see all the replies under my question
In my case it was a error on another page that i was including on my page
My best advice is to do what NickCoon had commented
echo $query;
to see the query that is being used. then strip all your page down to eliminate the issue

Categories