Not able to insert into database - php

<?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
}

Related

How can I connect mssql server and get values with php

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"}
]
}

SQL connection dies after one call

I have a custom class that takes a sql connection as a parameter. I use that to populate the class, and then I'm trying to use it again to modify the results on screen. But after the first use, I can't use it anymore.
connection.php:
$conn = new mysqli('localhost', 'root', '', 'loveConnections');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
personalityProfile.php (front end)
if (!isset($_SESSION['interests'])) {
$interests = new Interests($conn, $_SESSION['id']);
$_SESSION['interests'] = $interests;
} else {
$interests = $_SESSION['interests'];
}
interestsObject.php
class Interests {
// properties
public $conn;
public $id;
public $interestsArray = [];
public function __construct($conn, $memberId = null, $intArray = [
'basketball' => false,
'bowling' => false,
'movies' => false,
]) {
$this->conn = $conn;
$this->id = $memberId;
$this->interestsArray = $intArray;
$this->popArraySql();
}
public function popArraySql() {
$memInterests = [];
$sql = "SELECT i.interest
FROM memberInfo m
Join MemberInterestLink mi on (mi.memberID_FK = m.memberID_PK)
Join interests i on (mi.interestID_FK = i.interestID_PK)
WHERE memberID_PK = $this->id";
$result = $this->conn->query($sql);
$this->conn works perfectly here
foreach ($result as $row) {
array_push($memInterests, $row['interest']);
}
foreach ($this->interestsArray as $key => $value) {
for ($i=0; $i<sizeof($memInterests); $i++) {
if ($memInterests[$i] === $key) {
$this->interestsArray[$key] = true;
}
}
}
}
public function insertUpdateQuery() {
var_dump($this->conn);
foreach ($this->interestsArray as $key => $val) {
echo $key . "<br>";
$select = "SELECT interestID_PK from interests where interest = '" . $key . "'";
echo $select;
$result = $this->conn->query($select);
when I try and use it later though, I get a Warning: mysqli::query(): Couldn't fetch mysqli. Additionally, if I try and var_dump it, I get Warning: var_dump(): Property access is not allowed yet
var_dump($result);
if ($val === true) {
$insert = "INSERT INTO MemberInterestLink (memberID_FK, interestID_FK) VALUES ($this->id, $interestKey)";
$this->conn->query($insert);
} else {
$delete = "DELETE FROM MemberInterestLink WHERE interestID_FK = $interestKey";
$this->conn->query($delete);
}
}
}
}
I never close the connection, which is what most of the related answers suggested the cause may be. It's like my $conn variable just stops working after the first use.

Passing PHP array as parameter for SQL WHERE clause

Adapting an answer from here to try and pass an array as the parameter for a WHERE clause in MySQL. Syntax seems okay but I'm just getting null back form the corresponding JSON. I think understand what it is supposed to do, but not enough that I can work out where it could be going wrong. The code for the function is;
public function getTheseModulesById($moduleids) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_error());
}
// selecting database
mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());
$in = join(',', array_fill(0, count($moduleids), '?'));
$select = "SELECT * FROM modules WHERE id IN ($in)";
$statement = $con->prepare($select);
$statement->bind_param(str_repeat('i', count($moduleids)), ...$moduleids);
$statement->execute();
$result = $statement->get_result();
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
mysqli_close($con);
return $arr;
}
And the code outwith the function calling it looks like;
$id = $_POST['id'];
$player = $db->getPlayerDetails($id);
if ($player != false) {
$pid = $player["id"];
$moduleids = $db->getModulesByPlayerId($pid); //this one is okay
$modules = $db->getTheseModulesById($moduleids); //problem here
$response["player"]["id"] = $pid;
$response["player"]["fname"] = $player["fname"];
$response["player"]["sname"] = $player["sname"];
$response["modules"] = $modules;
echo json_encode($response);
[EDIT]
I should say, the moduleids are strings.

PDO Insert query in table in another database not working

I want to make a sendmail function on my program. But first, I want to store the information: send_to, subject, and message in a table in another database(mes) where automail is performed. The problem is data fetched from another database(pqap) are not being added on the table(email_queue) in database(mes).
In this code, I have a table where all databases in the server are stored. I made a query to select a specific database.
$sql5 = "SELECT pl.database, pl.name FROM product_line pl WHERE visible = 1 AND name='PQ AP'";
$dbh = db_connect("mes");
$stmt5 = $dbh->prepare($sql5);
$stmt5->execute();
$data = $stmt5->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
Then after selecting the database,it has a query for selecting the information in the table on the selected database. Here's the code.
foreach ($data as $row5) GenerateEmail($row5['database'], $row5['name']);
Then this is part (I think) is not working. I don't know what's the problem.
function GenerateEmail($database, $line) {
$sql6 = "SELECT * FROM invalid_invoice WHERE ID=:id6";
$dbh = db_connect($database);
$stmt6 = $dbh->prepare($sql6);
$stmt6->bindParam(':id6', $_POST['idtxt'], PDO::PARAM_INT);
$stmt6->execute();
$data = $stmt6->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
foreach ($data as $row6) {
$invnumb=$row6['Invoice_Number'];
$partnumb=$row6['Part_Number'];
$issue=$row6['Issues'];
$pic=$row6['PIC_Comments'];
$emailadd= $row6['PersoninCharge'];
if($row6['Status']=="Open") {
$message = "<html><b>Invoice Number: {$invnumb}.</b><br><br>";
$message .= "<b>Part Number:</b><br><xmp>{$partnumb}</xmp><br><br>";
$message .= "<b>Issues:</b><br><xmp>{$issue}</xmp><br>";
$message .= "<b>{$pic}<b><br>";
$message .= "</html>";
if(!empty($emailadd)) {
dbInsertEmailMessage($emailadd, "Invoice Number: {$invnumb} - {$issue}.", $message);
$dbh=null;
}
}
}
}
function dbInsertEmailMessage($send_to, $subject, $message) {
$sql7 = "INSERT INTO email_queue (Send_to, Subject, Message) VALUES (:send_to, :subject, :message)";
$dbh = db_connect("mes");
$stmt7 = $dbh->prepare($sql7);
$stmt7->bindParam(':send_to', $send_to, PDO::PARAM_STR);
$stmt7->bindParam(':subject', $subject, PDO::PARAM_STR);
$stmt7->bindParam(':message', $message, PDO::PARAM_STR);
$stmt7->execute();
$dbh=null;
}
Here's my db connection:
function db_connect($DATABASE) {
session_start();
// Connection data (server_address, database, username, password)
$servername = '*****';
//$namedb = '****';
$userdb = '*****';
$passdb = '*****';
// Display message if successfully connect, otherwise retains and outputs the potential error
try {
$dbh = new PDO("mysql:host=$servername; dbname=$DATABASE", $userdb, $passdb, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
return $dbh;
//echo 'Connected to database';
}
catch(PDOException $e) {
echo $e->getMessage();
}
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
There are a couple things that may help with your failed inserts. See if this is what you are looking for, I have notated important points to consider:
<?php
// take session_start() out of your database connection function
// it draws an error when you call it more than once
session_start();
// Create a connection class
class DBConnect
{
public function connect($settings = false)
{
$host = (!empty($settings['host']))? $settings['host'] : false;
$username = (!empty($settings['username']))? $settings['username'] : false;
$password = (!empty($settings['password']))? $settings['password'] : false;
$database = (!empty($settings['database']))? $settings['database'] : false;
try {
$dbh = new PDO("mysql:host=$host; dbname=$database", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// You return the connection before it hits that setting
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
catch(PDOException $e) {
// Only return the error if an admin is logged in
// you may reveal too much about your database on failure
return false;
//echo $e->getMessage();
}
}
}
// Make a specific connection selector
// Put in your database credentials for all your connections
function use_db($database = false)
{
$con = new DBConnect();
if($database == 'mes')
return $con->connect(array("database"=>"db1","username"=>"u1","password"=>"p1","host"=>"localhost"));
else
return $con->connect(array("database"=>"db2","username"=>"u2","password"=>"p2","host"=>"localhost"));
}
// Create a query class to return selects
function query($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return (!empty($result))? $result:0;
}
// Create a write function that will write to database
function write($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
}
// Do not create connections in your function(s), rather pass them into the functions
// so you can use the same db in and out of functions
// Also do not null the connections out
function GenerateEmail($con,$conMes,$line = false)
{
if(empty($_POST['idtxt']) || (!empty($_POST['idtxt']) && !is_numeric($_POST['idtxt'])))
return false;
$data = query($con,"SELECT * FROM `invalid_invoice` WHERE `ID` = :0", array($_POST['idtxt']));
if($data == 0)
return false;
// Instead of creating a bunch of inserts, instead create an array
// to build multiple rows, then insert only once
$i = 0;
foreach ($data as $row) {
$invnumb = $row['Invoice_Number'];
$partnumb = $row['Part_Number'];
$issue = $row['Issues'];
$pic = $row['PIC_Comments'];
$emailadd = $row['PersoninCharge'];
if($row['Status']=="Open") {
ob_start();
?><html>
<b>Invoice Number: <?php echo $invnumb;?></b><br><br>
<b>Part Number:</b><br><xmp><?php echo $partnumb; ?></xmp><br><br>
<b>Issues:</b><br><xmp><?php echo $issue; ?></xmp><br>
<b><?php echo $pic; ?><b><br>
</html>
<?php
$message = ob_get_contents();
ob_end_clean();
if(!empty($emailadd)) {
$bind["{$i}to"] = $emailadd;
$bind["{$i}subj"] = "Invoice Number: {$invnumb} - {$issue}.";
$bind["{$i}msg"] = htmlspecialchars($message,ENT_QUOTES);
$sql[] = "(:{$i}to, :{$i}subj, :{$i}msg)";
}
}
$i++;
}
if(!empty($sql))
return dbInsertEmailMessage($conMes,$sql,$bind);
return false;
}
function dbInsertEmailMessage($con,$sql_array,$bind)
{
if(!is_array($sql_array))
return false;
write($con,"INSERT INTO `email_queue` (`Send_to`, `Subject`, `Message`) VALUES ".implode(", ",$sql_array),$bind);
return true;
}
// Create connections
$con = use_db();
$conMes = use_db('mes');
GenerateEmail($con,$conMes);

Handling results from MySQLi query after MySql to MySqli conversion

I am trying to change the following code to use MySqli instead of MySql. I have removed some methods that seem unimportant to what I'm addressing here.
class db {
var $hostname,
$database,
$username,
$password,
$connection,
$last_query,
$last_i,
$last_resource,
$last_error;
function db($hostname=DB_HOSTNAME,$database=DB_DATABASE,$username=DB_USERNAME,$password=DB_PASSWORD) {
$this->hostname = $hostname;
$this->database = $database;
$this->username = $username;
$this->password = $password;
$this->connection = mysql_connect($this->hostname,$this->username,$this->password) or $this->choke("Can't connect to database");
if($this->database) $this->database($this->database);
}
function database($database) {
$this->database = $database;
mysql_select_db($this->database,$this->connection);
}
function query($query,$flag = DB_DEFAULT_FLAG) {
$this->last_query = $query;
$resource = mysql_query($query,$this->connection) or $this->choke();
list($command,$other) = preg_split("|\s+|", $query, 2);
// Load return according to query type...
switch(strtolower($command)) {
case("select"):
case("describe"):
case("desc"):
case("show"):
$return = array();
while($data = $this->resource_get($resource,$flag)) $return[] = $data;
//print_r($return);
break;
case("replace"):
case("insert"):
if($return = mysql_insert_id($this->connection))
$this->last_i = $return;
break;
default:
$return = mysql_affected_rows($this->connection);
}
return $return;
}
function resource_get($resource = NULL,$flag = DB_DEFAULT_FLAG) {
if(!$resource) $resource = $this->last_resource;
return mysql_fetch_array($resource,$flag);
}
}
This is what I've got so far:
class db {
var $hostname = DB_HOSTNAME,
$database = DB_DATABASE,
$username = DB_USERNAME,
$password = DB_PASSWORD,
$connection,
$last_query,
$last_i,
$last_resource,
$last_error;
function db($hostname, $database, $username, $password) {
$this->hostname = $hostname;
$this->database = $database;
$this->username = $username;
$this->password = $password;
$this->connection = new mysqli($this->hostname, $this->username, $this->password, $this->database) or $this->choke("Can't connect to database");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if($this->database)
$this->database($this->database);
}
function database($database) {
$this->database = $database;
mysqli_select_db($this->connection, $this->database );
}
function query($query, $flag = DB_DEFAULT_FLAG) {
$this->last_query = $query;
//print_r($query);
$result = mysqli_query($this->connection, $query) or $this->choke("problem connecting to DB");
while($row=mysqli_fetch_assoc($result)) {
$resource[]=$row;
}
//print($command);
//print_r($resource);print("<br>");
list($command, $other) = preg_split("|\s+|", $query, 2);
// Load return according to query type...
switch(strtolower($command)) {
case("select"):
case("describe"):
case("desc"):
case("show"):
$return = array();
while($data = $this->resource_get($resource, $flag))
$return[] = $data;
//print_r($return);
break;
case("replace"):
case("insert"):
if($return = mysqli_insert_id($this->connection))
$this->last_i = $return;
break;
default:
$return = mysqli_affected_rows($this->connection);
}
return $return;
}
function resource_get($resource = NULL, $flag = DB_DEFAULT_FLAG) {
if(!$resource)
$resource = $this->last_resource;
return mysqli_fetch_array($resource, $flag);
}
So here's the problem: I've checked the results with a print_r() and the $resource array is loading correctly, but the value of $return when checked with print_r() just ends up being "Array()". Therefore, as near as I can figure, something isn't being handled correctly in this part of the code, which is why I included the resource_get() function call:
$return = array();
while($data = $this->resource_get($resource, $flag))
$return[] = $data;
//print_r($return);
break;
If I use mysqli_fetch_row($resource, $flag) instead of mysqli_fetch_array($resource, $flag) I still get the same result, i.e. print_r($return) yields simply "Array()".
The variable $resource does not represent a mysqli_result resource object at the time you pass it into $this->resource_get(). Instead, it is already a 2D array of results since you previously ran a mysqli_fetch_assoc() loop.
To make this work with your current code, you may either remove the earlier fetch loop:
$result = mysqli_query($this->connection, $query) or $this->choke("problem connecting to DB");
// Remove this
//while($row=mysqli_fetch_assoc($result)) {
// $resource[]=$row;
//}
And later, pass $result instead of $resource into your resource_get() method since it is $result that is the resource object.
Or, you might just skip the resource_get() call entirely and return $resource directly since it already contains the result array.

Categories