my SQL statement is not outputting anything when run. Just an empty screen.
Here is my PHP code:
<?php
$con = mysqli_connect("localhost", "root", "root","payBills");
$paidBills = "SELECT * FROM houseBills WHERE houseID = '20'";
$resultset = mysqli_query($con, $paidBills);
$records = array();
//Loop through all our records and add them to our array
while ($r = mysqli_fetch_assoc($resultset)) {
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
?>
and here is my SQL tables
CREATE TABLE `houseBills` (
`houseBillID` int(11) NOT NULL AUTO_INCREMENT,
`houseID` varchar(11) NOT NULL,
`name` varchar(50) NOT NULL,
`amount` varchar(10) NOT NULL,
`date` varchar(50) NOT NULL,
`addedBy` varchar(100) NOT NULL,
PRIMARY KEY (`houseBillID`),
UNIQUE KEY `houseBillID` (`houseBillID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `houseBills`
--
INSERT INTO `houseBills` (`houseBillID`, `houseID`, `name`, `amount`, `date`, `addedBy`) VALUES
(1, '20', 'Loo roll', '£10', '10', 'samstone920#googlemail.com'),
(2, '20', 'toothpaste', '3', 'egreg', '44tq');
Is there any plainly obvious that I am missing?
Table is currently set as CHARSET=latin1 JSON_ENCODE doesn't except this. See this post: json_encode is returning NULL?. ALTER TABLE houseBills CONVERT TO CHARACTER SET utf8;
Because the table already contains data before the alteration this stills give a problem. In this case (test phase project) the solution is to re-enter data. For large existing table perhaps try copying data to new table might offer a solution. Please note this is untested.
Related
I have an php array:
$cont_array = Array("613:m-ent:id=one","930:m-lk:id=one;x=180;y=79;which=1","1080:m-lev:id=one;");
I want to insert it into a MySQL table with table-name as variable, like $table_name = "user1".
In addition, I want to break each array-element by the first ":" .After executing my php code I get just an empty table.
I need help please. This is my code:
<?php
$connection = mysqli_connect('localhost','root','','prueba');
$cont_array = Array("613:m-ent:id=one","930:m-clk:id=one;x=180;y=79;which=1","1080:m-lev:id=one;");
$table_name = "user1";
$sql_1 = "DROP TABLE IF EXISTS `".$table_name."`;";
$sql_1 .= "CREATE TABLE `".$table_name."` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`usercod` varchar(20) NOT NULL DEFAULT '',
`pid` varchar(1000) NOT NULL DEFAULT '',
`name` varchar(1000) NOT NULL DEFAULT '',
`time` varchar(1000) NOT NULL DEFAULT '',
`all_act` varchar(1000) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;";
mysqli_multi_query($connection,$sql_1);
foreach ($cont_array as $row){
$break_e = explode(':', $row, 2);
$sql="INSERT INTO`".$table_name."` (usercode,pid,name,time,all_act) VALUES ("user","pid_value","user_name",'$break_e [0]','$break_e [1]');";
mysqli_query($connection,$sql);
}
?>
This is what I get:
This is what I would like to get:
Your SQL seem to have issue check below SQL statement.
$sql = "INSERT INTO $table_name (usercod,pid,name,time,all_act) VALUES ('user','pid_value','user_name','".$break_e [0]."','".$break_e [1]."')";
Here is my function which i am using to un-follow users.It first DELETE the relationship between users and all the notifications that are related to this relationship.Then it INSERT a new notification for user which we are going to un-follow and then UPDATE his followers count (as one follower has left).I am using multi_query and this query seems to be bit slower on large database and i want to know whether it's a good practice or not or is there is any more complex form of query to get the job done.
PHP Function
// 'By' is the array that hold logged user and 'followed' is the user id which we are going to unfollow
function unFollowUser($followed,$by) {
$following = $this->getUserByID($followed);// Return fetch_assoc of user row
if(!empty($following['idu'])) { // if user exists
// return user followers as number of rows
$followers = $this->db->real_escape_string($this->numberFollowers($following['idu'])) - 1;
$followed_esc = $this->db->real_escape_string($following['idu']);
$by_user_esc = $this->db->real_escape_string($by['idu']);
// delete relationship
$query = "DELETE FROM `relationships` WHERE `relationships`.`user2` = '$followed_esc' AND `relationships`.`user1` = '$by_user_esc' ;" ;
// delete notification (user started following you )
$query.= "DELETE FROM `notifications` WHERE `notifications`.`not_from` = '$by_user_esc' AND `notifications`.`not_to` = '$followed_esc' ;" ;
// Insert a new notification( user has unfollowed you)
$query.= "INSERT INTO `notifications`(`id`, `not_from`, `not_to`, `not_content_id`,`not_content`,`not_type`,`not_read`, `not_time`) VALUES (NULL, '$by_user_esc', '$followed_esc', '0','0','5','0', CURRENT_TIMESTAMP) ;" ;
// update user followers (-1)
$query .= "UPDATE `users` SET `followers` = '$followers' WHERE `users`.`idu` = '$followed_esc' ;" ;
if($this->db->multi_query($query) === TRUE) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
Table structures
--
-- Table structure for table `notifications`
--
CREATE TABLE IF NOT EXISTS `notifications` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`not_from` int(11) NOT NULL,
`not_to` int(11) NOT NULL,
`not_content_id` int(11) NOT NULL,
`not_content` int(11) NOT NULL,
`not_type` int(11) NOT NULL,
`not_read` int(11) NOT NULL,
`not_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Table structure for table `relationships`
--
CREATE TABLE IF NOT EXISTS `relationships` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user1` int(11) NOT NULL,
`user2` int(11) NOT NULL,
`status` int(11) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`idu` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL,
`password` varchar(256) NOT NULL,
`email` varchar(256) NOT NULL,
`first_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`verified` int(11) NOT NULL,
`posts` text CHARACTER SET utf32 NOT NULL,
`photos` text CHARACTER SET utf32 NOT NULL,
`followers` text CHARACTER SET utf32 NOT NULL,
UNIQUE KEY `id` (`idu`),
UNIQUE KEY `idu` (`idu`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
In my testing, multi_query has been the fastest way to execute multiple different queries. Why do you feel it's running slow? Compared to what?
Anyway, improvements could come from adding indexes to some of the columns you search frequently:
relationships.users2
relationships.users1
notifications.not_from
notifications.not_to
users.idu
Adding indexes makes searching faster, but it has at least two downsides:
Makes the DB a lot more resource hungry, which could affect your server performance
Makes writing operations take longer
I don't see any problem with your current queries. Really consider whether the slow performance you're seeing comes from the DB queries themselves, or from the rest of your PHP process. Try measuring the script time with the queries, then skipping the queries and taking another measurement (you could hardcode query results). It will give you an idea of whether the slowness is attributable to something else.
Either way, benchmark.
Try creating index on user where deletes are running , this may speed up query
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.
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
I am trying to read from a database in MySQL and insert my data in another database in MySQL .
my first table is like this
CREATE TABLE IF NOT EXISTS `link` (
`_id` bigint(20) NOT NULL AUTO_INCREMENT,
`country` varchar(30) COLLATE utf8 DEFAULT NULL,
`time` varchar(20) COLLATE utf8 DEFAULT NULL,
`link` varchar(100) COLLATE utf8 DEFAULT NULL,
PRIMARY KEY (`_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6149 ;
and the second table is
CREATE TABLE IF NOT EXISTS `country` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(15) CHARACTER SET utf8 NOT NULL,
`Logo` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `Name_3` (`Name`),
UNIQUE KEY `ID` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8457 ;
There are about 6114 rows in first table that I'm trying to insert to second using this code
<?php
$tmp = mysqli_connect(******, *****, ****, *****); // First table in here
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$main = mysqli_connect(*****, *****, ****, ******); //Second table in here
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$req = "SELECT country FROM link";
$result = mysqli_query($tmp, $req) or die( mysqli_error($tmp) );
echo "-> ".mysqli_num_rows($result)."<br>";
while ($row = mysqli_fetch_array($result)) {
$con = $row["country"];
$req = "INSERT IGNORE INTO country (Name) VALUES ('$con')";
mysqli_query($main, $req) or die( mysqli_error($main) ) ;
}
?>
problem is the php code works but for 6114 take a very long time which I can't afford .
what is causing the code to take this long to work ? is it the "INSERT IGNORE" ?
is there any way I can do this faster ?
Since the databases are on the same server, you can simply use INSERT ... SELECT (which avoids having to bring the data into PHP and loop over the results executing separate database commands for each of them, so will be considerably faster):
INSERT INTO db2.country (Name) SELECT country FROM db1.link
you can try a create an index on column "country" of table Link.