I know this question has been asked many times , I tried lot of other answers but it didn't work for me
Here is my class
<?php
class saveexceltodb
{
var $inputFileName;
var $tableName;
var $conn;
var $allDataInSheet;
var $arrayCount;
/**
* Create a new PHPExcel with one Worksheet
*/
public function __construct($table=0)
{
$this->initiatedb();
}
private function initiatedb(){
//var_dump($allDataInSheet);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyx";
// Create connection
$this->conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$this->conn) {
die("Connection failed: " . mysqli_connect_error());
}
}
public function updateIntermidiate(){
$allocationeventwise=array();
mysqli_query($this->conn,"DELETE FROM `allocationeventwise` WHERE 1");
$sql = "INSERT INTO `allocationeventwise` (`empid`, `event1`, `event2`, `event3`, `event4`, `event5` `event6`, `event7`) VALUES ";
$result = mysqli_query($this->conn, "SELECT usdeal.empid , usdeal.event1 , usdeal.event2, usdeal.event3, usdeal.event4, usdeal.event5, usdeal.event6, usdeal.event7 , salary.salary from usdeal INNER JOIN salary ON usdeal.empid = salary.empid where usdeal.allocated=0");
$i=0;
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$i++;
$totaleventDays = $row["event1"]+$row["event2"]+$row["event3"]+$row["event4"]+$row["event5"]+$row["event6"]+$row["event7"];
$allocationeventwise[$row["empid"]]['event1']=($row['salary']/$totaleventDays)*$row["event1"];
$allocationeventwise[$row["empid"]]['event2']=($row['salary']/$totaleventDays)*$row["event2"];
$allocationeventwise[$row["empid"]]['event3']=($row['salary']/$totaleventDays)*$row["event3"];
$allocationeventwise[$row["empid"]]['event4']=($row['salary']/$totaleventDays)*$row["event4"];
$allocationeventwise[$row["empid"]]['event5']=($row['salary']/$totaleventDays)*$row["event5"];
$allocationeventwise[$row["empid"]]['event6']=($row['salary']/$totaleventDays)*$row["event6"];
$allocationeventwise[$row["empid"]]['event7']=($row['salary']/$totaleventDays)*$row["event7"];
$sql .='("'.$row["empid"].'",
'.$allocationeventwise[$row["empid"]]["event1"].',
'.$allocationeventwise[$row["empid"]]["event2"].',
'.$allocationeventwise[$row["empid"]]["event3"].',
'.$allocationeventwise[$row["empid"]]["event4"].',
'.$allocationeventwise[$row["empid"]]["event5"].',
'.$allocationeventwise[$row["empid"]]["event6"].',
'.$allocationeventwise[$row["empid"]]["event7"].',)';
if($i<mysqli_num_rows($result))
$sql .=",";
else
$sql .=";";
}
echo $sql;
if (mysqli_query($this->conn, $sql)) {
echo "New record created successfully<br/>";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($this->conn);
}
} else {
echo "0 results";
}
}
}
When I use it like this
include('saveexceltodb.php');
$obj = new saveexceltodb(0);
$obj->updateIntermidiate();
I get following error .
Warning: mysqli_query(): Couldn't fetch mysqli in C:\xampp\htdocs\import-excel\saveexceltodb.php
You should follow below steps
Check database connection
Check query syntax
You have to pass connection object in mysqli_query function in you case it is ' $this->conn '
Hope, It may help you.
Related
Hello every body is it possible to pass an array containing some data to a function and put this array of data in a WHERE condition of a mysql query?
Please, take a look to my code if it's correct. Anyway it is not working at the moment, it prints "No results" ...
public function target_query($ids_array){
include_once 'connection.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$ids = join("','",$ids_array);
$sql = "SELECT codice_target FROM customer WHERE id_customer IN ('$ids')";
$result = $conn->query($sql);
$arraytoclass = array();
if ($result->num_rows > 0) {
// output data of each row
//echo "tutto ok";
while($row = $result->fetch_row()) {
//echo "Codice target: " . $row["codice_target"]."<br>";
$arraytoclass[] = $row;
//echo "codice target:".$arraytoclass[$i]['codice_target'];
}
//print_r($arraytoclass);
return $arraytoclass;
//print_r($arraytoclass);
} else {
echo "NO results";
}
return $arraytoclass;
$conn->close();
}
The result of the query will be passed inside another function here below:
public function fputToFile($file, $allexportfields, $object, $ae)
{
if($allexportfields && $file && $object && $ae)
{
//one ready for export product
$readyForExport = array();
//put in correct sort order
foreach ($allexportfields as $value)
{
$object = $this->processDecimalSettings($object, $ae, $value);
$readyForExport[$value] = iconv("UTF-8", $ae->charset, $object[$value]);
}
$arraytoclass = $this->target_query($readyForExport['id_customer']);
print_r ($arraytoclass);
// and so on...
// and so on...
Many thanks in advance.
I have puzzled over this for some time. It is puzzling because a very similar query just a few lines above works fine. I am very new to mysqli, so there may be something very fundamental I am missing.
The connection is set up like this:
Class dbObj{
/* Database connection start */
var $servername = "myserver";
var $username = "myusername";
var $password = "mypassword";
var $dbname = "mydb";
var $conn;
function getConnstring() {
$con = mysqli_connect($this->servername, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error());
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$this->conn = $con;
}
return $this->conn;
}
}
Then, in an Ajax processing file:
include_once({the connection file above});
$db = new dbObj();
$connString = $db->getConnstring();
$params = $_REQUEST;
$action = isset($params['action']) != '' ? $params['action'] : '';
$NeedsCls = new Needs($connString);
Then, inside a class called "Needs":
protected $conn;
protected $data = array();
function __construct($connString)
{
$this->conn = $connString;
}
function insertNeeds($params)
{
$ExpDate = $params[Expire];
$sql = "INSERT INTO `pNeeds` (PubCode, Title, Description, Keywords, Expire) VALUES('".$_SESSION["PubCode"]."','".$params["Title"]."','".$params["Description"]."','".$params[NeedsTags]."','".$ExpDate."'); ";
echo $result = mysqli_query($this->conn, $sql) or die("Error - Failed inserting Needs data");
$Record = $db->insert_id;
$KW = explode(';',$params[NeedsTags]);
$KWCount = count($KW);
for($x=0;$x<$KWCount;$x++)
{
$Keyword = $KW[$x];
$sql = "INSERT INTO `Keywords` (Keyword, PubCode, Table, Record, Expire) VALUES ('".$Keyword."','".$_SESSION["PubCode"]."','pNeeds','".$Record."','".$ExpDate."'); ";
echo $result = mysqli_query($this->conn,$sql) or die("Error - Keywords not saved<br />".$mysqli_error());
}
}
The first query works fine. The second fails with the error "Function name must be a string". I've verified the data going into the Ajax code is correct. It doesn't appear that I am missing something stupid. (famous last words) The error message makes no sense to me. Similar posts here on StackOverflow and elsewhere do not seem to pertain in this instance.
It looks like you're just grabbing $params wrong:
$ExpDate = $params[Expire];
$params[NeedsTags];
Should be:
$ExpDate = $params['Expire'];
$params['NeedsTags'];
Edit
You're actual error is from:
$mysqli_error()
Remove the $
Edit
RationalRabbit: To avoid confusing anyone, I should mention that the whole syntax was wrong. Using object oriented mysqli, the error syntax should have been
db->error
OR
mysqli($this->conn)
I'm new with PHP 7 and updating the code into PHP 7. I got error below when trying to get length as mysql_field_len() as it is not exist in mysqli, so how to solved this?
My problem is in this line >>> $panjang = mysql_field_len($query,0);
Warning: mysql_field_len() expects parameter 1 to be resource, object
given in
function WriteCode($tabel, $inisial){
$server = "localhost";
$username = "user_db";
$password = "password_db";
$database = "name_db";
$connection = mysqli_connect($server,$username,$password);
if (!$connection) {
die("Database connection failed: " . mysqli_error($connection));
}
$db_select = mysqli_select_db($connection, $database);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
$query = mysqli_query($connection,"SELECT * FROM $tabel");
$panjang = mysql_field_len($query,0);
$qry = mysqli_query($connection,"SELECT MAX('.$property.') FROM ".$tabel);
if (!$qry) {
printf("Error: %s\n", mysqli_error($connection));
exit();
}
$row = mysqli_fetch_array($qry, MYSQLI_NUM);
if ($row[0]=="") {
$angka=0;
}
else {
$angka = substr($row[0], strlen($inisial));
}
$angka++;
$angka =strval($angka);
$tmp ="";
for($i=1; $i<=($panjang-strlen($inisial)-strlen($angka)); $i++) {
$tmp=$tmp."0";
}
return $inisial.$tmp.$angka;
Thank You
Since mysql_field_len is removed in PHP 7, try the alternatives, mentioned in the docs: http://php.net/manual/en/function.mysql-field-len.php
If you want the same named function, try to implement this one:
function mysqli_field_len($result, $field_offset) {
$properties = mysqli_fetch_field_direct($result, $field_offset);
return is_object($properties) ? $properties->length : null;
}
There are some other functions it's worth to investigate, such as mysql_fetch_lengths (to get an array with length of all fields in a result) or mysqli_fetch_fields and PDOStatement::getColumnMeta (which return fully detailed description, including table name, field name, type, length, etc.).
I am new to the idea of oop php and i am trying to write an irc php.
What I'm trying to do:
I am trying to query my database, get results from my database and put it into an array inside my program.
I tried making a new function to carry out the task and called it in the __construct function.
I have shortened the code but it pretty much looks like this:
Any thoughts and ideas are much appreciated.
class IRCBot
{
public $array = array();
public $servername = "localhost";
public $username = "root";
public $password = "usbw";
public $dbname = "bot";
function __construct()
{
//create new instance of mysql connection
$conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$this->database_fetch();
}
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($query);
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row();
}
}
function main()
{
print_r($array);
}
}
$bot = new IRCBot();
Changes
1) Change if ($mysqli->connect_errno) to if ($conn->connect_errno)
2) Change $array[] = $row(); to $array[] = $row;
3) Add return $array; in function database_fetch()
4) Call database_fetch() function inside main() function instead of constructor.
5) Add $this->conn in mysqli_query() (Thanks #devpro for pointing out.)
Updated Code
<?php
class IRCBot
{
public $array = array();
public $servername = "localhost";
public $username = "root";
public $password = "usbw";
public $dbname = "bot";
public $conn;
function __construct()
{
//create new instance of mysql connection
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_errno)
{
echo "Failed to connect to MySQL: (" . $this->conn->connect_errno . ") " . $this->conn->connect_error;
}
}
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($this->conn,$query);
while($row = mysqli_fetch_assoc($result)){
$array[] = $row;
}
return $array;
}
function main()
{
$data = $this->database_fetch();
print_r($data);
}
}
Quick Start
Object Oriented Programming in PHP
Classes and Objects
Principles Of Object Oriented Programming in PHP
First of all you need to fix error from your constructor, you can modify as:
function __construct()
{
//create new instance of mysql connection
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_errno)
{
echo "Failed to connect to MySQL: (" . $this->conn->connect_errno . ") " . $this->conn->connect_error;
}
echo $this->conn->host_info . "\n";
}
Here, you need to replace $mysqli with $conn because your link identifier is $conn not $mysqli
No need to call database_fetch() here.
You need to use $conn as a property.
Now you need to modify database_fetch() method as:
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($this->conn,$query);
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
return $array;
}
Here, you need to pass add first param in mysqli_query() which should be link identifier / database connection.
Second, you need to use return for getting result from this function.
In last, you need to modify your main() method as:
function main()
{
$data = $this->database_fetch();
print_r($data);
}
Here, you need to call database_fetch() method here and than print the data where you need.
When I'm using mysqli without class it's going ok:
index.php
require_once(dirname(__FILE__) . '/config.php');
$mysqli = new mysqli($hostname, $username, $password, $dbname);
$queryText = "SELECT * FROM User";
if($query = $mysqli->query($queryText)) {
$results = $query->fetch_array();
echo $results['userId'];
} else {
echo "Error ";
echo $mysqli->errno . " " . $this->mysqli->error;
}
?>
But when I start using mysqli with class something goes wrong. connectDB doesn't give any error, so i get connected to DB. But then when trying do any query it give me "No database selected error"
Result of index.php is: Error 1046 No database selected
index.php
<?php
require_once(dirname(__FILE__) . '/banana.php');
$banana = new Banana(1);
if ($banana->connectDB()) {
$banana->doQuery();
}
?>
banana.php
<?php
require_once(dirname(__FILE__) . '/config.php');
class Banana {
private $mysqli, $userId, $query;
function __construct($userId) {
$this->userId = $userId;
}
function __destruct() {
$this->mysqli->close();
}
public function connectDB() { // Подключение к БД
$this->mysqli = new mysqli($hostname, $username, $password, $dbname);
if ($this->mysqli->connect_errno) {
echo "Error (" . $this->mysqli->connect_errno . ") " . $this->mysqli->connect_error;
return false;
}
return true;
}
public function doQuery() {
$queryText = "SELECT * FROM User";
if($this->query = $this->mysqli->query($queryText)) {
$results = $query->fetch_array();
echo $results['userId'];
} else {
echo "Error ";
echo $this->mysqli->errno . " " . $this->mysqli->error;
}
}
?>
So it's very frustrating. I'm about 2 weeks in php, but can't find answer for couple days. I guess the answer is obvious but I can't see it.
Thank you for your time and patience.
One of the first problems you will encounter when you run your script is here:
public function connectDB() { // Подключение к БД
$this->mysqli = new mysqli($hostname, $username, $password, $dbname);
Note that all 4 variables you are using in your function call ($hostname, etc.) are undefined in the scope of the method.
There are several ways you can solve this:
Pass the variables as parameters to the method:public function connectDB($hostname, ...
Pass the necessary variable to your class constructor and set configuration properties in your class that you can use later on;
Use constants instead of variables;
Declare your variables global.
I would recommend one of the first 2 and definitely not the last one.
You can read more in the php manual about variable scope.
It looks like you are a copy'n'paste victim. In doQuery() change:
if($this->query = $this->mysqli->query($queryText)) {
$results = $query->fetch_array();
To:
if($this->query = $this->mysqli->query($queryText)) {
$results = $this->query->fetch_array();