Auto increment is lower than total rows - mysql

I created a php script that takes values from 1 table and inserts them into another.
This executes pretty quickly (1000 rows per second).
Everything went well. There are no duplicates in the table and I think all the values from the other table are inserted.
But something strange caught my attention:
There are a total of 903388 rows in the table but the highest ID that has auto-increment enabled is 898582.
That's a difference of 4806.
The other table has almost the same amount of items as the ID but that is always off by a bit due to the original table always getting new values.
Due to such a large database a MRE could not be produced
So now my question is:
How can the auto-increment value be lower than the total amount of rows?
The datatype of the original tables ID:
bigint(20)
The datatype of the IMAGES table ID:
int(11)
Show create table IMAGES;
CREATE TABLE `IMAGES` (
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`SRC` varchar(300) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci DEFAULT NULL COMMENT 'Pad naar afbeelding',
`VERWIJDERD` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0=image is online, 1=image is verwijderd',
`DATUM` datetime NOT NULL DEFAULT current_timestamp() COMMENT 'Datum van upload',
`IP` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci DEFAULT NULL COMMENT 'ip van uploader',
`SITE` tinyint(1) DEFAULT NULL COMMENT 'site waar image is geupload',
`OID` int(11) DEFAULT NULL COMMENT 'occasion id',
`POSITIE` int(11) NOT NULL DEFAULT 0 COMMENT 'sorteer id',
`TYPE` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0=normaal 1=schade',
PRIMARY KEY (`ID`),
KEY `OID` (`OID`)
) ENGINE=InnoDB AUTO_INCREMENT=898583 DEFAULT CHARSET=latin1
My PHP script that fills the table:
<form action="" method="post">
<label for="fname">Rijen:</label><br/>
offset<input type="number" name="offset"><br/>
amount<input type="number" name="amount"><br/>
<button type="submit" name="submit">Go</button>
</form><br/>
<?php
$per_insert = 100;
if(isset($_POST['submit'])){
echo "Offset: ".$_POST['offset']."<br/>";
echo "Limit: ".$_POST['amount']."<br/>";
$msc = microtime(true);
$count = (is_numeric($_POST['offset']) ? (int)$_POST['offset'] : 0);
$amount = (is_numeric($_POST['amount']) ? (int)$_POST['amount'] : 0);
$qcount = 0;
$filter_array = array('images/occ/', null, '');
for ($i = $count+$per_insert; $i <= $amount; $i+=$per_insert){
$valuesq = array();
$olddataq = $mysqli->query("SELECT `ID`,SITE,DATUM,IP,`IMG_1`,`IMG_2`,`IMG_3`,`IMG_4`,`IMG_5`,`IMG_6`,`IMG_7`,`IMG_8`,`IMG_9`,`IMG_10`,`IMG_11`,`IMG_12`,`IMG_13`,`IMG_14`,`IMG_15`,`IMG_16`,`IMG_17`,`IMG_18`,`IMG_19`,`IMG_20`,`IMGS_1`,`IMGS_2`,`IMGS_3`,`IMGS_4`,`IMGS_5`,`IMGS_6`,`IMGS_7`,`IMGS_8`,`IMGS_9`,`IMGS_10`,`IMGS_11`,`IMGS_12`,`IMGS_13`,`IMGS_14`,`IMGS_15`,`IMGS_16`,`IMGS_17`,`IMGS_18`,`IMGS_19`,`IMGS_20` FROM `OCCASIONS` LIMIT ".$per_insert." OFFSET ".$count.";");
$qcount++;
$schade = $normaal = 0;
while($olddata = $olddataq->fetch_assoc()){
$olddata = array_diff($olddata, $filter_array);
$id = $olddata['ID'];
$datum = $olddata['DATUM'];
$ip = $olddata['IP'];
$site = $olddata['SITE'];
unset($olddata['DATUM']);
unset($olddata['ID']);
unset($olddata['IP']);
unset($olddata['SITE']);
while ($data = current($olddata)) {
$key = explode('_',key($olddata));
if($key[0] == 'IMG'){
//normale image
$datacheck = check_fotodata($data, $id, $key[1], 0);
if($datacheck === false){
$valuesq[] = "('".$data."','".$datum."','".$ip."',".$site.",".$id.", ".$key[1].", 0,0)";
}else{
$valuesq[] = $datacheck;
}
}else{
//schade image
$datacheck = check_fotodata($data, $id, $key[1], 1);
if($datacheck === false){
$valuesq[] = "('".$data."','".$datum."','".$ip."',".$site.",".$id.", ".$key[1].", 1,0)";
}else{
$valuesq[] = $datacheck;
}
}
next($olddata);
}
}
$count += $per_insert;
//var_dump($valuesq);
$mysqli->query("INSERT INTO IMAGES (SRC, DATUM, IP, SITE, OID, POSITIE, TYPE, VERWIJDERD) VALUES ". implode(",", $valuesq));
$qcount++;
}
$msc = microtime(true)-$msc;
echo "buildtime: <br/>";
echo $msc . ' s<br/>'; // in seconds
echo ($msc * 1000) . ' ms<br/>'; // in millseconds
echo $qcount . "<br/>";
$msc = microtime(true);
}
function check_fotodata($image, $oid, $pos, $type){
global $qcount, $mysqli;
$checkdataq = $mysqli->query("SELECT * FROM FOTODATA WHERE KID = ". $oid ." AND IMG = '". $image ."'");
$qcount++;
if($checkdataq->num_rows > 0){
$checkdata = $checkdataq->fetch_assoc();
if($checkdata['INFO'] == 'Verwijderd'){
$del = 1;
}else{
$del = 0;
}
return "('".$checkdata['IMG']."', '".$checkdata['DATUM']."', '".$checkdata['IP']."', '".$checkdata['SITE']."', '".$checkdata['KID']."',".$pos.",".$type.",".$del.")";
}else{
return false;
}
}

Please check count of table by below query first then compare. Count of table and max id should be equal if you use auto_increment_offset 1 and auto_increment_increment 1 in MySQL.
select count(*) from IMAGES;
Please comment what you find.

Related

Laravel - How do update a table immediately records are saved in it

In my Laravel-5.8, I have this table.
CREATE TABLE `appraisal_goal_types` (
`id` int(11) NOT NULL,
`name` varchar(200) NOT NULL,
`parent_id` int(11) DEFAULT NULL,
`max_score` int(11) DEFAULT 0,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Then I created this controller to store record in another table.
public function store(StoreAppraisalGoalRequest $request)
{
$appraisalStartDate = Carbon::parse($request->appraisal_start_date);
$appraisalEndDate = Carbon::parse($request->appraisal_end_date);
$userCompany = Auth::user()->company_id;
$employeeId = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
try {
$goal = new AppraisalGoal();
$goal->goal_type_id = $request->goal_type_id;
$goal->appraisal_identity_id = $request->appraisal_identity_id;
$goal->employee_id = $employeeId; //$request->employees_id
$goal->weighted_score = $request->weighted_score;
$goal->goal_title = $request->goal_title;
$goal->goal_description = $request->goal_description;
$goal->company_id = Auth::user()->company_id;
$goal->created_by = Auth::user()->id;
$goal->created_at = date("Y-m-d H:i:s");
$goal->is_active = 1;
if ($request->appraisal_doc != "") {
$appraisal_doc = $request->file('appraisal_doc');
$new_name = rand() . '.' . $appraisal_doc->getClientOriginalExtension();
$appraisal_doc->move(public_path('storage/documents/appraisal_goal'), $new_name);
$goal->appraisal_doc = $new_name;
}
$goal->save();
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('company_id', $userCompany)->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
$goal->update(['parent_id' => $parentid]);
}
As soon as the record is saved, I want to quickly query appraisal_goal_types
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
$goal->update(['parent_id' => $parentid]);
and update the record.
I need only one row there where the answer is true. I used the code above, but nothing is happening.
How do I resolve this?
Thank you
Try like this,
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('company_id', $userCompany)->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
$goal->parent_id = $parentid;
$goal->save();
There is an another solution like this,
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('company_id', $userCompany)->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
AppraisalGoal::where('id', $goal->id)->update(['parent_id' => $parentid]);
Both will works. And let me know if you solved the issue

How to show only per attribute

I'm trying to make a optics shop with PRESTASHOP, but I'm facing a problem. I've create 4 new columns in product and customer table (left eye diopter, right eye diopter, bridge length, leg length), the same in both tables.
What I want to do is when the shop load the products, compare this variables and if they are the same then show the product. This is to try to filter glasses to the client, only showing him the glasses that are compatible with him.
The original query is the next:
$sql = 'SELECT p.*, product_shop.*, stock.out_of_stock, IFNULL(stock.quantity, 0) AS quantity'.(Combination::isFeatureActive() ? ', IFNULL(product_attribute_shop.id_product_attribute, 0) AS id_product_attribute,
product_attribute_shop.minimal_quantity AS product_attribute_minimal_quantity' : '').', pl.`description`, pl.`description_short`, pl.`available_now`,
pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, image_shop.`id_image` id_image,
il.`legend` as legend, m.`name` AS manufacturer_name, cl.`name` AS category_default,
DATEDIFF(product_shop.`date_add`, DATE_SUB("'.date('Y-m-d').' 00:00:00",
INTERVAL '.(int)$nb_days_new_product.' DAY)) > 0 AS new, product_shop.price AS orderprice
FROM `'._DB_PREFIX_.'category_product` cp
LEFT JOIN `'._DB_PREFIX_.'product` p
ON p.`id_product` = cp.`id_product`
'.Shop::addSqlAssociation('product', 'p').
(Combination::isFeatureActive() ? ' LEFT JOIN `'._DB_PREFIX_.'product_attribute_shop` product_attribute_shop
ON (p.`id_product` = product_attribute_shop.`id_product` AND product_attribute_shop.`default_on` = 1 AND product_attribute_shop.id_shop='.(int)$context->shop->id.')':'').'
'.Product::sqlStock('p', 0).'
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl
ON (product_shop.`id_category_default` = cl.`id_category`
AND cl.`id_lang` = '.(int)$id_lang.Shop::addSqlRestrictionOnLang('cl').')
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl
ON (p.`id_product` = pl.`id_product`
AND pl.`id_lang` = '.(int)$id_lang.Shop::addSqlRestrictionOnLang('pl').')
LEFT JOIN `'._DB_PREFIX_.'image_shop` image_shop
ON (image_shop.`id_product` = p.`id_product` AND image_shop.cover=1 AND image_shop.id_shop='.(int)$context->shop->id.')
LEFT JOIN `'._DB_PREFIX_.'image_lang` il
ON (image_shop.`id_image` = il.`id_image`
AND il.`id_lang` = '.(int)$id_lang.')
LEFT JOIN `'._DB_PREFIX_.'manufacturer` m
ON m.`id_manufacturer` = p.`id_manufacturer`
WHERE product_shop.`id_shop` = '.(int)$context->shop->id.'
AND cp.`id_category` = '.(int)$this->id
.($active ? ' AND product_shop.`active` = 1' : '')
.($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '')
.($id_supplier ? ' AND p.id_supplier = '.(int)$id_supplier : '');
I'm trying to modify it, but I don't have very clear how to. And in consecuence, I'm doing wrong things. I've added the next left joins to the query.
LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON pa.`id_product` = p.`id_product`
LEFT JOIN `'._DB_PREFIX_.'product_attribute_combination` pac ON pac.`id_product_attribute` = pa.`id_product_attribute`
LEFT JOIN `'._DB_PREFIX_.'attribute` attr ON attr.`id_attribute` = pac.`id_attribute`
LEFT JOIN `'._DB_PREFIX_.'attribute_lang` attr_lang ON (attr_lang.`id_attribute` = pac.`id_attribute` AND attr_lang.`id_lang` = '.(int)$id_lang.')LEFT JOIN `'._DB_PREFIX_.'attribute_group` attr_group ON attr_group.`id_attribute_group` = attr.`id_attribute_group`
LEFT JOIN `'._DB_PREFIX_.'attribute_group_lang` attr_group_lang ON attr_group_lang.`id_attribute_group` = attr.`id_attribute_group`
Thank you for any advice.
EDIT:
The new fields of the products are features inside prestashop (there aren't inside product table) sorry for the mistake.
I put the data model of prestashop for your info.
EDIT 2:
I'm trying now to achieve this by using a module, so my php file of my module has the next code. I've follow the code from CategoryController.php, but I don't know how to remove a product if the conditions are not satisfied.
<?php
if (!defined('_PS_VERSION_'))
exit;
class glassOptics extends Module
{
/* #var boolean error */
protected $_errors = false;
public function __construct()
{
$this->name = 'glassOptics';
$this->tab = 'front_office_features';
$this->version = '1.0';
$this->author = 'MAOL';
$this->need_instance = 0;
parent::__construct();
$this->displayName = $this->l('glassOptics');
$this->description = $this->l('...');
}
public function install()
{
if (!parent::install() OR
!$this->veopticasCustomerDB('add') OR
!$this->veopticasProductDB('add') OR
!$this->registerHook('hookActionProductListOverride')
return false;
return true;
}
public function uninstall()
{
if (!parent::uninstall() OR !$this->veopticasCustomerDB('remove') OR !$this->veopticasProductDB('remove'))
return false;
return true;
}
public function veopticasCustomerDB($method)
{
switch ($method) {
case 'add':
$sql = 'CREATE TABLE IF EXISTS `'._DB_PREFIX_.'customer_optics_data` (
`id_customer` int(10) UNSIGNED NOT NULL,
`left_dioptrics` decimal(20,6) NOT NULL DEFAULT '0.000000',
`right_dioptrics` decimal(20,6) NOT NULL DEFAULT '0.000000',
`bridge` decimal(20,6) NOT NULL DEFAULT '0.000000',
`leg` decimal(20,6) NOT NULL DEFAULT '0.000000',
`glass_width` decimal(20,6) NOT NULL DEFAULT '0.000000',
`glass_height` decimal(20,6) NOT NULL DEFAULT '0.000000'
) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8';
break;
case 'remove':
$sql = 'DROP TABLE IF EXISTS `'._DB_PREFIX_ . 'customer_optics_data`';
break;
}
if(!Db::getInstance()->Execute($sql))
return false;
return true;
}
public function veopticasProductDB($method)
{
switch ($method) {
case 'add':
$sql = 'CREATE TABLE IF EXISTS `'._DB_PREFIX_.'product_optics_data` (
`id_product` int(10) UNSIGNED NOT NULL,
`left_dioptrics` decimal(20,6) NOT NULL DEFAULT '0.000000',
`right_dioptrics` decimal(20,6) NOT NULL DEFAULT '0.000000',
`bridge` decimal(20,6) NOT NULL DEFAULT '0.000000',
`leg` decimal(20,6) NOT NULL DEFAULT '0.000000',
`glass_width` decimal(20,6) NOT NULL DEFAULT '0.000000',
`glass_height` decimal(20,6) NOT NULL DEFAULT '0.000000'
) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8';
break;
case 'remove':
$sql = 'DROP TABLE IF EXISTS `'._DB_PREFIX_ . 'product_optics_data`';
break;
}
if(!Db::getInstance()->Execute($sql))
return false;
return true;
}
public function hookActionProductListOverride($params)
{
$customer_settings = glassOptics::getCustomerSettings($this->context->customer);
if ($customer_settings) {
// Inform the hook was executed
$params['hookExecuted'] = true;
// Filter products here, you are now overriding the default
// functionality of CategoryController class.
// You can see blocklayered module for more details.
if ((isset($this->context->controller->display_column_left) && !$this->context->controller->display_column_left)
&& (isset($this->context->controller->display_column_right) && !$this->context->controller->display_column_right))
return false;
global $smarty;
if (!Configuration::getGlobalValue('PS_LAYERED_INDEXED'))
return;
$categories_count = Db::getInstance()->getValue('
SELECT COUNT(*)
FROM '._DB_PREFIX_.'layered_category
WHERE id_category = '.(int)Tools::getValue('id_category', Tools::getValue('id_category_layered', Configuration::get('PS_HOME_CATEGORY'))).'
AND id_shop = '.(int) Context::getContext()->shop->id
);
if ($categories_count == 0)
return;
// List of product to overrride categoryController
$params['catProducts'] = array();
$selected_filters = $this->getSelectedFilters();
$filter_block = $this->getFilterBlock($selected_filters);
$title = '';
if (is_array($filter_block['title_values']))
foreach ($filter_block['title_values'] as $key => $val)
$title .= ' > '.$key.' '.implode('/', $val);
$smarty->assign('categoryNameComplement', $title);
$this->getProducts($selected_filters, $params['catProducts'], $params['nbProducts'], $p, $n, $pages_nb, $start, $stop, $range);
// Need a nofollow on the pagination links?
$smarty->assign('no_follow', $filter_block['no_follow']);
foreach ($params['nbProducts'] as $product) {
$product_settings = glassOptics::getProductSettings($product);
if($product_settings){
$same_bridge = ($product_settings->bridge == $customer_settings->bridge ? true : false);
$same_leg = ($product_settings->leg == $customer_settings->leg ? true : false);
$same_glass_width = ($product_settings->glass_width == $customer_settings->glass_width ? true : false);
$same_glass_heigth = ($product_settings->glass_heigth == $customer_settings->glass_heigth ? true : false);
}
}
}
}
}
I'd recommend taking a different approach and use a module for that. You would create a module that upon installation creates a table_ something like customer_optics_data. Table structure could look something like this:
CREATE TABLE `'._DB_PREFIX_.'customer_optics_data` (
`id_customer` int(10) UNSIGNED NOT NULL,
`left_eye_diopter` int(10) UNSIGNED NOT NULL,
`right_eye_diopter` int(10) UNSIGNED NOT NULL,
`bridge_length` decimal(20,6) NOT NULL DEFAULT '0.000000',
`leg_length` decimal(20,6) NOT NULL DEFAULT '0.000000'
) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8;
Then your module would hook onto actionProductListOverride hook, and this is where you would perform the check:
public function hookActionProductListOverride($params)
{
$customer_settings = MyDiopterModuleHelperClass::getCustomerSettings($this->context->customer);
if ($customer_settings) {
$params['hookExecuted'] = true;
// Filter products here, you are now overriding the default
// functionality of CategoryController class.
// You can see blocklayered module for more details.
}
}
The module would have a helper class MyDiopterModuleHelperClass that is there to register and obtain data to/from the customer_optics_data table.
This way you're not overriding the core, your updates will still function as normal, the worst thing that can happen is if the hook is suddenly removed from the future versions of PrestaShop, which is unlikely.
The module would also employ the following hooks:
displayCustomerIdentityForm - to display additional fields in My Personal information. This is where your customers would input their information for the module.
actionObjectCustomerAddAfter - this is where you would fetch that data from $_POST and save it in module's table
actionObjectCustomerUpdateAfter - this is where you would update the data if it has been changed by the customer or insert the data if for some reason it's not there.
Optionally, you could also hook the module onto
displayAdminCustomersForm - to display the additional fields in the customers form in your back office.

How to add default value for varchar value in xampp

i am trying to add a default value in Xampp.
i set it as in the picture, but when i add 1 more product, if i left i in blank, it will be blank, i mean it will not have a value as default.
Do you have any idea.
my code is:
if (isset($_POST["add"])) {
//lấy thông tin từ các form bằng phương thức POST
$tennsx = $_POST["tennsx"];
$diachi = $_POST["diachi"];
$sdt = $_POST["sdt"];
$mieuta = $_POST["mieuta"];
if ($tennsx == "" || $diachi == "" || $sdt == "" ) {
echo '<h4 align=center style="color: red;">Vui lòng nhập đầy đủ thông tin</h4>';
}else{
//thực hiện việc lưu trữ dữ liệu vào db
$sql = "INSERT INTO nhasx(
tennsx,
diachi,
sdt,
mieuta
) VALUES (
'$tennsx',
'$diachi',
'$sdt',
'$mieuta'
)";
// thực thi câu $sql với biến conn lấy từ file connection.php
mysqli_query($conn,$sql);
header('Location:manu_management.php');
}
}
This is because the Mysql assume you want to insert the empty values instead of default values. You need to omit the field with default values if no value at all to insert, see following code :
// simply check if variable $mieuta is empty
// goes here
if ( $mieuta === "" ) {
$sql = "INSERT INTO nhasx(
tennsx,
diachi,
sdt
) VALUES (
'$tennsx',
'$diachi',
'$sdt'
)";
}
else {
$sql = "INSERT INTO nhasx(
tennsx,
diachi,
sdt,
mieuta
) VALUES (
'$tennsx',
'$diachi',
'$sdt',
'$mieuta'
)";
}
Default values should work if you omit the field name and value from query string. This kind of method come in handy when we want to insert default date created column.
For better approach use this :
$sql = "INSERT INTO nhasx(
tennsx,
diachi,
sdt,
mieuta
) VALUES (
'$tennsx',
'$diachi',
'$sdt',
'".($mieuta ==='') ? 'MY DEFAULT VALUE' : $mieuta."'
)";
In your code you have set mieuta = $mieuta while inserting a new record so as per priority it would insert value from $mieuta. please remove and try again as of like below code.
if (isset($_POST["add"])) {
//lấy thông tin từ các form bằng phương thức POST
$tennsx = $_POST["tennsx"];
$diachi = $_POST["diachi"];
$sdt = $_POST["sdt"];
$mieuta = $_POST["mieuta"];
if ($tennsx == "" || $diachi == "" || $sdt == "" ) {
echo '<h4 align=center style="color: red;">Vui lòng nhập đầy đủ thông tin</h4>';
}else{
//thực hiện việc lưu trữ dữ liệu vào db
$sql = "INSERT INTO nhasx(
tennsx,
diachi,
sdt
) VALUES (
'$tennsx',
'$diachi',
'$sdt'
)";
// thực thi câu $sql với biến conn lấy từ file connection.php
mysqli_query($conn,$sql);
header('Location:manu_management.php');
}
}
CREATE TABLE IF NOT EXISTS `xxxx` ( `username` varchar(15) NOT NULL default 'abc')
try MySQL like this.
Example:
CREATE TABLE IF NOT EXISTS `test` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(10) NOT NULL DEFAULT 'abc', `test` varchar(12) NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;INSERT INTO `dbName`.`test` (`id` ,`test`)VALUES (NULL , '1');

Codeigniter Model Getting Error: Column count doesn't match value count at row 2

I am parsing currency rates from a rss.xml feed that all works great. I am now trying to insert that data into a database called rates with a table called tblRates. I keep getting this error and do not know why. Here is the function in the model I am using to try to batch insert into the database.
function addIQDRates($Data){
if($this->db->insert_batch('tblRates', $Data, 'Currency'))
{
return $this->db->affected_rows();
}else{
return FALSE;
}
}
Also here is the foreach statement I am using in my controller to sort the data from the xml file and to insert it into the database.
$Data = array();
$Data = array();
$Count = 0;
foreach ($xml->channel->item as $currencyInfo) {
$Data[$Count]['Currency'] = trim(str_replace("/USD", "", $currencyInfo->title)); // UNIQUE
$Data[$Count]['PubDate'] = date('Y-m-d H:i:s', strtotime(trim($currencyInfo->pubDate)));
$Data['CXRate'] = trim(preg_replace("/[^0-9,.]/", "", str_replace("1 United States Dollar = ", "", $currencyInfo->description)));
$Data[$Count]['DateCreated'] = date('Y-m-d H:i:s');
$Count++;
}
$TotalRows = $this->mycron_model->addIQDRates($Data);
Also here is my Create Table statement
CREATE TABLE IF NOT EXISTS `tblRates` (
`RateID` int(11) NOT NULL AUTO_INCREMENT,
`Currency` varchar(50) NOT NULL,
`PubDate` datetime NOT NULL,
`CXRate` int(11) NOT NULL,
`DateCreated` datetime NOT NULL,
PRIMARY KEY (`RateID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
all help greatly appreciated.
I am not sure, you might have written $Data['CXRate'] instead of $Data[$Count]['CXRate'].
So the loop should like like below:
foreach ($xml->channel->item as $currencyInfo) {
$Data[$Count]['Currency'] = trim(str_replace("/USD", "", $currencyInfo->title)); // UNIQUE
$Data[$Count]['PubDate'] = date('Y-m-d H:i:s', strtotime(trim($currencyInfo->pubDate)));
$Data[$Count]['CXRate'] = trim(preg_replace("/[^0-9,.]/", "", str_replace("1 United States Dollar = ", "", $currencyInfo->description)));
$Data[$Count]['DateCreated'] = date('Y-m-d H:i:s');
$Count++;
}

Mysql not inserting defined values

session_start();
if(!$_SESSION['user_id'])
{
$_SESSION['user_id'] = rand(1, 1000000);
include 'database_connect.php';
mysql_query('INSERT INTO product_views (user_session_id)
VALUES
('.$_SESSION['user_id'].')');
}
$productid = $_GET['name'];
$query = 'SELECT * FROM product_views WHERE user_session_id = '.$_SESSION['user_id'].'';
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
mysql_query('UPDATE product_views SET modelNumber="'.$productid.'" WHERE user_session_id="'.$_SESSION['user_id'].'"');
}
My field modelNumber is set to null, and I am performing an Update via the last query.
Do you think that since the default value is null, it is therefore not allowing an insertion?
My table structure:
CREATE TABLE `product_views` (
`id` int(10) DEFAULT NULL,
`user_session_id` int(11) DEFAULT NULL,
`product_id` varchar(100) DEFAULT NULL,
`view_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`modelNumber` varchar(...
I'm confused:
$query = 'SELECT * FROM product_views WHERE user_session_id = '.$_SESSION['user_id'].'';
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
mysql_query('UPDATE product_views SET modelNumber="'.$productid.'" WHERE user_session_id="'.$_SESSION['user_id'].'"');
}
Why are you looping through this result set if you're not even using $row?
Edit: I think this is what you're really trying to do:
session_start();
if(!$_SESSION['user_id'])
{
// Get the user ID
$_SESSION['user_id'] = rand(1, 1000000);
require_once('database_connect.php');
// Get the model number and escape it to prevent SQL injection
$model_number = mysql_real_escape_string($_GET['name']);
// Insert a row that associates the user_id with the model number
mysql_query("INSERT INTO product_views (user_session_id,modelNumber) VALUES('{$_SESSION['user_id']}', '$model_number')");
}