This question already has answers here:
How to connect to a SQLite3 db with PHP
(3 answers)
Closed 5 years ago.
I need some help with my PHP code. I want to connect to the database file called myChannel.db to extract the data from the rows, but I have got no idea how to do that by using this code:
Here is the config:
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'myusername');
define('DB_PASSWORD', 'mypassword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
?>
Here is the get-listing.php script:
<?php
$errmsg_arr = array();
$errflag = true;
$link;
//Connect to the database
require_once('config.php');
$qrytable1="SELECT id, channels, programme_title, programme_description, programme_start_date, programme_end_date FROM tvguide WHERE channels='$channels' && id='$id'";
$result1 = mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
//output the data for channels, programme_title, programme_description, programme_start_date, programme_end
}
?>
The code will only allow me to connect to mysql and nothing is else.
Can you please show me an example how I could connect to myChannel.db and extract the data from the columns called channels, programme_title, programme_description, programme_start_date, programme_end where the channels is matched?
You asked for an example... this was my solution for querying geocoordinates from mySQL database. I call all of this in my php file...
//set up a MySQL query, this is the data you are asking for. This asks for all data from tabele 'shelters'. Be sure to call your specific table.
$sql = "SELECT * FROM shelters;";
if(!$results = $link->query($sql)){
die("Query Unsuccessful");
}
//Here I create a value map and pull out the results I care about from my request query.
$valueMap = array();
while ($data = $results->fetch_assoc()){
$valueMap[] = array(
'title' => $data['title'],
'lat' => $data['lat'],
'lng' => $data['lng'],
);
}
//encoding it into JSON is more manageble for me, but you will have to parse it into a javascript object in your index file.
$JSONData = json_encode($valueMap);
//heere you want to echo your data in order to retrieve it in your index file. Has the functionality of connecting to an API
echo $JSONData;
Hit me up in the comments with any more specific questions.
Related
I'm trying to connect to my Azure sql database using following code:
<?php
//Constants to connect with the database
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'xyz-server.database.windows.net');
define('DB_NAME', 'xyz_db');
<?php
//Class DbConnect
class DbConnect
{
//Variable to store database link
private $con;
//Class constructor
function __construct()
{
}
//This method will connect to the database
function connect()
{
//Including the constants.php file to get the database constants
include_once dirname(__FILE__) . '/Constants.php';
//connecting to mysql database
$this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//finally returning the connection link
return $this->con;
}
}
I'm getting this error
Type: ErrorException
Code: 2
Message: mysqli::__construct(): (HY000/9002): The connection string may not be right. Please visit portal for references.
File: /home/site/wwwroot/blingoo/include/DbConnect.php
Line: 22
I'm just beginning with Azure. Maybe I'm missing something. If you could simply point how to connect my database and web app(where I'm using php files to connect to the database), that will be great.
Seems to me that your code is trying to connect to MySQL rather than MSSQL.
To connect to MSSQL use the following:
<?php
$serverName = "your_server.database.windows.net"; // update me
$connectionOptions = array(
"Database" => "your_database", // update me
"Uid" => "your_username", // update me
"PWD" => "your_password" // update me
);
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
$tsql= "SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName
FROM [SalesLT].[ProductCategory] pc
JOIN [SalesLT].[Product] p
ON pc.productcategoryid = p.productcategoryid";
$getResults= sqlsrv_query($conn, $tsql);
echo ("Reading data from table" . PHP_EOL);
if ($getResults == FALSE)
echo (sqlsrv_errors());
while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC)) {
echo ($row['CategoryName'] . " " . $row['ProductName'] . PHP_EOL);
}
sqlsrv_free_stmt($getResults);
?>
source: https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-php
Since you are trying to connect to Azure SQL you can use PDO_DBLIB driver, if you have this extension installed. See php -m.
$config = [
'dsn' => 'dblib:host=xyz-server.database.windows.net;dbname=xyz_db',
'user' => 'username',
'pass' => 'password',
];
$connection = new PDO($config['dsn'], $config['user'], $config['pass']);
$sth = $connection->prepare('Your query comes here;');
$sth->execute();
$rows = $sth->fetchAll(PDO::FETCH_CLASS);
foreach ($rows as $row) {
// Do the processing here
}
When I was trying to make website for school project then I make a registration page so I make a html page and a php and a database.
But when I tried to enter anything in form then the result after submitting the information is blank page. When I opened php file in browser then a blank page opened. There should be either connected to the database or failed to connect to database. My coding of php file is given below:
Please help me as less time is remaining for last date of submission.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'practice');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db(DB_NAME, $con) or die("Failed to connect to MySQL: " . mysql_error());
function NewUser()
{
$fullname = $_POST['name'];
$userName = $_POST['user'];
$email = $_POST['email'];
$password = $_POST['pass'];
$query = "INSERT INTO websiteusers(fullname,userName,email,pass) VALUES ('$fullname','$userName','$email','$password')";
$data = mysql_query($query) or die(mysql_error());
if ($data) {
echo "YOUR REGISTRATION IS COMPLETED...";
}
}
function SignUp()
{
if (!empty($_POST['user'])) //checking the 'user' name which is from Sign-Up.html, is it empty or have some text
{
$query = mysql_query("SELECT * FROM websiteusers WHERE userName='$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
if (!$row = mysql_fetch_array($query) or die(mysql_error())) {
newuser();
} else {
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
}
}
if (isset($_POST['submit'])) {
SignUp();
}
?>
MySQL is depreciated. Use MySQli instead
Connect to your database this way
$connect = mysqli_query(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
then check this way
if($connect){
echo "Connected";
}else{
echo "Not connected";
}
and any query you run should be in this format
$query = mysqli_query($connect,$Sql);
I tried many source codes from google but I am unsuccessful everytime. Everytime I clicked on submit button it shows a blank page. Please provide me help I want to create a signup page and in this I want to connect html coding to mysql database I have knowledge about html. So please provide an easy way to interconnect the database and html.
I also came to know about the php so I tried to copy source code from google but everytime I failed as php preview in browser is blank page.
I am working on a small social web application as a final project for my iOS class. I have a profile view controller where all the info about the user from the database is supposed to be displayed on the labels. The problem is that I don't really know the best way to do this. Here is my php script:
<?
// Database credentials
$host = 'localhost';
$db = 'blabla';
$uid = 'blabla';
$pwd = 'blabla';
// Connect to the database server
$link = mysql_connect($host, $uid, $pwd) or die("Could not connect");
//select the json database
mysql_select_db($db) or die("Could not select database");
// Create an array to hold our results
$arr = array();
//Execute the query
$rs = mysql_query("SELECT IdUser, username, fullname, phonenumber, facebook, instagram FROM login");
// Add the rows to the array
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
//return the json result.
echo '{"users":'.json_encode($arr).'}';
?>
So here I get the info about all the users in the database. I am sure this is not the right way to go, so I guess I need to change the SQL query to retrieve the data for the current user only. But how can I do this? Should I put the username which I enter on the login page into an extra variable and then pass it with JSON to this php script and add the 'WHERE username = 'blabla' statement to the SQL query then? If so, how can I pass the variable to this script with JSON?
Can you please give me some sample code? Or is there a different way to do this?
Thank you so much!
<?php
// Database credentials
$host = 'localhost';
$db = 'blabla';
$uid = 'blabla';
$pwd = 'blabla';
// Connect to the database server
$link = mysql_connect($host, $uid, $pwd) or die("Could not connect");
//select the json database
mysql_select_db($db) or die("Could not select database");
//Execute the query
$rs = mysql_query("SELECT IdUser, username, fullname, phonenumber, facebook, instagram FROM login");
// Add the rows to the array
$data = mysql_fetch_array($rs);
foreach($data as $rec){
echo "user: $rec<br>";
}
?>
Using Johnboy's tutorial on importing .csv files to MySQL, I tried to make a script that would take exchange rate data from Yahoo finance, and write it to the MySQL database.
<?php
//connect to the database
$host = "****"
$user = "****"
$password = "****"
$database = "****"
$connect = mysql_connect($host,$user,$password);
mysql_select_db($database,$connect);
//select the table
if ($_FILES[csv][size] > 0) {
//get the csv file
$symbol = "ZARINR"
$tag = "l1"
$file = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=$tag&s='$symbol'=x";
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO ZAR_to_INR(exchange_rate) VALUES
(
'".addslashes($data[0])."',
)
");
echo "done";
}
} while ($data = fgetcsv($handle,1000,",","'"));
//redirect
header('Location: import.php?success=1'); die;
}
else{
echo "nope";
}
?>
I added the echos in the hope that they'd tell me whether or not the script worked. It doesn't work at all. There are no error messages or anything. When I run the script by opening it in my webhost, it simply does not run.
I'd appreciate any advice on how to make this script work (or even an alternate way of solving the problem).
try using mysql debugs :
mysql_select_db($database) or die('Cant connect to database');
$result = mysql_query($query) or die('query fail : ' . mysql_error());
$connect = mysql_connect($host,$user,$password)
or die('Cant connect to server: ' . mysql_error());
to find this outputs you need to check your php error_log : where-does-php-store-the-error-log
I need to get some data from a Microsoft SQL Server database at work. When I have the data I need, I need to make an Excel spreadsheet that can be saved locally on my computer.
I found PHPExcel which seems to do the job on the Excel part, but what about getting the data from the Database?
I can't seem to find anything that's recent. Only old tutorials.
Use this way to Fetch the Records :
<?php
$hostname = "192.168.3.50";
$username = "sa";
$password = "123456";
$dbName = "yourdb";
MSSQL_CONNECT($hostname,$username,$password) or DIE("DATABASE FAILED TO RESPOND.");
mssql_select_db($dbName) or DIE("Database unavailable");
$query = "SELECT * FROM dbo.table";
$result = mssql_query( $query );
for ($i = 0; $i < mssql_num_rows( $result ); ++$i)
{
$line = mssql_fetch_row($result);
print( "$line[0] - $line[1]\n");
}
?>
This will fetch each rows from the Data Retrieve and Print on the Page. Use your Required format into that. I mean, Use html Table to show the data in well format.
Use this code to get an data from Database.
<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = '192.168.3.50';
// Connect to MSSQL
$link = mssql_connect($server, 'sa', 'sa');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
else{
echo "connected ";
mssql_select_db('Matrix') or die("Wrong DATAbase");
//mssql_query("SELECT Seq_no from dbo.Trans_R WHERE Seq_no = 000001",$link) or die("cannot execute the query");
$query = mssql_query("SELECT Tr_Date,Tr_Time,Tr_Data from Matrix.dbo.Trans_R");
$f = mssql_fetch_array($query);
echo $f['Tr_Date'];
}
?>
Can i know why Negative Vote??
He asked me to :
" but what about getting the data from the Database?"