How to use mysql_field_len in PHP 7? - php

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.).

Related

"Function name must be a string" on INSERT - mysqli PHP

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)

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.

Flattening a SQL query result for PHP array

I have a SQL table (modules) with two columns (id, name). Now I can retrieve the rows from this through a PHP script but what I want is to use the value of id as the key, and the value of name as the value, in a multidimensional array. Then I want to be able to encode those into a JSON, retaining the relationship between key/value. I've muddled something together but it returns null.
the relevant code from index.php
$mod1 = $core["module1"];
$mod2 = $core["module2"];
$modules = $db->getModulesById($mod1, $mod2); //module names & ids
$response["module"]["mod1"] = $modules[$mod1];
$response["module"]["mod2"] = $modules[$mod2];
$response["module"]["mod1name"] = $modules[$mod1]["name"];
$response["module"]["mod2name"] = $modules[$mod2]["name"];
echo json_encode($response);
The function from DB_Functions.php
public function getModulesById($mod1, $mod2) {
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());
$query = "SELECT * FROM modules WHERE id= '$mod1' OR id='$mod2'";
$result = mysqli_query($con, $query);
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
// process each row
//each element of $arr now holds an id and name
$arr[] = $row;
}
// return user details
return mysqli_fetch_array($arr);
close();
}
I've looked around but I'm just not 'getting' how the query return is then broken down into key/value for a new array. If someone could ELI5 I'd appreciate it. I'm just concerned with this aspect, it's a personal project so I'm not focusing on security issues as yet, thanks.
You are pretty well there
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if (!$con) {
die("Connection error: " . mysqli_connect_error());
}
$query = "SELECT * FROM modules WHERE id= '$mod1' OR id='$mod2'";
$result = mysqli_query($con, $query);
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
// here is wrong
//return mysqli_fetch_array($arr);
// instead return the array youy created
return $arr;
}
And call it and then just json_encode the returned array
$mod1 = $core["module1"];
$mod2 = $core["module2"];
$modules = $db->getModulesById($mod1, $mod2); //module names & ids
$response['modules'] = $modules;
echo json_encode($response);
You should really be using prepared and paramterised queries to avoid SQL Injection like this
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if (!$con) {
die("Connection error: " . mysqli_connect_error());
}
$sql = "SELECT * FROM modules WHERE id= ? OR id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param('ii', $mod1, $mod2);
$stmt->execute();
$result = $stmt->get_result();
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
// here is wrong
//return mysqli_fetch_array($arr);
// instead return the array youy created
return $arr;
}
mysqli_fetch_array requires the result of a mysqli_query result. Passing the constructed array to mysqli_fetch_array() is not going to work.
If you want to have a specific value from a row to use as its key, you can't resolve this with any mysqli_* function. You could however construct it yourself:
while($row = mysqli_fetch_assoc($result)) {
// process each row
//each element of $arr now holds an id and name
$arr[$row['id']] = $row;
}
mysqli_close($con);
return $arr;
You should close the connection before returning the result, code positioned after a return will not be executed.

Warning: mysqli_query(): Couldn't fetch mysqli in my code

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.

How to get a list of databases?

I was wondering if there's a way in PHP to list all available databases by usage of mysqli. The following works smooth in MySQL (see php docs):
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
}
Can I Change:
$db_list = mysql_list_dbs($link); // mysql
Into something like:
$db_list = mysqli_list_dbs($link); // mysqli
If this is not working, would it be possible to convert a created mysqli connection into a regular mysql and continue fetching/querying on the new converted connection?
It doesn't appear as though there's a function available to do this, but you can execute a show databases; query and the rows returned will be the databases available.
EXAMPLE:
Replace this:
$db_list = mysql_list_dbs($link); //mysql
With this:
$db_list = mysqli_query($link, "SHOW DATABASES"); //mysqli
I realize this is an old thread but, searching the 'net still doesn't seem to help. Here's my solution;
$sql="SHOW DATABASES";
$link = mysqli_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql: ' . mysqli_error($link).'\r\n');
if (!($result=mysqli_query($link,$sql))) {
printf("Error: %s\n", mysqli_error($link));
}
while( $row = mysqli_fetch_row( $result ) ){
if (($row[0]!="information_schema") && ($row[0]!="mysql")) {
echo $row[0]."\r\n";
}
}
Similar to Rick's answer, but this is the way to do it if you prefer to use mysqli in object-orientated fashion:
$mysqli = ... // This object is my equivalent of Rick's $link object.
$sql = "SHOW DATABASES";
$result = $mysqli->query($sql);
if ($result === false) {
throw new Exception("Could not execute query: " . $mysqli->error);
}
$db_names = array();
while($row = $result->fetch_array(MYSQLI_NUM)) { // for each row of the resultset
$db_names[] = $row[0]; // Add db name to $db_names array
}
echo "Database names: " . PHP_EOL . print_r($db_names, TRUE); // display array
Here is a complete and extended solution for the answer, there are some databases that you do not need to read because those databases are system databases and we do not want them to appear on our result set, these system databases differ by the setup you have in your SQL so this solution will help in any kind of situations.
first you have to make database connection in OOP
//error reporting Procedural way
//mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//error reporting OOP way
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL & MYSQLI_REPORT_STRICT;
$conn = new mysqli("localhost","root","kasun12345");
using Index array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_NUM)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row[0] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row[0];
}
}
same with Assoc array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row["Database"] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row["Database"];
}
}
same using object of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($obj = $result->fetch_object()){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if( $obj->Database == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'. $obj->Database;
}
}

Categories