Selecting column dynamically with curly braces - php

I am trying to select a column with curly braces, but the column has a prefix, for example:
//sql to run
$sql = "SELECT * FROM trades
WHERE trade_market = ?
AND trade_buysell = ?
" . $order . "";
//run the sql
$tickersHigh = $database->prepare($sql);
$tickersHigh->execute(array(strtolower($market), $buysell));
//fetch the results
$tickerHigh = $tickersHigh->fetch();
//return the results
return $tickerHigh->trade_{$type};
Since I have added trade_ to my column name it no longer works, it used to work like so:
return $tickerHigh->{$type};
But I recently added the prefix trade_ to my columns, like so:
return $tickerHigh->trade_{$type};
And I get the error:
Column not found: 1054 Unknown column 'PRICE' in 'order clause'
It should be selecting trade_price rather than just price
so how can I get this to work with my prefix too?
My table:
CREATE TABLE `trades` (
`trade_id` int(11) NOT NULL,
`trade_amount` text NOT NULL,
`trade_market` varchar(25) NOT NULL,
`trade_cost` varchar(25) NOT NULL,
`trade_fee` varchar(25) NOT NULL,
`trade_time` time NOT NULL,
`trade_user` varchar(25) NOT NULL,
`trade_ip` varchar(25) NOT NULL,
`trade_price` text NOT NULL,
`trade_buysell` text NOT NULL,
`trade_date` datetime NOT NULL,
`trade_maincoin` text NOT NULL,
`trade_charttime` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

try
return $tickerHigh->{"trade_$type"};

Related

Can't modify 'updated_at' in my database after adding a column with a migration in Laravel 5.1

I am trying to add a new integer "id" column in a table of my database to map every row with an id. In order to do so, I am using a migration in Laravel 5.1. The run() function of the migration is exactly the following:
public function up()
{
Schema::table('license_keys', function($table) {
$table->integer('id_nuevo');
});
}
The table I am trying to modify is set with default 'updated_at' and 'created_at' timestamps.
I execute the migration and the column is added correctly. I made sure to add the new column in the $fillable variable in my model. The next step in the process is to set the ids correctly, because that column is created with all 0s. In order to do so, I am using a Seeder with the following code:
public function run()
{
$i=1;
$licenses = LicenseKey::getEveryLicenseKey();
foreach ($licenses as $license){
$license->id_nuevo = $i;
//$license->timestamps = false;
$license->save();
$i++;
}
}
But the problem starts here. When I try to update any field of any row with the save() function it gives me the following error:
[Illuminate\Database\QueryException]
SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1 (SQL: update `license_keys` set `id_nuevo` = 1, `updated_at` = 2018-11-15 13:24:11
where `hash_key` = 0...0b)
[PDOException]
SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1
But if I set the timestamps to false (commented line in the code), the operation succeeds. Even if I try to manually change the value of the 'updated_at' column in phpMyadmin, it gives me the same error. Can anybody help me with this problem?
The structure of the table is:
CREATE TABLE `license_keys` (
`hash_key` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(10) UNSIGNED NOT NULL,
`plan_id` int(10) UNSIGNED NOT NULL,
`id_nuevo` int(11) NOT NULL,
`max_credits` bigint(20) NOT NULL,
`max_models` int(11) NOT NULL,
`max_model_categories` int(11) NOT NULL,
`max_dictionaries` int(11) NOT NULL,
`max_dictionary_entries` int(11) NOT NULL,
`max_sentiment_models` int(11) NOT NULL,
`max_sentiment_entries` int(11) NOT NULL,
`current_credits` bigint(20) NOT NULL,
`current_requests` bigint(20) NOT NULL,
`last_operation` timestamp NULL DEFAULT NULL,
`total_credits` bigint(20) NOT NULL,
`total_requests` bigint(20) NOT NULL,
`msg_pay_status` varchar(510) COLLATE utf8_unicode_ci NOT NULL,
`start_date` timestamp NULL DEFAULT NULL,
`start_billing_date` timestamp NULL DEFAULT NULL,
`expiration_date` timestamp NULL DEFAULT NULL,
`update_operation` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
And the query I'm trying to execute is:
update `license_keys` set `id_nuevo` = 1, `updated_at` = '2018-11-15 13:24:11' where `hash_key` = '0...0b'
Thanks.
Try your query without update_at, it will be written automatically
update `license_keys` set `id_nuevo` = 1 where `hash_key` = '0...0b'

Why won't my array get inserted into my Database?

I have this code and for some reason it won't get inserted into my database. It's basically taking an array, turning it into a string and then submit the values.
(If you need me to edit to show my whole code, I will do so)
Code I am having issues with down below
$array = array($RaceNumber,$Track,$Num,$HorseName,$Odds,$Color,$Jockey,$Trainer,$PostTime,$Course,$RaceDistance,$Win,$Place,$Show);
for ($a=0; $a<$Num; $a++) {
$dataArray=array($RaceNumber[$a],$Track[$a],$Num[$a],$HorseName[$a],$Odds[$a],$Color[$a],$Jockey[$a],$Trainer[$a],$PostTime[$a],$Course[$a],$RaceDistance[$a],$Win[$a],$Place[$a],$Show[$a]);
$dataArray--;
for ($j=0; $j<$Num; $j++) {
$RaceNumber=$dataArray[0];
$Track=$dataArray[1];
$Num=$dataArray[2];
$HorseName=$dataArray[3];
$Odds=$dataArray[4];
$Color=$dataArray[5];
$Jockey=$dataArray[6];
$Trainer=$dataArray[7];
$PostTime=$dataArray[8];
$Course=$dataArray[9];
$RaceDistance=$dataArray[10];
$Win=$dataArray[11];
$Place=$dataArray[12];
$Show=$dataArray[13];
$sql="INSERT INTO `$Date` (RaceNumber,Track,HorseNum,HorseName,Odds,Color,JockeyName,TrainerName,PostTime,Course,RaceDistance,Win,Place,Show) VALUES ('$RaceNumber','$Track','$Num','$HorseName','$Odds','$Color','$Jockey','$Trainer','$PostTime','$Course','$RaceDistance','$Win','$Place','$Show')";
echo $sql;
mysqli_query($query2,$sql);
}
}
when I echo my $sql I get
INSERT INTO 2018-09-20 (RaceNumber,Track,HorseNum,HorseName,Odds,Color,JockeyName,TrainerName,PostTime,Course,RaceDistance,Win,Place,Show) VALUES ('1','FingerLakes','1','','','Red','','','','Dirt','','none','none','none')
But when I do my query, it isn't inserting into database.
Part of my code where I create the datatable
<?php
if(isset($_POST['submit'])) {
$Date = $_POST['date'];
$sql = "CREATE TABLE IF NOT EXISTS `$Date` (
`Id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`RaceNumber` varchar(255) NOT NULL,
`Track` varchar(255) NOT NULL,
`HorseNum` varchar(255) NOT NULL,
`HorseName` varchar(255) NOT NULL,
`Odds` varchar(255) NOT NULL,
`Color` varchar(255) NOT NULL,
`JockeyName` varchar(255) NOT NULL,
`TrainerName` varchar(255) NOT NULL,
`PostTime` varchar(255) NOT NULL,
`Course` varchar(255) NOT NULL,
`RaceDistance` varchar(255) NOT NULL,
`Win` varchar(255) NOT NULL,
`Place` varchar(255) NOT NULL,
`Show` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8"
;
$query2 = mysqli_connect('localhost','root','','Races');
$z= mysqli_query($query2, $sql) or die("Table already exist.. please try again");
echo "Your Table ".$Date." is successfully created <br/>";
$RaceNum = $_POST['RaceNum'];
$i=1;
I am receiving in my error log of
2018-09-20 16:00:59 9444 [ERROR] Incorrect definition of table mysql.column_stats: expected column 'max_value' at position 4 to have type varbinary(255), found type varchar(255).
You are using a column named Show that's a reserved keyword in mysql, add backquotes to it and the insert query should work.
It's worth noting that you shouldn't name your table with only digits and hyphens.
For reference here is the complete list of the reserved keywords:
https://dev.mysql.com/doc/refman/8.0/en/keywords.html

PHP MYSQL prevent getting duplicate unique id while inserting from different users at same time

I am trying to generate invoice id in each invoice, now i am having thousands of invoices, Now while adding from different ip same time i am getting duplicate invoice ids how to prevent it,
invoice id generating by getting the last inserted invoice id and increment 1 to it.
my function as follows parameters
get_new_tbl_id('table_name','invoice_id_column','string to strip (INV in INV0012)','any conditions');
function get_new_tbl_id($tbl_name,$id_field,$string,$options='')
{
$new_id = 0;
$query_count_rows = "SELECT MAX(CONVERT(replace(replace($id_field,',',''),'$string',''), SIGNED INTEGER)) as $id_field FROM $tbl_name WHERE $id_field LIKE '$string%' $options";
$count_rows = mysql_query($query_count_rows);
$num_rows = mysql_num_rows($count_rows);
if($num_rows >0)
{
$last_row = mysql_fetch_assoc($count_rows);
$last_id = $last_row[$id_field];
$last_inserted_id = intval(str_replace($string,'',$last_id));
$new_id = $last_inserted_id+1;
}
else
$new_id = 1;
$format = '%1$03d';
$new_id=sprintf($format,$new_id,'');
return $string.$new_id;
}
My table as follows
CREATE TABLE IF NOT EXISTS `tbl_invoice` (
`invoice_tbl_id` int(11) NOT NULL AUTO_INCREMENT,
`invoice_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`invoice_ip` varchar(25) NOT NULL,
`invoice_status` tinyint(1) NOT NULL DEFAULT '0',
`invoice_added_by` smallint(6) NOT NULL,
`invoice_edited_by` smallint(6) NOT NULL,
`invoice_date` date NOT NULL,
`invoice_id` varchar(15) NOT NULL,
`customer_id` varchar(11) NOT NULL,
`invoice_credit_date` tinyint(4) NOT NULL,
`invoice_credit_status` tinyint(1) NOT NULL DEFAULT '0',
`total_items_count` smallint(6) NOT NULL,
`invoice_total_amount` varchar(20) NOT NULL,
`invoice_grandtotal_amount` double NOT NULL,
`invoice_discount` double NOT NULL DEFAULT '0',
`invoice_total_card_amount` double NOT NULL,
`invoice_total_cash_amount` double NOT NULL,
`invoice_total_profit` varchar(10) NOT NULL,
`cashier_approval` tinyint(1) NOT NULL DEFAULT '0',
`cashier_approval_id` smallint(6) NOT NULL,
`cashier_approval_time` datetime NOT NULL,
`cashier_approval_ip` varchar(20) NOT NULL,
`invoice_delete_note` text NOT NULL,
PRIMARY KEY (`invoice_tbl_id`),
KEY `invoice_id` (`invoice_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Use a myisam table to generate the ids for you with 2 fields. The 1st field contains the prefix (this is $string in your function), the second should be an auto increment field. Add a primary key on these 2 fields, but the prefix field must be the 1st one in the index. If you insert a new row into this table with a prefix, then mysql will increment the auto increment value within that group.
See myisam notes section in mysql documentation on auto increment for details and example.
CREATE TABLE animals (
grp ENUM('fish','mammal','bird') NOT NULL,
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (grp,id)
) ENGINE=MyISAM;
INSERT INTO animals (grp,name) VALUES
('mammal','dog'),('mammal','cat'),
('bird','penguin'),('fish','lax'),('mammal','whale'),
('bird','ostrich');
If your base table is mysql, then just alter it to get this behaviour, if not, then create a separate myisam table, do the inserts into that one first, then obtain the ids fo use in your main table.
May there will be some optimized solution, but for now I can give you this solution
use static variable lock if one person is getting id make $lock=true and keep other requests on waiting for 1 second and check again by goto start; until first request is completed; make $lock=false; at the end to release the function.
public static $lock=false;
function get_new_tbl_id($tbl_name,$id_field,$string,$options='')
{
global $lock;
start:
if($lock==true){
sleep(1);
goto start;
}
if($lock==false){
$lock==true;
}
$new_id = 0;
$query_count_rows = "SELECT MAX(CONVERT(replace(replace($id_field,',',''),'$string',''), SIGNED INTEGER)) as $id_field FROM $tbl_name WHERE $id_field LIKE '$string%' $options";
$count_rows = mysql_query($query_count_rows);
$num_rows = mysql_num_rows($count_rows);
if($num_rows >0)
{
$last_row = mysql_fetch_assoc($count_rows);
$last_id = $last_row[$id_field];
$last_inserted_id = intval(str_replace($string,'',$last_id));
$new_id = $last_inserted_id+1;
}
else
$new_id = 1;
$format = '%1$03d';
$new_id=sprintf($format,$new_id,'');
$lock=false;
return $string.$new_id;
}

Table in php is not being created when ran through the query

I did this earlier and it worked just fine and I even brought in another table and it was created just fine. I am stuck.
Here is the table that is not working.
<?php
include_once('dbconx.php');
$tbl_pages = "CREATE TABLE IF NOT EXISTS pages (
id INT(11) NOT NULL AUTO_INCREMENT,
label VARCHAR(20) NOT NULL,
title VARCHAR(50) NOT NULL,
body TEXT NOT NULL,
slug VARCHAR(50) NOT NULL,
create TIMESTAMP NOT NULL,
updated TIMESTAMP NULL,
PRIMARY KEY(id),
)";
$query = mysqli_query($dbcon, $tbl_pages);
if ($query === TRUE) {
echo "<h3>Pages table created OK :) </h3>";
} else {
echo "<h3>Pages table NOT created :( </h3>";
}
?>
One of your field names is a MySQL reserved words create. Try changing the field name to something like created. See MySQL Keywords and Reserved Words
You also have an extra comma after the primary key definition.
Try this query:
$tbl_pages = "CREATE TABLE IF NOT EXISTS pages (
id INT(11) NOT NULL AUTO_INCREMENT,
label VARCHAR(20) NOT NULL,
title VARCHAR(50) NOT NULL,
body TEXT NOT NULL,
slug VARCHAR(50) NOT NULL,
created TIMESTAMP NOT NULL,
updated TIMESTAMP NULL,
PRIMARY KEY(id)
)";
You can also echo mysqli_error if it fails so you can see details of the error.

Error fetching row from database with PHP

I am trying to fetch a row from a table in my database, and everything is retrieved successfully except for one column (page_content), whose data comes in partially. Here is the table creation code:
CREATE TABLE 'usol_site_page' (
'page_id' int(11) NOT NULL auto_increment,
'page_type_id' int(11) NOT NULL,
'page_menu_id' int(11) NOT NULL,
'page_name' varchar(100) NOT NULL,
'page_link' varchar(100) NOT NULL,
'page_heading' varchar(255) default '',
'page_content' text,
'page_title' varchar(255) default NULL,
'meta_keywords' mediumtext,
'keyword_description' text,
'pic_small' varchar(255) default NULL,
'pic_main' varchar(255) default NULL,
'pic_size' varchar(50) default NULL,
'pic_type' varchar(50) default NULL,
'display_order' int(11) NOT NULL,
'parent_page_id' int(11) NOT NULL,
'status' varchar(20) NOT NULL,
'creation_date' date NOT NULL,
'last_update_date' date NOT NULL,
PRIMARY KEY ('page_id'),
KEY 'Refusol_page_menu60' ('page_menu_id'),
KEY 'Refusol_page_type44' ('page_type_id'),
CONSTRAINT 'Refusol_page_menu60' FOREIGN KEY ('page_menu_id') REFERENCES 'usol_page_menu' ('page_menu_id') ON DELETE CASCADE,
CONSTRAINT 'Refusol_page_type44' FOREIGN KEY ('page_type_id') REFERENCES 'usol_page_type' ('page_type_id') ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=latin1
Does anyone know why page_content is not being fully retrieved?
here is the code the query :
$extendQry = "";
if($mode != "admin"){
$extendQry = "AND p.status='enable' ";
}
$qry = "SELECT p.page_id, p.page_link, p.page_name, p.page_heading, p.page_content, p.status, p.page_title,
p.meta_keywords, p.keyword_description, p.pic_main, p.pic_small, p.parent_page_id,
t.page_type_id, t.page_type, m.page_menu_id, m.menu_type
FROM usol_site_page p, usol_page_type t , usol_page_menu m
WHERE p.page_id = ".$pageId." $extendQry
AND t.page_type_id = p.page_type_id
AND m.page_menu_id = p.page_menu_id";
$result = mysql_query($qry);
return mysql_fetch_row($result);
fellas thank you very much for your quick responce sorry for my very unclear question, i got it solved by changing datatype of the column (page_content) from 'text' (64KB) to mediumtext(16MB). and it is working perfectly now. thank you all for your kind support you guyz are the best.

Categories