I'm a newbie on php and I try to make a calendar for people travel information from db and want to show these info on the calendar's day so my problem is to connect MSSQL Server and take the values form db.My php pages work on localhost(wampp) and my calendar view perfectly but cannot get the value from DB.It does not give an error.But can not pull data.Could you please help me to find my fault.Thanks.
connect.php;
<?php
class DBO
{
private $server = "servername";
private $db_name = "dbname";
private $password = "pass";
private $username = "username";
private $conn;
private $database;
function Connect()
{
$this->conn = mssql_connect($this->server, $this->username, $this->password)
or die("Couldn't connect to SQL Server on " . $this->server);
$this->database = mssql_select_db($this->db_name, $this->conn)
or die("Couldn't open database " . $this->db_name);
}
function RunSql($sqlQuery)
{
return mssql_query($sqlQuery);
}
}
?>
query code;
<?php
include_once("db_connect.php");
$DBO = new DBO();
$DBO->Connect();
$query = "SELECT ID, TYPE, STARTDATE, ENDDATE FROM TABLENAME";
$query_results = $DBO->RunSql($query)
or die('Error in $query_menu. Error code :' . mssql_get_last_message() );
$calendar = array();
while( $results = mssql_fetch_assoc($query_menu_results) )
{
$calendar[] = array('ID' =>$rows['ID'],'TYPE' => $rows['TYPE'],'url' => "#","class" =>'event-important','start' => "$start",'end' => "$end");
}
$calendarData = array(
"success" => 1,
"result"=>$calendar);
echo json_encode($calendarData);
exit;
?>
<?php
I believe you're issue is from executing the SQL via...
$query_results = $DBO->RunSql($query)
...but using it via...
while( $results = mssql_fetch_assoc($query_menu_results) )
Basically, $query_results becomes $query_menu_results.
I use a variant of this to test MsSQL connectivity:
<?php
// connect to the server
$dbconn = mssql_connect('SEVER_NAME_OR_IP', 'MsSQL-User', 'MsSQL-User-Password');
if (!$dbconn) {
$message='unable to connect to the database: ' . mssql_get_last_message();
die($message);
}
// select the database
if (!mssql_select_db('DATABASE_NAME', $dbconn)) {
die('Unable to select the database!');
}
// execute a query. NOTE: Never use string concatenation in SQL statements. EVER!!!
$sql = "select * from information_schema.tables;";
$query = mssql_query($sql, $dbconn);
// consume the results
echo "<table border='1'><tr><th>Column A</th><th>Column B</th></tr>";
while ($row = mssql_fetch_row($query)) {
echo "<tr><td>";
echo $row[0];
echo "</td><td>";
echo $row[1];
echo "</td></tr>";
}
echo "</table>";
// clean up
mssql_free_result($query);
mssql_close($dbconn);
?>
SECURITY NOTE: Last I check, The mssql* doesn't support prepared statements. Please see PDO or sqlsrv*. This Question has good info on MsSQL prepared statements.
Solution:
I've reproduced your code and I've found these errors:
include_once("db_connect.php"); must be include_once("connect.php");
while ($results = mssql_fetch_assoc($query_menu_results)) { must be while ($results = mssql_fetch_assoc($query_results)) {
'ID' =>$rows['ID'], must be 'ID' => $results['ID'],
'TYPE' => $rows['TYPE'], must be 'TYPE' => $results['TYPE'],
missing $start and $end variables;
Working example:
Example is based on your code. I've left your erros in comment. Table definition is just to make working query.
Database:
CREATE TABLE [dbo].[TABLENAME] (
[ID] [numeric](10, 0) NULL,
[TYPE] [numeric](10, 0) NULL,
[STARTDATE] datetime NULL,
[ENDDATE] datetime NULL
) ON [PRIMARY]
INSERT [TABLENAME] (ID, TYPE, STARTDATE, ENDDATE)
VALUES (1, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
INSERT [TABLENAME] (ID, TYPE, STARTDATE, ENDDATE)
VALUES (1, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
SELECT ID, TYPE, STARTDATE, ENDDATE
FROM [TABLENAME]
connect.php
<?php
class DBO {
private $server = "servername";
private $db_name = "dbname";
private $password = "pass";
private $username = "username";
private $conn;
private $database;
function Connect() {
$this->conn =
mssql_connect($this->server, $this->username, $this->password) or
die("Couldn't connect to SQL Server on " . $this->server);
$this->database =
mssql_select_db($this->db_name, $this->conn) or
die("Couldn't open database " . $this->db_name);
}
function RunSql($sqlQuery) {
return mssql_query($sqlQuery);
}
}
?>
query.php
<?php
//include_once("db_connect.php");
include_once("connect.php");
$DBO = new DBO();
$DBO->Connect();
$query = "SELECT ID, TYPE, STARTDATE, ENDDATE FROM [TABLENAME]";
$query_results =
$DBO->RunSql($query)
or die('Error in $query_menu. Error code :' . mssql_get_last_message() );
$calendar = array();
//while ($results = mssql_fetch_assoc($query_menu_results)) {
while ($results = mssql_fetch_assoc($query_results)) {
$calendar[] = array(
//'ID' =>$rows['ID'],
'ID' => $results['ID'],
//'TYPE' => $rows['TYPE'],
'TYPE' => $results['TYPE'],
'url' => "#",
"class" => 'event-important',
//'start' => "$start",
//'end' => "$end"
);
}
$calendarData = array(
"success" => 1,
"result"=>$calendar
);
echo json_encode($calendarData);
exit;
?>
Output:
{
"success":1,
"result":[
{"ID":"1","TYPE":"1","url":"#","class":"event-important"},
{"ID":"1","TYPE":"1","url":"#","class":"event-important"}
]
}
Related
Forgive me if the question is a little odd
I can clarify if needed:
I have the code that can connect to a mysql database as normal, however i have encapsulated it as a class:
<?php
define("HOST", "127.0.0.1"); // The host you want to connect to.
define("USER", "phpuser"); // The database username.
define("PASSWORD", "Secretpassword"); // The database password.
class DBConnection{
function conn($sql, $database){
$DB = new mysqli(HOST,USER,PASSWORD,$database);
if ($DB->connect_error){
die("Connection failed: " . $DB->connect_error);
exit();
}
if ($result = $DB->query($sql)){
return TRUE;
$DB->close();
}
else{
echo "Error: " . $sql . "<br>" . $DB->error;
$DB->close();
}
}
}
?>
I have done it this way so i can include this class in any subsequent php page and allow them to send it an sql statment and the database, see below as an example:
$sql = ("INSERT INTO users (first_name, last_name, username, email, password, group_level) VALUES ('John', 'Doah','JDoah', 'example#email', 'password', 'user')");
$DB = new DBConnection;
$result = $DB->conn($sql,"members");
if ($result ==TRUE){
return "Record added sucessfully";
}
This works fine.
however, im looking to send other sql statments to DBConnection.
How do i do that and to have it pass back any results that it recives? errors, boolean, row data etc. The caller will worry about parsing it.
Hopefully that makes sense.
This is an old class I used to use way back in the days of mysql still works but will need to be updated for mysqli or newer
class DBManager{
private $credentials = array(
"host" => "localhost",
"user" => "",
"pass" => "",
"db" => ""
);
function DBManager(){
$this->ConnectToDBServer();
}
function ConnectToDBServer(){
mysql_connect($this->credentials["host"],$this->credentials["user"],$this->credentials["pass"]) or die(mysql_error());
$this->ConnectToDB();
session_start();
}
function ConnectToDB(){
mysql_select_db($this->credentials["db"]) or die(mysql_error());
}
function Insert($tableName,$data){
$parameters = '';
$len = count($data);
$i = 0;
foreach($data as $key => $value){
if(++$i === $len){
$parameters .= $key . "='$value'";
}else{
$parameters .= $key . "='$value'" . ", ";
}
}
$query = "INSERT INTO $tableName SET $parameters";
mysql_query($query) or die(mysql_error());
return true;
}
function GetRow($tableName,$select,$where){
$selection = '';
$len = count($select);
$i = 0;
foreach($select as $key){
if(++$i === $len){
$selection .= $key;
}else{
$selection .= $key . ",";
}
}
$whereAt = '';
foreach($where as $key => $value){
$whereAt .= $key . "='$value'";
}
$query = "SELECT $selection FROM $tableName WHERE $whereAt";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
return $row;
}
}
}
The key things here is you can create a persistent connection to your database without rewriting a bunch of code
Example
global $DB;
$DB = new DBManager();
Since the connection happens in the constructor you will now have a connection on the page you call this code and can begin getting and setting to the database through use of $DB->GetRow() and $DB->Insert() which makes things much easier and was modeled after the $wpdb instance which is a class that manages the database in wordpress sites
Examples
For these examples we will assume you have a table as such
Insert new student
//create an associative array
$data = array(
"student_id" => 1,
"birth_date" => "02/06/1992",
"grade_level" => 4
);
//Send Call
$dm->Insert("student",$data);
Get data
//Create selection
$selection = array("grade_level");
//Create associative array for where we want to find the data at
$where = array(
"id" => 1
);
//Get Result
$result = $dm->GetRow("student",$selection,$where);
//do something with result
echo $result->grade_level;
I created a PHP handler to receive a JSON payload from a POST request and then insert it into a database in phpMyAdmin. I'm not sure why this is not working.
JSON:
payload = {
"version":"1.0",
"event":"video_recorded",
"data":{
"videoName":"vs1457013120534_862",
"audioCodec":"NellyMoser ASAO",
"videoCodec":"H.264",
"type":"FLV",
"orientation":"landscape",
"id":"0",
"dateTime":"2016-03-03 15:51:44",
"timeZone":"Europe/Bucharest",
"payload":"111.111.111.11",
"httpReferer":"http://site_from_where_video_was_recorded.com"
}
}
The PHP code I got from a tutorial online. The tutorial was from 2017 so I'm assuming everything is up to date, but yet it still does not work:
<?php
/* db variables */
$dbhost = 'localhost';
$dbname = 'name_db';
$dbuser = 'user_db';
$dbpass = 'pass_db';
/* grab the json */
$data = $_POST['payload'];
/* put json into php associative array */
$data_array = json_decode($data);
/* store in PHP variables */
$ip_address = $data_array['data']['payload'];
$vid_name = $data_array['data']['videoName'];
$date_time = $data_array['data']['dateTime'];
$time_zone = $data_array['data']['timeZone'];
/* connect to mysql db */
$con = mysql_connect($dbuser, $dbpass, $dbhost) or die('Could not connect: ' . mysql_error());
/* select the specific db */
mysql_select_db($dbname, $con);
/* insert the values into the db */
$sql = "INSERT INTO ip_and_videos(IpAddress, VideoName, DateTime, Timezone) VALUES('$ip_address','$vid_name','$date_time','$time_zone')";
if(!mysql_query($sql,$con))
{
die('Error : ' . mysql_error());
}
?>
I have the primary key set to an int and have it on auto increment. If I understand correctly I don't need to insert anything into that column because it will assign a number each time. Or do I still need to pass it when I INSERT the other variables?
This works for the array part, you get correct answer. So, your code is not bad, but you should check all errors (as stated by Bhavin in comment). And I'm retty sure you have a typo -> $vid_name = $data_array['data']['videName']; is NOT like $vid_name = $data_array['data']['videoName']; Thereforer, error_reporting will be very helpful, and after that, check the query if other errors (prepared statements ^^)
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$payload = '{
"version":"1.0",
"event":"video_recorded",
"data": {
"videoName":"vs1457013120534_862",
"audioCodec":"NellyMoser ASAO",
"videoCodec":"H.264",
"type":"FLV",
"orientation":"landscape",
"id":"0",
"dateTime":"2016-03-03 15:51:44",
"timeZone":"Europe/Bucharest",
"payload":"111.111.111.11",
"httpReferer":"http://site_from_where_video_was_recorded.com"
}
}';
$data_array = json_decode($payload, true);
/* store in PHP variables */
$ip_address = $data_array['data']['payload'];
$vid_name = $data_array['data']['videoName'];
$date_time = $data_array['data']['dateTime'];
$time_zone = $data_array['data']['timeZone'];
echo"[ $ip_address / $vid_name / $date_time / $time_zone ]";
// EDIT : added query
include"config.inc.php";
// connect to DB
$mysqli = mysqli_connect("$host", "$user", "$mdp", "$db");
if (mysqli_connect_errno()) { echo "Error connecting : " . mysqli_connect_error($mysqli); }
$query = " INSERT INTO ip_and_videos (`IpAddress`, `VideoName`, `DateTime`, `Timezone`) VALUES (?,?,?,?) ";
$stmt = $mysqli->prepare($query);
print_r($stmt->error_list);
$stmt->bind_param("ssss", $ip_address, $vid_name, $date_time, $time_zone );
if (!$stmt->execute()) { echo $stmt->error; } else { echo"true"; }
?>
Not sure if you had the same issue but this does not work for me...
$vid_name = $data_array['data']['videName'];
I had to use
$vid_name = $data_array->data->videoName;
Can't use stdClass as an array.
Should be better this way
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
/* db variables */
$dbhost = 'localhost';
$dbname = 'name_db';
$dbuser = 'user_db';
$dbpass = 'pass_db';
/* grab the json */
$data = $_POST['payload'];
/* put json into php associative array */
$alldata = json_decode($data,true);
print_r($alldata);
/* connect to mysql db */
$con = mysql_connect($dbuser, $dbpass, $dbhost) or die('Could not connect: ' . mysql_error());
/* select the specific db */
mysql_select_db($dbname, $con);
/* insert the values into the db */
foreach($alldata as $data_array) {
$ip_address = $data_array['data']['payload'];
$vid_name = $data_array['data']['videoName'];
$date_time = $data_array['data']['dateTime'];
$time_zone = $data_array['data']['timeZone'];
$sql = "INSERT INTO ip_and_videos(IpAddress, VideoName, DateTime, Timezone) VALUES('".$ip_address."','".$vid_name."','".$date_time."','".$time_zone."')";
mysql_query($sql);
echo mysql_errno($con) . ": " . mysql_error($con) . "\n";
}
?>
Hope this helps
My code is working, but there is a NOTICE on the if satement while running. I tried to solve it, but I can't.
Notice error: Notice: Object of class PDOStatement could not be converted to int in D:\wamp\www\pdo\addOrders.php on line 30
here is my code:
<?php
$host = 'localhost';
$dbname = 'test';
$username = 'root';
$password = '';
try
{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
/* echo "Connected to $dbname at $host successfully.<br/>"; */
}
catch (PDOException $e)
{
echo "<h3>Error:</h3>". $e->getMessage();
}
$customer_id=addslashes($_GET['customer_id']);
$t=time();
$d=date("Y-m-d",$t);
$sql= "INSERT INTO `test`.`orders` (`customer_id`, `date`) VALUES ('$customer_id', '$d');";
$result =$conn->query($sql);
$lastid = $conn->lastInsertId();
if($result==1)
{
$query = "select * from `orders` where customer_id='$customer_id'";
$result = $conn->query($query);
$dbvalue = $result->fetch(PDO::FETCH_OBJ);
$customer_id=$dbvalue->customer_id;
$date=$dbvalue->date;
$details = array(
'status'=>'sucess',
'message'=>'customer added sucessfully',
'id' => $lastid,
'customer_id' => $customer_id,
'date' => $date,
);
echo json_encode($details);
}
else
{
$detail = array(
'status'=>'unsucess',
'message'=>'cannot add customer',
);
echo json_encode($detail);
}
?>
$conn->query($sql) returns either a PDOStatement object upon success, or false on failure. Comparing either to == 1 is nonsense. It was nonsense in the times of mysql_query, and is still nonsense in the times of PDO. You want to test the result for truthiness, not against a numeral.
It's as simple as:
if ($result)
<?php
require_once '/var/www/html/es/vendor/autoload.php';
class test {
//public $params = array();
public $mysql_con;
public $es_con;
public function __construct($es_username, $es_password, $server_name, $db_username, $db_password, $db_name) {
$params = array();
$params['connectionParams']['auth'] = array(
$es_username,
$es_password,
'Basic'
);
$es_con = new Elasticsearch\Client($params);
if ($es_con) {
$mysql_con = mysqli_connect($server_name, $db_username, $db_password, $db_name);
if (!$mysql_con) {
echo nl2br("Connected successfully to elasticsearch. Please check your credentials for database\n");
}
else {
echo nl2br("Connected successfully to both elasticsearch and database\n") ;
}
}
else {
echo nl2br("Failed to connect to elasticsearch. Please check your credentials\n");
}
}
public function insert() {
$insert_query = "INSERT INTO user (username,firstname,lastname,profile_about) VALUES ('shreyas','shreyas','r','Let us get out !!')";
$run_insert_query = mysqli_query($this->mysql_con, $insert_query);
if ($run_insert_query) {
$select_query = "SELECT * FROM user ORDER BY id DESC LIMIT 1";
$run_select_query = mysqli_query($this->mysql_con, $select_query);
while ($selected_row = mysqli_fetch_array($run_query)) {
$id = $selected_row['id'];
$username = $selected_row['username'];
$firstname = $selected_row['firstname'];
$lastname = $selected_row['lastname'];
$profile_about = $selected_row['profile_about'];
}
$es_insert = array();
$es_insert['body'] = array('id' => $id, 'username' => $username, 'firstname' => $firstname, 'lastname' => $lastname, 'profile_about' => $profile_about);
$es_insert['index'] = 'test';
$es_insert['type'] = 'jdbc';
$es_insert['id'] = $id;
$check_insert = $this->es_con->index($params);
if($check_insert) {
echo nl2br("Successfully inserted to both database and elasticsearch\n");
}
}
else {
echo nl2br("Failed to insert into database hence closing the connection\n");
}
}
}
$connection = new test('pavan', 'password', 'localhost', 'root', 'password', 'sample');
$connection->insert();
?>
I get the following error when I run the code -
mysqli_query() expects parameter 1 to be mysqli, null given in /var/www/html/es/combined.php on line 39
Can someone please help me debug this?I want to insert the data into database as well as elasticsearch.
You did not set $mysql_con to $this->mysql_con in your __construct. Which is why parameter 1 $this->mysql_con is null.
else {
echo nl2br("Connected successfully to both elasticsearch and database\n");
$this->mysql_con = $mysql_con; // Add this line
$this->es_con = $es_con; // After OP's comment, add this line too
}
I need to get username, password etc from the wp-config file to connect to a custom PDO database.
Currently I have another file where I have this info, but I would like to only use the wp-config.
So how can I read the different properties of wp-config?
I have even defined my own constants in in wp-config.php and managed to retrieve them in theme without any includes.
wp-config.php
define('DEFAULT_ACCESS', 'employee');
functions.php
echo "DEFAULT_ACCESS :".DEFAULT_ACCESS;
outputs DEFAULT_ACCESS :employee
Here's some same code.
// ...Call the database connection settings
require( path to /wp-config.php );
// ...Connect to WP database
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if ( !$dbc ) {
die( 'Not Connected: ' . mysql_error());
}
// Select the database
$db = mysql_select_db(DB_NAME);
if (!$db) {
echo "There is no database: " . $db;
}
// ...Formulate the query
$query = "
SELECT *
FROM `wp_posts`
WHERE `post_status` = 'publish'
AND `post_password` = ''
AND `post_type` = 'post'
";
// ...Perform the query
$result = mysql_query( $query );
// ...Check results of the query and terminate the script if invalid results
if ( !$result ) {
$message = '<p>Invalid query.</p>' . "\n";
$message .= '<p>Whole query: ' . $query ."</p> \n";
die ( $message );
}
// Init a variable for the number of rows of results
$num_rows = mysql_num_rows( $result );
// Print the number of posts
echo "$num_rows Posts";
// Free the resources associated with the result set
if ( $result ) {
mysql_free_result( $result );
mysql_close();
}
I would just include the file then I would have access to the variable in it varibales.
<?php
require_once('wp-config.php');
echo DB_NAME;
?>
This is assuming you're on the same server and you can access wp-config.php through the file system.
If you're doing this for a plugin, these values are already available. You won't need to include the file again.
You can get all the global constants from wp-config.php simply echo the const like that:
<?php
echo DB_HOST;
echo DB_NAME;
echo DB_USER;
echo DB_PASSWORD;
Here is a function to read all WP DB defines:
function get_wordpress_data() {
$content = #file_get_contents( '../wp-config.php' );
if( ! $content ) {
return false;
}
$params = [
'db_name' => "/define.+?'DB_NAME'.+?'(.*?)'.+/",
'db_user' => "/define.+?'DB_USER'.+?'(.*?)'.+/",
'db_password' => "/define.+?'DB_PASSWORD'.+?'(.*?)'.+/",
'db_host' => "/define.+?'DB_HOST'.+?'(.*?)'.+/",
'table_prefix' => "/\\\$table_prefix.+?'(.+?)'.+/",
];
$return = [];
foreach( $params as $key => $value ) {
$found = preg_match_all( $value, $content, $result );
if( $found ) {
$return[ $key ] = $result[ 1 ][ 0 ];
} else {
$return[ $key ] = false;
}
}
return $return;
}
this returns an array like this:
array (size=5)
'db_name' => string '.........'
'db_user' => string '.........'
'db_password' => string '.........'
'db_host' => string 'localhost'
'table_prefix' => string 'wp_'
If you want to connect to DB, for current versions of PHP, using mysqli extention is recommended (mysql extention is going to deprecate):
require_once ("../wp-config.php"); // path to wp-config depends on your file locatoin
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Just add required wp-load.php file.
you can use all wordpress functionality like
get_recent_posts() and many more...