writing xml into mysql in for each loop - mysql

I have pulled values from an xml file which i need to store. I now need to get this data into my mysql database. I have done a complex for each loop with multiple levels so I am wondering how I would go about putting this in to a MYSQL insert statement. Any help would be gratefully appreciated.
Example
<?php
$source = file_get_contents("test.xml");
$xml = simplexml_load_string($source);
$game = $xml->xpath("//market");
foreach ($game as $event)
{
if (strpos($event['name'], 'Match Betting') !== false)
{
mysql_query("INSERT INTO feed (feedid, homeid, homeodd, drawid, drawodd, awayid, awayodd)
VALUES ("echo $event['id'] .", ";
{
foreach ($event->children() as $prices)
{
echo $prices['id'] . ", ";
echo $prices['odds'];
}
}
")");
}
}
?>
The above really doesnt work and is a little stupid but I really cant think how to do this.
Help please :D

dont use foreach loop inside the mysql statement. instead use the sql in the foreach loop. try it and inform if it doesn't work.

Related

Saving JSON Objects into MySQL DB in Laravel

I have the following JSON. I am a newbie to both JSON and Laravel. I want to save each of the array objects like LineNum, StationName and StopNum into the DB. Any help is greatly appreciated. I have been able to parse, but unable to save them to DB.
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n <br />" ;
$trainDetail->Route = "$key";
} else {
echo "$key => $val\n <br />";
$trainDetail->StopNumber = "$key";
$trainDetail->StationName = "$val";
}
}
The Route is not storing the LineNum, the StopNumb is not storing the correct value.
Here is the JSON I am working on.
{"LineNum1":[{"StopNumber":"MN218","StationName":"ABCD"}],"LineNum2":[{"StopNumber":"MN244","StationName":"XYZ"}],"LineNum3":[{"StopNumber":"MN220","StationName":"DEFCG"},{"StopNumber":"MN318","StationName":"QWERTY"}]}
Any help is greatly appreciated.
Regards,
A normal query will return something like this,
[{"ID":"1","Code":"ECX4236"},{"ID":"10","Code":"LWJ3154"},{"ID":"11","Code":"TTX4201"},{"ID":"12","Code":"TTY2545"},{"ID":"13","Code":"RRA2553"}]
If you use Laravel's query format.
$items = DB::table('Items')->where('isActive','=',1)->pluck('Code');
this returns an array.
["ECX4236","LWJ3154","TTX4201","TTY2545","RRA2553"]
You can easily enter this into a database using Laravel. This is what I do.

Laravel Select Query within helper file

I'm coming from codeigniter background. Unlike codeigniter helper directory, i just created helper directory within app directory of Laravel. Just want to know how to execute query within this common function. Here is my codeigniter function.
function show_menu($primary_key_col, $parent_id, $sort_order)
{
$output = "";
$ci =& get_instance();
$ci->db->select("*");
$ci->db->where('is_active', "Y");
$ci->db->where('is_delete', "N");
$ci->db->where('parent_id', $parent_id);
($sort_order!="")?$ci->db->order_by($sort_order, "ASC"):"";
$query = $ci->db->get('tbl_cms_menus');
foreach ($query->result() as $row){
$output .= '<option value="'.$row->$primary_key_col.'">'.$indent.$row->menu_name.'</option>';
}
return $output;
}
I tried something like this in laravel file. but this code did't give me any result. Please tell me where i'm doing wrong in this code. thanks
function databaseTable()
{
$table = DB::table('tbl_cms_menus');
$get_rows = $table->get();
$count_rows = $table->count();
if($count_rows > 0){
foreach ($get_rows as $tbl)
{
echo $tbl->menu_name;
}
}
}
This code will rot so hard that it shipped pre-rotten.
But, if you want to just.. ram it into the app all dry like that.. then add something like this to your base controller class...
$whatever = crazyChainingStuff;
foreach ($whatever ...) { $topMenu .= ... }
View::share('topMenu', $topMenu);
If you want to learn how to write code that will do less damage to your company and your clients then I recommend starting by watching Uncle Bob's "Fundamentals" videos. At least the first 5-6. http://cleancoders.com
It looks like you are trying to generate a drop-down/select with some data from your database, in this case, you should pass the data required for the drop-down/select from your controller to the view where you have written your HTML, for example, in your view, you may have a select like this:
echo Form::select('cms_menu', $cms_menu, Input::old('cms_menu'));
Or this (If you are using Blade):
{{ Form::select('cms_menu', $cms_menu, Input::old('cms_menu')) }}
From your controller you should pass the $cms_menu which should contain the menu-items as an arrtay and to populate that array you may try something like this:
$menuItems = DB::table('tbl_cms_menus')->lists('menu_name','id');
return View::make('your_view_name', array('cms_menu' => $menuItems));
Also, you may use something like this:
// Assumed you have a Page model
$menuItems = Page::lists('menu_name', 'id');
return View::make('your_view_name', array('cms_menu' => $menuItems));
You may also read this article which is about building a menu from database using view composer (More Laravelish way). Read more about Form::select on documentation.
It was too late to give an answer. I was also from CodeIgniter background and when I learnt Laravel then first I try to find how can I write a query in Helper. My Team leader helped me.
I have converted your code in a helper function.
function show_menu($primary_key_col, $parent_id, $sort_order)
{
$query = DB::table('tbl_cms_menus')
->select('*')
->where('is_active', '=', 'Y')
->where('is_delete', '=', 'N')
->where('parent_id', '=', $parent_id);
($sort_order != "")? $query->orderBy($sort_order, "ASC") : "";
$resultData = $query->get()->toArray();
}
Here $resultData will be array format. Now, you can create a foreach loop according to your requirement.

Why am I getting error SQLSTATE[HY093]: Invalid parameter number: ? How can I fix it?

Based on this question How to insert array into mysql using PDO and bindParam?
I'm trying to insert values of an array into mysql via PDO.
I'm having a hard time of it, because I keep getting the following error.
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
for this line $stmt->execute();
I'm guessing the problem has something to do with this line
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR); Specifically 'val$count', but I'm not sure exactly what is going wrong.
QUESTION: What am I doing wrong? How can I fix this?
Anyway here is the code I'm using along with the sample array.
$lastInsertValue=87;
$qid[0][0]=1;
$qid[0][1]=1;
$qid[1][0]=2;
$qid[1][1]="null";
$qid[2][0]=3;
$qid[2][1]=0;
$array_count = count($qid);
if (isset($lastInsertValue))
{
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stqid=array();
$a=0;
for ($i=0; $i<$array_count; $i++)
{
$stqid[$a]=$lastInsertValue;
$a++;
$stqid[$a]=$qid[$i][0];
$a++;
$stqid[$a]=$qid[$i][1];
$a++;
}
$sql = "INSERT INTO qresults (instance, qid, result) VALUES ( :val0, :val1, :val2)";
$count = 0;
$stmt = $dbh->prepare($sql);
foreach ($stqid as $val)
{
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR);
$count++;
}
$stmt->execute();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Yikes, so many issues.
Your array building is so verbose. Try this
$stqid = array();
foreach ($qid as $qidArr) {
$stqid[] = $lastInsertValue; // no idea why you repeat this
$stqid[] = $qidArr[0];
$stqid[] = $qidArr[1];
}
Use positional placeholders if you're simply relying on number of arguments
$sql = 'INSERT INTO ... VALUES (?, ?, ?)';
bindParam uses references which you are overwriting with each loop iteration. You would want to use bindValue() instead
Your query only has 3 placeholders but your $stqid array has 9 items. This is the source of your error.
You have single quotes around a variable, which will be treated as the variable name $count (not the value), try concatenating the variable to the string. Give this a try:
$stmt->bindParam(':val' . $count, $val,PDO::PARAM_STR);
for ($i=0; $i<$array_count; $i++)
{
$stqid[$a]=$lastInsertValue;
$a++;
$stqid[$a]=$qid[$i][0];
$a++;
$stqid[$a]=$qid[$i][1];
$a++;
}
so in case $i = 2, it will add $stqid[6], $stqid[7], $stqid[8] so
foreach ($stqid as $val)
{
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR);
$count++;
}
will give you :val0 to :val8
In your query you have only :val0 to :val2.
Also having multiple values in one field in database is bad. Don't do it. Try to redesign your DB differently
EDIT: bad math in the morning... sorry

How to see MySQL statements and error (if any) in CakePHP shell

I am using CakePHP 1.3 and writing custom shells to run mundane tasks in cronjobs. I am seeing failed Model->save() from time to time but I don't know anyway to find out what the exact problem is.
Is there a way to display the actual SQL statements executed and warning/error returned by MySQL in a CakePHP shell?
Thanks.
You can use the following SQL dump task for shells.
http://bakery.cakephp.org/articles/carcus88/2011/04/08/sql_dump_task_for_shells
One way to do this would be to watch the MySQL log file in a separate terminal.
A couple ways of doing this are listed here:
MySQL Query Logging in CakePHP
I found a way to do it. In your shell, add:
function initialize()
{
Configure::write('debug', 2);
$this->_loadDbConfig();
$this->_loadModels();
}
Then whenever you like to see the log, call this function:
function dump_sql()
{
$sql_dump = '';
if (!class_exists('ConnectionManager') || Configure::read('debug') < 2)
return false;
$noLogs = !isset($logs);
if ($noLogs)
{
$sources = ConnectionManager::sourceList();
$logs = array();
foreach ($sources as $source):
$db =& ConnectionManager::getDataSource($source);
if (!$db->isInterfaceSupported('getLog')):
continue;
endif;
$logs[$source] = $db->getLog();
endforeach;
}
if ($noLogs || isset($_forced_from_dbo_))
{
foreach ($logs as $source => $logInfo)
{
$text = $logInfo['count'] > 1 ? 'queries' : 'query';
$sql_dump .= "cakeSqlLog_" . preg_replace('/[^A-Za-z0-9_]/', '_', uniqid(time(), true));
$sql_dump .= '('.$source.') '. $logInfo['count'] .' '.$text. ' took '.$logInfo['time'].' ms';
$sql_dump .= 'Nr Query Error Affected Num. rows Took (ms)';
foreach ($logInfo['log'] as $k => $i)
{
$sql_dump .= $i['query'];
}
}
}
else
{
$sql_dump .= 'Encountered unexpected $logs cannot generate SQL log';
}
}
One other approach would be to have all your custom queries in the models/behaviors, and just calling the data/updates from shells. This would give you an extra benefit of being able to reuse those custom SQL in other parts of the project. For example, in unit tests.
In CakePHP 1.2, I was able to get the SQL queries to show up in my console output by adding a Configure::write('debug', 2); call to the bottom of the __bootstrap method in the cake/console/cake.php file.
No need to mess around with specifically calling a dump_sql function like some of these answers, I just automatically get the normal queries like at the bottom of a web page.

Adding 2 drop lists to associated table

I am having an issue trying to add the records using 2 drop lists.
I have a table called Urls which holds the details of url. I have a table called category populates a drop list, I have another table called publishers which populates another drop list.
$query = 'INSERT INTO url_associations (url_id, url_category_id, approved, url_publisher_id) VALUES ';
foreach ($_POST['types'] as $v){
$query .= "($uid, $v, 'Y', $k), ";
}
$query = substr ($query, 0, -2); // Chop off the last comma and space.
$result = #mysql_query ($query); // Run the query.
if (mysql_affected_rows() == count($_POST['types'])) { // Query ran OK.
echo '<p><b>Thank you for your submission!</b></p>';
$_POST = array(); // Reset values.
} else { // If second query did not run OK.
The code above allows me to addd data using the categories drop list but when I try to add the url_publisher_id as 'posters' as $k I keep getting errors in my parsing. If anyone can understand what I am trying to achieve your help would be welcomed
If the value of your $k variable is anything other than an integer or float you'll get an error because it needs quotes around it when you're building the SQL INSERT statement:
$query .= "($uid, $v, 'Y', '$k'), ";
Note: There are some major security problems in your example. If you put user input from $_POST into your SQL without escaping it you're giving the user the ability to run whatever SQL commands they want to run on your database.
I have added an extra array foreach ($_POST[posters] as $k)
//so it reads
'foreach ($_POST[types] as $v)
foreach ($_POST[posters] as $k) {`
and it has executed perfectly.
Thanks for your help.
Sean