I'm trying to fetch images and text from mysql using php with this example
example.
The result from php code is empty, where is the error in this php code?
I store my images in server folder and add links in the database.
<?php
require_once('dbConnect.php');
$sql = "SELECT * FROM androidosnames";
$r = mysqli_query($con,$sql);
$result = array();
while($res = mysqli_fetch_array($r)) {
array_push($result,array(
"AndroidNames"=>$res['AndroidNames'],
"ImagePath"=>$res['ImagePath']
));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
using your code and this dbConnect.php
<?php
$con = new mysqli('localhost', 'broadcasting', 'broadcasting', 'broadcasting', 3306);
and this database information
CREATE TABLE IF NOT EXISTS `androidosnames` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`AndroidNames` varchar(50) NOT NULL,
`ImagePath` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
INSERT INTO `androidosnames` (`id`, `AndroidNames`, `ImagePath`) VALUES
(1, 'myname', '/ports/links');
yields following result when executing on command line (php -f test.php)
{"result":[{"AndroidNames":"myname","ImagePath":"\/ports\/links"}]}
So everything works as intended. It looks to me like the information from the database cannot be retrieved in your environment.
Related
I am not able to connect my database(.sql) file to heroku. I am using PHP for connecting database and frontend of webpage. The heroku page is showing the static site and for login page, it's showing error while registering new user. It's working perfectly fine when I run it on xampp server.
On clicking submit button of a form on heroku deployed app page, it says "herokuapp.com can't currently handle this request.".
Here's the link to my website https://enigmatic-journey-04762.herokuapp.com/login.html
Can someone tell me the steps of deploying php site on heroku using postgresql.....
Like this is the code I'm using for connection using PHP
<?php
session_start();
$con = mysqli_connect('localhost','root','');
mysqli_select_db($con,'task1');
$email = $_POST['email'];
$pass = $_POST['password'];
$s = "select * from farmer where email='$email' && password='$pass'";
$result = mysqli_query($con,$s);
$num = mysqli_num_rows($result);
if($num==1){
$row = mysqli_fetch_array($result);
$_SESSION['email']=$row['email'];
$_SESSION['fname']=$row['name'];
$_SESSION['fcity']=$row['city'];
$_SESSION['logged_in']=true;
header('location:profileFarmer.php');
}
else{
echo "Login error";
echo "<script>setTimeout(\"location.href = 'login.php';\",1500);</script>";
}
?>
This is what i did to connect to heroku postgresql.
Change all mysqli functions in the php to PDO functions so that they work with postgresql as well as mysql also.
Open the .sql file and file queries that start with CREATE and remove ' ` ' this character For eg Something like this
CREATE TABLE `blog` (
`id` int(11) NOT NULL,
`blog_id` text NOT NULL,
`heading` text NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_id` text NOT NULL,
`image_link` text
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
should be changed to this
CREATE TABLE blog (
id serial PRIMARY KEY,
blog_id text NOT NULL,
heading text NOT NULL,
created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
user_id text NOT NULL,
image_link text
)
and paste it to the heroku postgresql console and run it
Use pgweb for a phpmyadmin like interface for postgresql. Get the credentials to connect to the postgresql server in the heroku dashboard
I'm following this website to create mySQL table and php in order to convert data to JSON
SQL:
CREATE TABLE IF NOT EXISTS `employee` (
`id_employee` int(3) unsigned NOT NULL AUTO_INCREMENT,
`emp_name` varchar(10) DEFAULT NULL,
`designation` varchar(9) DEFAULT NULL,
`date_joined` date DEFAULT NULL,
`salary` decimal(7,2) DEFAULT NULL,
`id_dept` int(2) DEFAULT NULL,
PRIMARY KEY (`id_employee`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;
INSERT INTO `employee` (`id_employee`, `emp_name`, `designation`, `date_joined`, `salary`, `id_dept`) VALUES
(1, 'SMITH', 'CLERK', '2010-12-17', 2500.00, 20),
(2, 'ALLEN', 'SALESMAN', '2005-02-20', 3500.00, 30),
(3, 'WARD', 'SALESMAN', '2009-02-22', 3550.00, 30),
(4, 'JONES', 'MANAGER', '2010-04-02', 3975.00, 20),
(5, 'MARTIN', 'SALESMAN', '2011-09-28', 3300.00, 30);
PHP:
<?php
//Create Database connection
$db = mysql_connect("localhost","root","root");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("test_json",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from employee", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id_employee'] = $row['id_employee'];
$row_array['emp_name'] = $row['emp_name'];
$row_array['designation'] = $row['designation'];
$row_array['date_joined'] = $row['date_joined'];
$row_array['salary'] = $row['salary'];
$row_array['id_dept'] = $row['id_dept'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
However, i get 2 results with null and no other errors:
[{"id_employee":null,"emp_name":null,"designation":null,"date_joined":null,"salary":null,"id_dept":null},{"id_employee":null,"emp_name":null,"designation":null,"date_joined":null,"salary":null,"id_dept":null}]
I just copied the code and try to run it, how come there is no return in the result??
Can someone points out what's wrong with my code??
Or it is my server problem??
PHP version:5.2
MySQL ver. :5.1
Thank you
Please have a look at mysql_set_charset(). As about JSON itself, last error can be fetched with json_last_error().
You should replace mysql_fetch_array to mysql_fetch_assoc so you can access the variable by column name.
Also, you should start using mysqli instead of mysql, to connect and interact wth mysql database from php.
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.
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.
I am new to php and SQL so this is probably an easy question but I could not find any good sources online.
I am trying to create a SQL table when someone submits a form and this is what I have so far
include("dbstufflive.php");
$cxn = mysqli_connect($host,$user,$passwd,$dbname)
or die("Couldn't connect to server");
$sql = "CREATE TABLE IF NOT EXISTS `$company` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`company_name` varchar(80) NOT NULL,
`contact` varchar(50) NOT NULL,
`email` varchar(80) NOT NULL,
`phone` varchar(13) NOT NULL,
... (long list of table data)
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ";
mysqli_query($cxn,$sql);
I will of course be doing other stuff with this table but I think I have most of that under control.
The problem is that this statement does not actually create my table :( The SQL statement works in phpadmin when I enter it as is and also there are no errors when the script runs. So it goes through all of this, and more, and seems to work but the table simply doesn't appear.
I can supply more code if needed but I don't want to paste more code here than is necessary.
Thanks in advance for any help from the community.
EDIT:
I was using wrong DBinfo...wow, I am not very bright.
Your SQL Statement looks fine - from the looks of it, you are missing your login credentials. An efficient way to do so:
// Add this line
require_once('config.php');
// Then change the variables below to pull your credentials from that file.
$cxn = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD)
or die("Couldn't connect to server");
$sql = "CREATE TABLE IF NOT EXISTS `$company` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`company_name` varchar(80) NOT NULL,
`contact` varchar(50) NOT NULL,
`email` varchar(80) NOT NULL,
`phone` varchar(13) NOT NULL,
... (long list of table data)
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ";
mysqli_query($cxn,$sql);
Then create a new file called config.php in same directory. Put your credentials:
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASSWORD', 'your_password');
define('DB_DATABASE', 'database_name');
?>
You should check the result of mysqli_query (as far as i know it returns false on failure). See mysqli documentation for details, where you can read, that "Create table doesn't return a resultset" but True/false on sucess/failure.
example:
if (!mysqli->query($cxn,$sql)) {
printf("Error: %s\n", mysqli_error($cxn));
}