I wrote an global function that getting array with keys and values, and inserting it to mysql db. something like this:
function insert_to_db($table, $data, $is_using_id) {
// I'm connecting to db before this code.
global $mysqli;
// .. Checking for errors ..
// .. if using id, remove the id from the values like this:
$columns = array_keys($data);
$values = array_values($data);
if ($is_using_id == true) {
unset($values[0]);
// Reorder the array after unset()
$values = array_merge($values);
}
// ..
// Generating text for use at the mysqli::prepare
$columns_text = "";
$i = 0;
while ($i < count($columns)) {
$column = $columns[$i];
if ($i == 0) {
$columns_text = $column;
} else {
$columns_text = $columns_text.", ".$column;
}
$i++;
}
unset($i);
unset($column);
$values_text = "";
// b_p_f is the $types string for mysqli-stmt::bind_param
$b_p_f = "";
// Generating text for use at the mysqli::prepare
$i = -1;
while ($i < count($values)) {
echo "\$i equals to {$i}<br>";
if ($is_using_id == true && $i == -1) {
// Null because id is calculated automatically by mysql
$values_text = "NULL";
} else if ($is_using_id == false && $i == 0) {
$value = $values[$i];
$values_text = "?";
if (is_numeric($value))
{
$b_p_f = 'i';
} else {
$b_p_f = 's';
}
} else {
$value = $values[$i];
$values_text = $values_text.", ?";
if (is_numeric($value))
{
echo "Value: {$value} Found as numberic<br>";
$b_p_f = $b_p_f.'i';
} else {
echo "Value: {$value} Found as non-numberic<br>";
$b_p_f = $b_p_f.'s';
}
}
$i++;
}
unset($i);
unset($value);
echo "b_p_f:";
var_dump($b_p_f);
echo " values:";
var_dump($values);
$stmt = $mysqli->prepare("INSERT INTO ".$table." (".$columns_text.") VALUES (".$values_text.")");
if (!$stmt) {
return array("error"=>"true", "error_mysqli"=>$mysqli->error, "MORE"=>"INSERT INTO ".$table." (".$columns_text.") VALUES (".$values_text.")");
}
$stmt->bind_param($b_p_f, $values);
if ($stmt->execute()) {
return array("error"=>"false", "inserted_id"=>$mysqli->insert_id);
} else {
return array("error"=>"true", "error_stmt"=>$stmt->error, "MORE"=>"INSERT INTO ".$table." (".$columns_text.") VALUES (".$values_text.")");
}
}
Then I am calling to the function:
function hash_password($password) {
$options = [ 'cost' => 12 ];
return password_hash($password, PASSWORD_BCRYPT,$options);
}
$data = array(
"ID" => NULL,
"first_name" => "Alexander",
"last_name" => "Margolis",
"email" => "shay24590#gmail.com",
"username" => "smartDonkey",
"password" => "Incorrect",
"birthday" => "12-12",
"date_added" => time(),
"total_points" => 0,
"cafe_added" => 0,
"review_placed"=> 0);
$data["password"] = hash_password($data["password"]);
var_dump ( insert_to_db("user", $data, true) );
And I see on the screen
array(3) {
["error"]=> string(4) "true"
["error_stmt"]=> string(53) "No data supplied for parameters in prepared statement" ["MORE"]=> string(178) "..."
}
Why am I getting this? What is the problem?
Also, If I pass the value instead of ? to the mysql::prepare, it works! So - it means that the problem is with mysqli stmt bind_param..
I know that this question similar to others, but I didn't found one that helps my problem. and sorry for my english and for the long function. thank you!
I've moved to PDO, and instead of calling $stmt->bind_param($b_p_f, $values); you can call $pdo_stmt->execute($values) where $values is an Array.
Related
I have an issue with my INSERT query, $pdo->execute return false, with error code 00000
Query
string 'INSERT INTO module_test (img_name, description, priority) VALUES(:img_name, :description, :priority)' (length=100)
errorInfo() return:
array (size=3)
0 => string '00000' (length=5)
1 => null
2 => null
Code:
private function Init($query, $parameters = "")
{
# Connect to database
if (!$this->bConnected) {
$this->Connect();
}
try {
# Prepare query
$this->sQuery = $this->pdo->prepare($query);
# Add parameters to the parameter array
$this->bindMore($parameters);
# Bind parameters
if (!empty($this->parameters)) {
foreach ($this->parameters as $param => $value) {
$type = PDO::PARAM_STR;
switch ($value[1]) {
case is_int($value[1]):
$type = PDO::PARAM_INT;
break;
case is_bool($value[1]):
$type = PDO::PARAM_BOOL;
break;
case is_null($value[1]):
$type = PDO::PARAM_NULL;
break;
}
// Add type when binding the values to the column
$this->sQuery->bindValue($value[0], $value[1], $type);
}
}
# Execute SQL
var_dump($query);
var_dump($this->sQuery->execute());
var_dump($this->sQuery->errorInfo());
}
catch (PDOException $e) {
# Write into log and display Exception
echo $this->ExceptionLog($e->getMessage(), $query);
die();
}
# Reset the parameters
$this->parameters = array();
}
public function query($query, $params = null, $fetchmode = PDO::FETCH_ASSOC)
{
$query = trim(str_replace("\r", " ", $query));
$this->Init($query, $params);
$rawStatement = explode(" ", preg_replace("/\s+|\t+|\n+/", " ", $query));
# Which SQL statement is used
$statement = strtolower($rawStatement[0]);
if ($statement === 'select' || $statement === 'show') {
return $this->sQuery->fetchAll($fetchmode);
} elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') {
return $this->sQuery->rowCount();
} else {
return NULL;
}
}
public function insert($table, $keyValue)
{
$fieldString = '';
$valueString = '';
$i = 1;
foreach ($keyValue as $key => $currKeyValue)
{
$fieldString .= $key;
$valueString .= ':'.$key;
if($i != count($keyValue))
{
$fieldString .= ', ';
$valueString .= ', ';
}
$i++;
}
$query = 'INSERT INTO '.$table.' ('.$fieldString.') VALUES('.$valueString.')';
$this->query($query, $keyValue);
}
Parameters array
F:\Dev\wamp\wamp64\www\include\class\Database.class.php:216:
array (size=3)
'img_name' => string 'ttt1' (length=4)
'description' => string 'ttt1' (length=4)
'priority' => int 0
I already try this query in phpmyadmin and everything worked well.
If someone know how to solve this?
thanks
PS: sorry for my bad english
PDO is reported not to fill the errorInfo property in certain circumstances.
Instead, you have to make it throw an exception, which is the most reliable way to get the error message. To do so, in your constructor, add this line
$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
Also note that your class is a genuine example of all the mistakes one could make writing a PDO wrapper. I compiled the most popular mistakes in an article, Your first database wrapper's childhood diseases and your class contains every single one of them.
i am working on my own restfull api. I have read many article about, but i come out more confused that before.
fist question:
in PUT request is correct to use question mark (?) ex:
http://myapi.me/testApi/v5/create/places?address=Five&building=old
or i must to use
http://myapi.me/testApi/v5/create/places/address=Five&building=old
if the second is the correct way, how i can explode the query string for create my insert statement? my code work well with (?). But curl command does not want to enter the record. So i need to modify the script to reflect the correct way with(/) instead of (?).
Please help...
my code:
$body = file_get_contents("php://input");
$content_type = false;
if(isset($_SERVER['CONTENT_TYPE'])) {
$content_type = $_SERVER['CONTENT_TYPE'];
// echo $content_type;
}
switch($content_type) {
//other case...
case "application/x-www-form-urlencoded":
parse_str($body, $postvars);
foreach($postvars as $field => $value) {
$parameters[$field] = $value;
}
$this->format = "html";
break;
default:
// we could parse other supported formats here
break;
}
$this->parameters = $parameters;
private function createRecord(){
if($this->get_request_method() != "PUT"){
$this->response('',406);
}
$table = strtolower(trim(str_replace("/", "", $_REQUEST['rquest'])));
/*
$Q = explode("/", $_SERVER["rquest"]);
print_r(array_values($Q));
echo "\n";
*/
$uri = $this->parameters;
if($uri){
array_shift($uri);
foreach( $uri as $k => $v )
{
$aKeyPholder[]= $k;
$aKey[]= ':'.$k;
}
$aKeyPholder= implode(',', $aKeyPholder);
$aKey= implode(',', $aKey);
$insert = "INSERT INTO '$table' ($aKeyPholder) VALUES ($aKey)";
// echo "insert=$insert\n";
$stmt = $this->db->prepare($insert);
foreach($uri as $k => &$v){
$stmt->bindParam(':'.$k, $v, PDO::PARAM_STR);
}
//$stmt->execute();
if ($stmt->execute()) { echo "Record succesfully created!";}
$this->response($this->json($success),200);
}
else{
$this->response('',204); // If no records "No Content" status
}
}
Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.
<td class="td_input_form">
<?php
// if the BidIDFile is empty,
if(empty($result["BidIDFile"]))
{
//then show file upload field for Bid File
echo '<input type="file" name="BidIDFile[]" size="50">';
}
else
{
// Bid file already upload, show checkbox to delete it.
echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
'.$result["BidIDFile"].'';
}
</td>
Then to delete this file, I use the following code:
// Connect to SQL Server database
include("connections/Connect.php");
// Connect to SQL Server database
include("connections/Connect.php");
$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;
if(isset($_POST['delete']))
{
// whilelisted table columns
$fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');
$fileColumns = array();
foreach ($_POST['delete'] as $fileColumn)
{
if(in_array($fileColumn, $fileColumnsInTable))
$fileColumns[] = $fileColumn;
}
// get the file paths for each file to be deleted
$stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
$files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);
// loop over the files returned by the query
foreach ($files as $file )
{
//delete file
unlink($file);
}
// now remove the values from the table
$stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?php
error_reporting(E_ALL);
class ProcessBid
{
public $data;
public $statement;
public $where_vals;
protected $keyname;
protected $conn;
public function __construct($conn = false)
{
$this->conn = $conn;
}
public function SaveData($request = array(),$skip = false,$keyname = 'post')
{
$this->keyname = $keyname;
$this->data[$this->keyname] = $this->FilterRequest($request,$skip);
return $this;
}
public function FilterRequest($request = array(), $skip = false)
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Use the skip
if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
// Create insert values
$vals['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$vals['cols'][] = "".str_replace("txt","",$key)."";
// For good measure, create an update string
$vals['update'][] = "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$vals['bind']['cols'][] = "".$key."";
$vals['bind']['cols_bind'][] = ":".$key;
$vals['bind']['vals'][":".$key] = $value;
$vals['bind']['update'][] = "".$key.' = :'.$key;
}
}
}
return (isset($vals))? $vals:false;
}
public function AddFiles($name = 'item')
{
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// we need to differentiate our type array names
$use_name = ($name == 'item')? 'Addend':$name;
// To start at Addendum1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $this->target.$file_name)) {
// Format the key values for addendum
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = $this->FilterRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
$this->data[$name] = $sql;
return $this;
}
public function SaveFolder($target = '../uploads/')
{
$this->target = $target;
// Makes the folder if not already made.
if(!is_dir($this->target))
mkdir($this->target,0755,true);
return $this;
}
public function where($array = array())
{
$this->where_vals = NULL;
if(is_array($array) && !empty($array)) {
foreach($array as $key => $value) {
$this->where_vals[] = $key." = '".ms_escape_string($value)."'";
}
}
return $this;
}
public function UpdateQuery()
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$update[] = implode(",",$arr['update']);
}
}
$vars = (isset($update) && is_array($update))? implode(",",$update):"";
// Check that both columns and values are set
$this->statement = (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;
if(isset($this->where_vals) && !empty($this->where_vals)) {
$this->statement .= " where ".implode(" and ",$this->where_vals);
}
return $this;
}
public function SelectQuery($select = "*",$table = 'bids')
{
$stmt = (is_array($select) && !empty($select))? implode(",",$select):$select;
$this->statement = "select ".$stmt." from ".$table;
return $this;
}
public function InsertQuery($table = 'bids')
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
$this->statement = "insert into ".$table;
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$insert['cols'][] = implode(",",$arr['cols']);
$insert['vals'][] = implode(",",$arr['vals']);
}
}
$this->statement .= '(';
$this->statement .= (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
$this->statement .= ") VALUES (";
$this->statement .= (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
$this->statement .= ")";
return $this;
}
}
include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
{ ?>
<h2><?php echo (isset($settings['title']))? $settings['title']:"Error"; ?></h2>
<p><?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?></p>
<?php
}
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
{
if(!isset($data) || empty($data))
return "";
if(is_numeric($data))
return $data;
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
$non_displayables[] = '/[\x00-\x08]/'; // 00-08
$non_displayables[] = '/\x0b/'; // 11
$non_displayables[] = '/\x0c/'; // 12
$non_displayables[] = '/[\x0e-\x1f]/'; // 14-31
foreach($non_displayables as $regex)
$data = preg_replace($regex,'',$data);
$data = str_replace("'","''",$data);
return $data;
}
// New bid save engine is required for both sql statement generations
$BidSet = new ProcessBid($conn);
$strId = null;
if(isset($_POST["Id"]))
{
$strId = $_POST["Id"];
//echo $strId;
}
If ($strId == "") {
//echo "This is an insert statement";
// This will generate an insert query
$insert = $BidSet->SaveData($_POST)
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->InsertQuery()
->statement;
// Check that statement is not empty
if($insert != false) {
sqlsrv_query($conn,$insert);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to Solicitation screen'));
$err = false;
}
//echo '<pre>';
//print_r($insert);
// echo '</pre>';
}
else
{
//echo "This is an update statement";
// This will generate an update query
$update = $BidSet->SaveData($_POST,array("Id"))
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->where(array("Id"=>$_POST["Id"]))
->UpdateQuery()
->statement;
//echo '<pre>';
//print_r($update);
//echo '</pre>';
// Check that statement is not empty
if($update != false) {
sqlsrv_query($conn,$update);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to admin screen'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>
I try save integer with value 0 in php to decimal(7,2) in miranda db.
But integer with value 0 save always 99999.99
I cannot find the solution. I think it can transform automatically.
I use PDO in php.
Other values than 0 works well.
My inserted array:
array(":name"=>"3ld",":urlid"=>($url->id),":date"=>"NOW()",":type"=>"renew",":status"=>($url->alias.$url->custom.".".$url->tld),":price"=>$price)
Var dump value from array:
array(6) { [":name"]=> string(3) "3ld" [":urlid"]=> string(1) "1" [":date"]=> string(5) "NOW()" [":type"]=> string(5) "renew" [":status"]=> string(19) "support.url.tld" [":price"]=> int(0) }
The part of code:
$this->db->insert("log_url",array(":name"=>"3ld",":urlid"=>($url->id),":date"=>"NOW()",":type"=>"renew",":status"=>($url->alias.$url->custom.".".$url->tld),":price"=>$price));
DB insert function:
public function insert($table,$parameters=array()){
$param="";
$val="";
$insert= $this->ph($parameters);
//Build Query
$query="INSERT INTO {$this->dbinfo["prefix"]}$table";
if(is_array($insert)){
$count=count($insert);
$i=0;
foreach ($insert as $key => $value) {
if($parameters[$value]=="NOW()"){
$val.= "NOW()";
unset($parameters[$value]);
}else{
$val.=$this->quote($value,$parameters);
}
$param.="`$key`";
if(++$i != $count) {
$param.=",";
$val.=",";
}
}
$query.=" ($param) VALUES ($val)";
}
$result = $this->db->prepare($query);
$result->execute($parameters);
if($this->error_message($result->errorInfo())) {
$this->query=strtr($query,$parameters);
$this->db_error=$this->error_message($result->errorInfo());
exit;
}
++$this->num_queries;
return TRUE;
}
Quote function:
private function quote($string,$param=''){
if(empty($param)){
return "'$string'";
}
return $string;
}
Generate placeholders function:
private function ph(array $a){
$b=array();
foreach ($a as $key => $value) {
$b[str_replace(":", "", $key)]="$key";
}
return $b;
}
Any information helps, thank you.
Updated Code:
public function insert($table,$parameters=array()){
$param="";
$val=array();
$insert= array_keys($parameters); var_dump($parameters);
//Build Query
$query="INSERT INTO {$this->dbinfo["prefix"]}$table";
if(is_array($insert)){
$query.=' (`'.implode($insert,"`,`").'`) VALUES (:'.implode($insert,', :').')';
$result = $this->db->prepare($query);
foreach($parameters as $key=>$param) {
$result->bindParam(":".$key, ($param['value']=='NOW()')?date('Y-m-d H:i:s'):$param['value'], PDO::PARAM_STR);
}
}
$result->execute(); //$result->execute($parameters);
if($this->error_message($result->errorInfo())) {
$this->query=strtr($query,$parameters);
$this->db_error=$this->error_message($result->errorInfo());
exit;
}
++$this->num_queries;
return TRUE;
}
produce as price 2015.00
Replace call to method by removing ":" it has no sense to send ":" and then remove that ":" by ->ph()
$this->db->insert("log_url",
array("name"=>array("value"=>"3ld","type"=>PDO::PARAM_STR), //
"urlid"=>array("value"=>$url->id,"type"=>PDO::PARAM_STR),
"date"=>array("value"=>'NOW()',"type"=>PDO::PARAM_STR),
"type"=>array("value"=>'renew',"type"=>PDO::PARAM_STR),
"status"=>array("value"=>$url->alias.$url->custom.".".$url->tld,"type"=>PDO::PARAM_STR),
"price"=>array("value"=>$price,"type"=>PDO::PARAM_STR))); //
about PDO types params read here:
http://php.net/manual/en/pdo.constants.php
and here
http://php.net/manual/en/pdostatement.bindparam.php
and inside your function you can replace this:
$param="";
$val="";
$insert= $this->ph($parameters);
//Build Query
$query="INSERT INTO {$this->dbinfo["prefix"]}$table";
if(is_array($insert)){
$count=count($insert);
$i=0;
foreach ($insert as $key => $value) {
if($parameters[$value]=="NOW()"){
$val.= "NOW()";
unset($parameters[$value]);
}else{
$val.=$this->quote($value,$parameters);
}
$param.="`$key`";
if(++$i != $count) {
$param.=",";
$val.=",";
}
}
$query.=" ($param) VALUES ($val)";
}
$result = $this->db->prepare($query);
with this:
$val=array();
$insert= array_keys($parameters);
//Build Query
$query="INSERT INTO {$this->dbinfo["prefix"]}$table";
if(is_array($insert)){
$query.=' (`'.implode($insert,"`,`").'`) VALUES (:'.implode($insert,', :').')';
$stmt= $this->db->prepare($query);
foreach($parameters as $key=>$param) {
//$stmt->bindParam(":".$key, ($param['value']=='NOW()')?date('Y-m-d H:i:s'):$param['value']);
if($param['value']=='NOW()') {
$now = date('Y-m-d H:i:s');
$stmt->bindParam(":".$key, $now, $param['type']);
} else {
$stmt->bindParam(":".$key, $param['value'], $param['type']);
}
}
}
so, this must work
by the way, don't forget change:
$result->execute($parameters);
to
$stmt->execute();
downthere...
hi all im new ish to php and new to stack overflow but do have some knowledge in php what im trying to do is get one value from my returned array call from an api function is
$character->getSlot('head');
using print_r gives me:
Array (
[icon] => http://url to image location
[name] => Wizard's Petasos
[slot] => head )
if i echo $character->getSlot('head', 'name); gives me C:\xampp\htdocs\test\index.php on line 19 and just returns the word Array
here is the section of index.php
<?php
include('api.php');
// Call API
$API = new LodestoneAPI();
// Search for: Demonic Pagan on Sargatanas
$character = $API->get(array(
"name" => "Darka Munday",
"server" => "Ragnarok"
));
// Basic character data
echo "Character ID: " . $character->getID();
$ID = $character->getID();
$API->parseProfile($ID);
$Character = $API->getCharacterByID($ID);
echo $character->getSlot('head', 'name');
and the section of the api just in case
// GEAR
public function setGear($Array)
{
$this->Gear['slots'] = count($Array);
$GearArray = NULL;
// Loop through gear equipped
$Main = NULL;
foreach($Array as $A)
{
// Temp array
$Temp = array();
// Loop through data
$i = 0;
foreach($A as $Line)
{
// Item Icon
if (stripos($Line, 'socket_64') !== false) { $Data = trim(explode('"', $A[$i + 1])[1]); $Temp['icon'] = $Data; }
if (stripos($Line, 'item_name') !== false) { $Data = trim(str_ireplace(array('>', '"'), NULL, strip_tags(html_entity_decode($A[$i + 2])))); $Temp['name'] = htmlspecialchars_decode(trim($Data), ENT_QUOTES); }
if (stripos($Line, 'item_name') !== false) {
$Data = htmlspecialchars_decode(trim(html_entity_decode($A[$i + 3])), ENT_QUOTES);
if (
strpos($Data, " Arm") !== false ||
strpos($Data, " Grimoire") !== false ||
strpos($Data, " Tool") !== false
)
{ $Main = $Data; $Data = 'Main'; }
$Temp['slot'] = strtolower($Data);
}
// Increment
$i++;
}
// Slot manipulation
$Slot = $Temp['slot'];
if (isset($GearArray[$Slot])) { $Slot = $Slot . 2; }
// Append array
$GearArray['numbers'][] = $Temp;
$GearArray['slots'][$Slot] = $Temp;
}
// Set Gear
$this->Gear['equipped'] = $GearArray;
// Set Active Class
$classjob = str_ireplace('Two-Handed ', NULL, explode("'", $Main)[0]);
$this->Stats['active']['class'] = $classjob;
if (isset($this->Gear['soul crystal'])) { $this->Stats['active']['job'] = str_ireplace("Soul of the ", NULL, $this->Gear['soul crystal']['name']); }
}
public function getGear() { return $this->Gear; }
public function getEquipped($Type) { return $this->Gear['equipped'][$Type]; }
public function getSlot($Slot) { return $this->Gear['equipped']['slots'][$Slot]; }
the solution to this is probably really simple and im being really dumb but any help would be great :) thanks in advance
public function getSlot($Slot) {
return $this->Gear['equipped']['slots'][$Slot];
}
getSlot method have only one argument. You are passing another argument but getSlot method returns array.
You can do like this :
public function getSlot($Slot, $param = null) {
if(empty($param)) {
return $this->Gear['equipped']['slots'][$Slot];
} else {
if(isset($this->Gear['equipped']['slots'][$Slot][$param] )) {
return $this->Gear['equipped']['slots'][$Slot][$param];
} else {
return null;
}
}
}
OR
echo $character->getSlot('head')['name'] // If version is >= 5.4.*
If version < 5.4.*
$slot = $character->getSlot('head');
echo $slot['name'];