Here is my code
<?php
$con = mysql_connect('localhost','test','test');
mysql_select_db('test',$con);
require_once("xml2json.php");
$testXmlFile = 'mytest.xml';
$xmlStringContents = file_get_contents($testXmlFile);
$jsonContents = "";
$jsonContents = xml2json::transformXmlStringToJson($xmlStringContents);
$obj =json_decode($jsonContents);
$rows = array();
foreach($obj->rss->channel->item as $item) {
echo $item->title."\n";
echo $item->description."\n";
$rows[] = "('".mysql_real_escape_string($item->title)."','".mysql_real_escape_string($item->description)."')";
}
$del_horoscope = "delete from jos_horoscope";
mysql_query($del_horoscope);
$query = mysql_real_escape_string("INSERT INTO `jos_horoscope` (`title`,`description`) VALUES ".implode(', ',$rows));
mysql_query($query);
if (!mysql_query($query)) echo 'Oh no! Something went wrong with the query: '.mysql_error();
?>
I am not able to insert the title and description in DB. It always says
Oh no! Something went wrong with the query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'What\'s special today for you\',\'Your birth on the 25th day of the month (7 e' at line 1
Some of the Data which I am trying to insert is
What's special today for you
Your birth on the 25th day of the month (7 energy) modifies
your life path by giving you some special interest in technical,
scientific, or other complex and often hard to understand subjects.
You may become something of a perfectionist and a stickler for
details. Your thinking is logical and intuitive, rational and responsible.
Your feelings may run deep, but you are not very likely to let them
show. This birthday makes you a more private person, more
introspective and perhaps more inflexible.
Aries Horoscope for Thursday, April 25, 2013
Although most of us when we make a decision we don`t have to worry what it will impact for the world we live in, but when you make a decision we have to remember that it does impact our society in so many ways. Our choice has to be an ethical one, regardless of the outcome. Your emotions are brought into more conscious focus these few days. You may find that you can more easily communicate your feelings at this time.
The First line is title and rest is Description till Aries Horoscope . After that another title starts . Please help me . I tried many options but its not working for me
Here is my table structure
Please help me .
You are escaping your query multiple times, here is the correct way:
foreach($obj->rss->channel->item as $item) {
$rows[] = "('".mysql_real_escape_string($item->title)."','".mysql_real_escape_string($item->description)."')";
}
Now you don't need to escape it again:
$query = "INSERT INTO `jos_horoscope` (`title`,`description`) VALUES ".implode(', ',$rows);
mysql_query($query);
First of all, you don't want to escape the actual INSERT string. Just the values you are going to INSERT.
$query = mysql_real_escape_string("INSERT INTO `jos_horoscope` (`title`,`description`) VALUES ".implode(', ',$rows));
Is what you are currently doing. Just escape each of the values you are going to insert. Which leads us to the next problem. Your $rows[] array you are building inside the foreach loop isn't formatted properly if the foreach runs multiple times. Your insert should be inside of the foreach. And just scrap the array.
foreach($obj->rss->channel->item as $item) {
echo $item->title."\n";
echo $item->description."\n";
$title = mysql_real_escape_string($item->title);
$description = mysql_real_escape_string($item->description);
$query = "INSERT INTO `jos_horoscope` (`title`,`description`) VALUES ('$title', '$description')";
mysql_query($query);
}
Then I'm not really sure what the delete query is for.
Related
My question is pretty straight-forward, and I assume that people need to do this pretty often; yet, after hours of searching online, nothing especially enlightening has come up. I am aware of a thread on here about doing the same thing using PDO, but I want to stick to mysqli to be consistent across my whole site.
So, I need to move one or several rows from one database to another (and NOT from one table to another within a single database).
The code I have so far is sure to get some laughs, as this task proved to be considerably beyond my ability. Anyway, here goes:
To begin with, I have two mysqli_connect... not sure if that is encouraged, although it has not caused me problems so far.
$connect_MAIN = mysqli_connect($servername_MAIN, $username_MAIN, $password_MAIN, $dbname_MAIN);
$connect_TEMP = mysqli_connect($servername_TEMP, $username_TEMP, $password_TEMP, $dbname_TEMP);
Here is the meat in the sandwich in terms of code:
///Prepare this in advance because the 'IN' values are taken from a $_GET
$sql_select = "SELECT * FROM Concert WHERE id IN (1, 2, 3, 4)";
///Connect to source DB
$result = $connect_TEMP->query($sql_select);
if ($result->num_rows != 0) {
///Connect to destination DB
$stmt = $connect_MAIN->prepare('INSERT INTO Concert (venue_id, date, ensemble_id, info, title, repertoire, time) VALUES (?, ?, ?, ?, ?, ?, ?)');
$venue_id = $date = $ensemble_id = $info = $title = $repertoire = $time = null;
$stmt->bind_param("isissss", $venue_id, $date, $ensemble_id, $info, $title, $repertoire, $time);
while($row = $result->fetch_assoc()) {
$venue_id = $row["venue_id"];
$date = $row["date"];
$ensemble_id = $row["ensemble_id"];
$info = $row["info"];
$title = $row["title"];
$repertoire = $row["repertoire"];
$time = $row["time"];
if ($stmt->execute() === TRUE) {
if ($show_once == 1) {
echo "Info successfully submitted.";
$show_once = 0;
}
} else {
echo "Hmm, something went wrong..." . $connect_MAIN->error;
}
}
}
$stmt->close();
mysqli_close($connect_TEMP);
}
So, I know that this is a bit of a jumble... as I said, I am not sure if it is possible to connect to DB2 in the middle of a while loop returning values from DB1. Feel free to mock, but only if you have something useful to suggest!
Use a parametrized query instead of concatenating strings.
///Prepare this in advance because the 'IN' values are taken from a $_GET
$sql_select = "SELECT * FROM Concert WHERE id IN (1, 2, 3, 4)";
///Connect to source DB
$result = $connect_TEMP->query($sql_select);
if ($result->num_rows != 0) {
///Connect to destination DB
$stmt = $connect_MAIN->prepare('INSERT INTO Concert (venue, date, info, time) VALUES (?, ?, ?, ?)');
$venue = $date = $info = $time = null;
$stmt->bind_param("ssss", $venue, $date, $info, $time);
while($row = $result->fetch_assoc()) {
$venue = $row["venue"];
$date = $row["date"];
$info = $row["info"];
$time = $row["time"];
if ($stmt->execute()) {
///This is just to stop message from appearing multiple times.
if ($show_once == 1) {
echo "Info successfully submitted.";
$show_once = 0;
}
} else {
echo "Hmm, something went wrong..." . $stmt->error;
}
}
$stmt->close();
mysqli_close($connect_TEMP);
}
Yes, you may establish a second DB connection at any point in your script. There's nothing preventing it nor there's a reason to discourage it. It's far more common than you'd think (for different reasons). However, considering the overhead that actually connecting to the database carries, I would advice you to not establish a connection on each iteration (this is the best practice, performance-wise)
What I would do:
First, connect to the source database, get the data you need
Not much to say here, you already did and it looks OK. Check, as you did, that there's at least one result before moving on. If the resultset is empty, don't go any further (exit)
If there was at least one row in the resultset, establish a connection to the destination database
Do this before starting to loop to avoid the performance penalty of establishing multiple connections. If you're looking at hundreds/thousands or more rows, you'll really notice the difference. Once the connection is established, move on
Loop through the source data and prepare the insert statements
You have a choice here. Either a) loop through the whole resultset and prepare one single insert with multiple rows which you'll insert all at once at the end of the loop or b) create a single insert (single row) on each iteration, run the insert and then move on to the next iteration.
There's reasons for and against both strategies. Choose the one that suits you better.
In algorythmical terms, your code is pretty much ready (just connect to the destination DB once before you start looping). You may benefit from using a parameterized query with bindings instead of writing the full insert string, but other than that you're pretty much there.
If you are running your own MySql server, you may do this in a simpler way using the Federated engine.
The federated table behaves like a normal table, but it stores the data in a remote database. With this engine you can do someting like this:
INSERT INTO remoteTable (values) SELECT * FROM localTable
I'm working on a project to blend a number of different data sets within a PostgreSQL database. I still consider myself a beginner with PHP development and scripting. I am having some real trouble with escaping the apostrophes within the arrays. I tried a few different solutions from these forums: An escaped apostrophe in associative array value, Replace apostrophe in a dynamically created insert statement, http://www.codingforums.com/php/296075-array_walk_recursive-w-function-takes-2-parameters-mysqli_real_escape_string.html, and finally here Escaping quotation marks in PHP. I'm currently trying to recreate my script with a PDO version so I do not have to sanitize my text. At least that is what I understand is the better approach from all of the research I have done. What I'm currently looking for is a method to escape the characters while I find a more eloquent solution. Here is the main piece of code I'm using for the import process:
<?php
include('connect_local.php'); //Includes DB Connection Script
ini_set('max_execution_time', 3000); //3000 seconds = 50 minutes
$emp_get = "SELECT * FROM table1 WHERE person_type LIKE 'Employee'";
$emp_data = pg_query($conn, $emp_get);
while ($emp_row=pg_fetch_array($emp_data)) {
$oraint_get = "SELECT * FROM table2 WHERE source_enrollment_status_name LIKE 'Attended' AND employee_number LIKE '$emp_row[0]' ";
$oraint_data = pg_query($conn, $oraint_get);
$oraint_lms = "Oracle Learning Management Platform";
$oranull = "";
//foreach ($oraint_row as $oraint)
while ($oraint_row = pg_fetch_array($oraint_data)){
$data_deposit = "INSERT INTO EDU_DATA (person_number, person_name, preferred_name, person_type, start_date, original_date_of_hire
,hire_date, email_address, region, location, gender, job_name, cbs_level, supervisor_employee_number
,supervisor_name, supervisor_person_type, business_unit, organization_2, organization_3, effective_date
,completion_date, training_item_code, days_on_to_do_list, days_overdue, initial_due_in, initial_due_in_unit
,retraining_due_in, retraining_due_in_unit, retraining_period, retraining_period_unit
,curriculum_code, curriculum_title, learning_course_name, learning_activity, class_duration, college, delivery_method_name
,class_location_name, class_location_country_name, learning_category, source_enrollment_status_name, lms_platform
,supervisor_1 ,supervisor_2, supervisor_3, supervisor_4, supervisor_5, supervisor_6, supervisor_7, supervisor_8)
VALUES ('$emp_row[0]','$emp_row[1]','$emp_row[2]','$emp_row[4]','$emp_row[5]','$emp_row[6]','$emp_row[8]'
,'$emp_row[9]','$emp_row[16]','$emp_row[17]','$emp_row[19]','$emp_row[21]','$emp_row[22]','$emp_row[28]'
,'$emp_row[29]','$emp_row[30]','$emp_row[33]','$emp_row[44]','$emp_row[45]','$oraint_row[2]','$oraint_row[3]'
,'$oranull','$oranull','$oranull','$oranull','$oranull','$oranull','$oranull','$oranull','$oranull','$oranull'
,'$oranull','$oraint_row[4]','$oraint_row[5]','$oraint_row[6]','$oraint_row[7]','$oraint_row[8]','$oraint_row[9]'
,'$oraint_row[10]','$oraint_row[11]','$oraint_row[12]','$oraint_lms','$emp_row[46]','$emp_row[47]','$emp_row[48]'
,'$emp_row[49]','$emp_row[50]','$emp_row[51]','$emp_row[52]','$emp_row[53]')";
pg_query($conn, $data_deposit);
In my attempts to sanitize the text I have tried turning the array output into a string and then using addslashes without any success:
$clnname = $emp_row[1];
addslashes($clnname);
I also tried creating a function to handle this for me recursively using the example I found here: Escape single quotes in every string in php. The code snippet is the following:
function escapeApos(array $emp_row)
{
$return_array = [];
array_walk_recursive($emp_row, function($x) use (&$return_array)
{
$return_array[] = str_replace("'","\\'",$x);
}
return $return_array;
}
I have also tried a few other ways without any success. Any aid or assistance will be greatly appreciated. Also with the above function I was not sure if I needed to declare the actual column in the array that I wanted to have sanitized. Again any assistance is welcome! Thank you in advance!
Alright, HUGE thanks to everyone for helping me out! I started recreating the script using PDO instead of the first approach I took. Here is a sample of the script, I have some work ahead of me. However, now that I'm using PDO, the issues with sanitizing the text is a non-issue. I'm going to use this method from now on!
<?php
include('connect_local_pdo.php'); //Includes DB Connection Script
ini_set('max_execution_time', 3000); //3000 seconds = 50 minutes
try {
$stmt = $conn->query('SELECT * FROM table1');
$rows = $stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($rows = $stmt->fetch()) {
$emp_id = $rows['person_number'];
$stmt2 = $conn->query("SELECT * FROM table2 WHERE employee_number LIKE '$emp_id'");
$oracleint = $stmt2->setFetchMode(PDO::FETCH_ASSOC);
while ($oracleint = $stmt2->fetch()) {
$GO = $conn->prepare("INSERT INTO table3 (person_number, person_name, learning_course_name) VALUES (:emp_number, :emp_name, :learning_course_name)");
$GO->bindParam(':emp_number', $rows['person_number']);
$GO->bindParam(':emp_name', $rows['person_name']);
$GO->bindParam(':learning_course_name', $oracleint['learning_course_name']);
$GO->execute();
}
}
} catch (PDOException $b) {
echo 'Data Extraction Failed: ' . $b->getMessage();
}
Again, thanks for assisting the newbie! I totally love StackExchange!! You guys ROCK!
let me explain my problem..actualy i have a table where patient report get stored and patient can have more than one test so the result for every report should be different on print, result is inserting differnt but the field remark and nor inserting same value for more than one test..
this is input field image of report
and the field row can increase acording to increase of tested by patient..
now i am using this for inserting in table
function save_report_content()
{
$R=DIN_ALL($_REQUEST);
$dt = time();
foreach($R as $k=>$v)
{
$test_id = str_replace('rep_result_', '', $k);
if(strstr($k, 'rep_result_'))
{
$content = $v;
$SQL = "INSERT INTO report SET
rep_te_id = '$test_id',
rep_result = '$content',
record_id = '$R[payment_id]',
remark= '$R[remark]',
nor= '$R[nor]',
rep_date = '$dt'";
now result is going differently in table but remark and nor same for more than one test
i spend so much time to recover this problem but did not succeed, if i miss any relevant info regarding this question then feel free to ask me, and thanks in advance, any idea will be appreciate highly....
Whats the structure of your form ?
<input name='nor[]' />
It should be an array to allow each rows value to come other wise just the last rows value will come ...
when you are in the foreach .. you shouldn't use $R[remark] since you are using $k=>$v
it should be $v['remark']
OK so I used some php/SQL scripts that I found online for hosting a March Madness pool website. It was a pain to set up and debug the guys code, but I basically got it working. For some reason the author created a "brackets" table and a "scores" table.
The "brackets" table is much larger and contains variables for: id, name, person, email, time, tiebreaker, and all 63 of the persons game selections. id increments for every bracket. name is actually the name given to the bracket by the creator. person is the persons name. And so on.
For some reason, this guy made a separate table for scoring the brackets. The "scores" table has the variables: id, name, score, and scoring_type.
Sorting through the scripts where the data is actually displayed to the website, I have no idea what the creator was thinking, but pretty much all of the data displayed uses the "scores" table.
My Problem: The scores table doesn't have a variable for the persons name. So the rankings and brackets are all displayed and organized by the name that the person gave their bracket. People keep asking me whose bracket is whose. I figured it'd be a quick fix to implement it, but boy was I wrong. I'm new to MySql and don't really completely understand what I'm doing. But I looked some stuff up and I've tried many things and CANNOT get it to work.
What I've tried: I was thinking about combining the tables into one but I didn't want to spend hours on something I set up once a year. Figuring both tables have 2 values that are the same, name and id, I tried doing some queries to match the values and request the variable "person." None of these have worked however.
I modified this in a few different ways:
$query = "SELECT person FROM `brackets' WHERE name='$name'";
$result = mysql_query($query,$db) or die(mysql_error());
echo "mysql_result($result)";
I tried with and without using variables. I also tried:
$query = 'SELECT * FROM `brackets';
$result = mysql_query($query,$db) or die(mysql_error());
$dataArray = array(); // create a variable to hold the information
while (($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false){
$dataArray[] = $row; // add the row in to the results (data) array
}
$personsNameToDisplay = personsName($name, $dataArray);
echo "$personsNameToDisplay";
With a function that I also tried several approaches with:
function personsName( $passedBracketName, $dataArray ){
$personsMatchedName;
foreach ($dataArray as $key => $value){
if($value == $passedBracketName ){
$personsMatchedName = $value['person'];
}
}
return $personsMatchedName;
}
The error that I've been getting is:
Table 'mlmadness.brackets' WHERE name='beasters'' doesn't exist
Yet when I go into mySQL, and click on "brackets" then "name" there is definitely a bracket with the name value of "beasters"
Thanks
"SELECT person FROM 'brackets' WHERE name='{$name}'";
that should do the trick. You also had blasters' .. the closing should also be and not a '
Better Way:
$mysqli = new mysqli("localhost", "username", "password", "database_name");
$query = "SELECT person FROM brackets WHERE name='{$name}'";
$result = $mysqli->query($query);
while($row = $result->fetch_array())
{
var_dump($row);
}
HI everyone i tried for 3 days and i'm not able to solve this problem. This is the codes and i have went through it again and again but i found no errors. I tried at a blank page and it worked but when i put it inside the calendar it has the syntax error. Thanks a million for whoever who can assist.
/** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/
$testquery = mysql_query("SELECT orgid FROM sub WHERE userid='$userid'");
while($row4 = mysql_fetch_assoc($testquery))
{
$org = $row4['orgid'];
echo "$org<br>";
$test2 = mysql_query("SELECT nameevent FROM event WHERE `userid`=$org AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'") or die(mysql_error());
while($row5=mysql_fetch_assoc($test2))
{
$namethis = $row5['nameevent'];
$calendar.=$namethis;
}
}
First question: what calendar are you talking about?
And here are my 2-cents: does the EXTRACT function returns a string or a number?
Are the "backticks" (userid) really in your query? Try to strip them off.
Bye!
It's a guess, given that you haven't provided the error message you're seeing, but I imagine that userid is a text field and so the value $org in the WHERE clause needs quotes around it. I say this as the commented out testquery has quotes around the userid field, although I appreciate that it works on a different table. Anyway try this:
SELECT nameevent FROM event WHERE userid='$org' AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'
In such cases it's often useful to echo the sql statement and run it using a database client
First step in debugging problems like this, is to print out the acutal statement you are running. I don't know PHP, but can you first build up the SQL and then print it before calling mysql_query()?
EXTRACT() returns a number not a character value, so you don't need the single quotes when comparing EXTRACT(YEAR FROM startdate) = 2010, but I doubt that this would throw an error (unlike in other databases) but there might be a system configuration that does this.
Another thing that looks a bit strange by just looking at the names of your columns/variables: you are first retrieving a column orgid from the user table. But you compare that to the userid column in the event table. Shouldn't you also be using $userid to retrieve from the event table?
Also in the first query you are putting single quotes around $userid while you are not doing that for the userid column in the event table. Is userid a number or a string? Numbers don't need single quotes.
Any of the mysql_* functions can fail. You have to test all the return values and if one of them indicates an error (usually when the function returns false) your script has to handle it somehow.
E.g. in your query
mysql_query("SELECT orgid FROM sub WHERE userid='$userid'")
you mix a parameter into the sql statement. Have you assured that this value (the value of $userid) is secure for this purpose? see http://en.wikipedia.org/wiki/SQL_injection
You can use a JOIN statement two combine your two sql queryies into one.
see also:
http://docs.php.net/mysql_error
http://docs.php.net/mysql_real_escape_string
http://www.w3schools.com/sql/sql_join.asp
Example of rudimentary error handling:
$mysql = mysql_connect('Fill in', 'the correct', 'values here');
if ( !$mysql ) { // some went wrong, error hanlding here
echo 'connection failed. ', mysql_error();
return;
}
$result = mysql_select_db('dbname', $mysql);
if (!$result ) {
echo 'select_db failed. ', mysql_error($mysql);
return;
}
// Is it safe to use $userid as a parmeter within an sql statement?
// see http://docs.php.net/mysql_real_escape_string
$sql = "SELECT orgid FROM sub WHERE userid='$userid'";
$testquery = mysql_query($sql, $mysql);
if (!$testquery ) {
echo 'query failed. ', mysql_error($mysql), "<br />\n";
echo 'query=<pre>', $sql, '</pre>';
return;
}