Escaping apostrophe in a dynamically created array in PHP - php
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!
Related
PHP SQL Request: select only the lowest value of time where name = $name and stage = $stage
Hi so I've already got a php script working working for this but it use a massive amount of data for a really easy task so I really would like to improve it. My problem is the following: I have a SQL database build like this and I would to do request like this one: http://myphppage.php?username=Whataname&stage=1 and I would like it to echo the result so that if I read my php page content I can read the following: 21 so basicly all I want is to do a request with the username and the stage as parameters and I would like it to return the lowest value of the column "time" WHERE name=the name parameter entered AND stage = the stage parameter entered I'm not really good in sql but I'm pretty I can make this kind of sql request in a single line or two instead of this massive script I have right now. here's the current script I have: <?php $q2 = "SELECT username FROM DB WHERE stage='$stage' GROUP BY username ORDER BY time ASC"; $result2 = mysql_query($q2); $times = array(); $userusernames = array(); $usernames = mysql_fetch_assoc($result2); while($rows=mysql_fetch_assoc($result2)) { $temp = $rows['username']; $q3 = "SELECT time FROM DB WHERE stage='$stage' AND username='$temp' GROUP BY time ORDER BY time ASC"; $result3 = mysql_query($q3); while($aaa = mysql_fetch_assoc($result3)) { array_push($times, $aaa['time']); array_push($userusernames, $rows['username']); if($rows['username']==$username) { echo $aaa['time']; } break; } } ?> may someone please help me figuring out how to do this EDIT: I have been looking around on internet but I can't find what I'm looking for, I'm pretty sure there's the answer somewhere so maybe you can just help me reformulate my question and I could find the answer by myself. I'm pretty stuck due to my lack of english vocabulary... thx in advance
You can archive the wanted result with only one query: SELECT username, MIN(time) AS lowertime FROM test_table WHERE stage='$stage' AND username='$temp' GROUP BY username ORDER BY time
Blank result for some columns when php mysql_query, works in phpmyadmin
I've run into a problem that is making me go a bit crazy. I have imported some csv data into a table in my phpadmin database and am now using a php script with mysql_query() to run a simple select query on the database and convert the result into json format - e.g. SELECT clients FROM TABLE 29. Basically, some of the columns in the table result in a json string after passing them through mysql_query() but others simply return a blank. I have fiddled for hours now and can't figure out why this is. The last bit of my code looks like this: $myquery = "SELECT `clients` FROM `TABLE 29`"; $query = mysql_query($myquery) or die(mysql_error()); if ( ! $query ) { echo mysql_error(); die; } $data = array(); for ($x = 0; $x < mysql_num_rows($query); $x++) { $data[] = mysql_fetch_assoc($query); } echo json_encode($data); mysql_close($server); Any help would be greatly appreciated. Could it be something about the data in the table? I'm at a loss. thank you! UPDATE: the length of the strings in the column clients seems to be having an effect. When I replace all the text with something shorter (e.g. aaa instead of something like company name 111 - 045 - project name - currency - etc) it works. However, I need it to be able to handle long strings as I want it to just take whatever users happen to import into it... what am I doing wrong?
No, its not about the table, its about how you loop them. Example: $data = array(); while($row = mysql_fetch_assoc($query)) { // While a row of data exists, put that row in $row as an associative array $data[] = $row; } echo json_encode($data); mysql_close($server); exit; Note: mysql is depreacted and no longer maintained. Use the improved version of the mysql extension which is mysqli or use PDO instead.
After checking all the rows of the data I discovered that the source of the problem was a 'é' - yes, an 'e' with an accent. Once I replaced it with a regular 'e' the problem went away. So much lost time for something so tiny :(
Displaying users with a php, sql count?
I have a database with users input and was wanting to output a user table (id, username) as a count on a page. The following piece of code is what I've been trying to work with but I've been having no luck and it keeps getting more and more complex - the SQL works perfectly so I'm not sure what's wrong. mysqli_select_db($db); $result = $_POST ['$result'] ; $result = mysqli_query("SELECT COUNT( * ) FROM users"); $row = mysqli_real_escape_string($result,$db); $total = $row[0]; echo "Total rows: " . $total; I'm still learning how to properly link SQL in with PHP. The warnings tell me to add an extra parameter however when I do so it still complains. I originally wanted a simple COUNT but will change the count to a table array if need be. I understand this maybe a little basic and I may have been going about it the wrong way, but I've hit a wall with it and any help on fixing the COUNT would be greatly appreciated
Replace the call to mysqli_real_escape_string to mysqli_fetch_array and your code will works. mysqli_real_escape_string is only useful for string escaping when you INSERT or UPDATE data to MySQL. $row = mysqli_fetch_array ($result);
Please try this code: $sql="SELECT * FROM users"; $result=mysqli_query($con,$sql); // Numeric array $row=mysqli_fetch_array($result,MYSQLI_NUM); $number = count($rows); Hope this works.
PHP Class uses Static DB Table/Column Names. How to make Dynamic? (BEST PRACTICES)
I found a PHP-based recipe and meal plan script, that I'd like to edit. There's a MealPlan Class that allows all users to create their own daily menus/mealplans, by selecting from a list of all recipes found in the database. I want to switch the table/column names used in the insert statement, based on the level of the user. The original insert method is: // Insert Meal Plan function insert($date, $meal, $recipe, $servings, $owner) { global $DB_LINK, $db_table_mealplans, $LangUI; $date = $DB_LINK->addq($date, get_magic_quotes_gpc()); $meal = $DB_LINK->addq($meal, get_magic_quotes_gpc()); $recipe = $DB_LINK->addq($recipe, get_magic_quotes_gpc()); $servings = $DB_LINK->addq($servings, get_magic_quotes_gpc()); $owner = $DB_LINK->addq($owner, get_magic_quotes_gpc()); $sql = "INSERT INTO $db_table_mealplans ( mplan_date, mplan_meal, mplan_recipe, mplan_servings, mplan_owner) VALUES ( '$date', $meal, $recipe, $servings, '$owner')"; $rc = $DB_LINK->Execute($sql); DBUtils::checkResult($rc, NULL, $LangUI->_('Recipe already added on:'.$date), $sql); } My idea was to change: mplan_date, mplan_meal, mplan_recipe, mplan_servings, mplan_owner to: $mplan_date, $mplan_meal, $mplan_recipe, $mplan_servings, $mplan_owner and use a switch statement to change the table/column names. But I've been told that this sort of thing is frowned upon in OOP. What's the best way to go about this? (NOTE: I can post the whole class if need be, but figured this would be enough info)
I don't have any code for you, but I've done something similar to this recently. Basically I dynamically made the SQL string by concating the string depending on what the user input. Bear with me as I try to type something on the fly. $columnsArray = array(); $sqlCmd = "INSERT INTO"; If (someCondition) { array_push($columnsArray, "mplan_date"); }//Could try turning this into a loop and just push all //applicable columns into the array $counter = 0; Foreach ($columnsArray as $columnName) { $sqlCmd .= " $columnName"; $counter++ If ($counter < count($columnsArray)){ $sqlCmd .= ","; }//This will put a comma after each column with the //exception of the last one. } So I did something like this only with a user defined select statement to retrieve data. Basiclly keep going with the logic until you’ve built a custom string that will be the user defined SQL statement, and then execute it. This includes doing something similar to the above script to concat the values into the string. Hope this gives you some ideas.
PHP foreach insert statement issue with arrays
Hey guys, i'm currently learning php and I need to do this $connection = mysql_open(); $likes= array(); foreach($likes as $like) { $insert3 = "insert into ProfileInterests " . "values ('$id', '$like', null)"; $result3 = # mysql_query ($insert3, $connection) or showerror(); } mysql_close($connection) or showerror(); For some reason this does not work =/ I don't know why. $likes is an array which was a user input. I need it to insert into the table it multiple times until all of the things in the array are in. EDIT I fixed the issue where I was closing it in my foreach loop. mysql_open is my own function btw. Any ideas?
For one $likes is an empty array in your example, I am assuming you fix that in the code you run. The second is you close the MySQL connection the first the time the loop would run, which would prevent subsequent MySQL queries from running.
there's no such function as mysql_open you may need mysql_connect also $likes variable is empty. so no foreach iterations will execute.
You close the connection within the foreach loop.
Here is the proper formatted code to insert data...You can use this. // DATABASE CONNECTION $conn=mysql_connect(HOST,USER,PASS); $link=mysql_select_db(DATABASE_NAME,$conn); // function to insert data ..here $tableName is name of table and $valuesArray array of user input function insertData($tableName,$valuesArray) { $sqlInsert=""; $sqlValues=""; $arrayKeys = array_keys($valuesArray); for($i=0;$i < count($arrayKeys);$i++) { $sqlInsert .= $arrayKeys[$i].","; $sqlValues .= '"'.$valuesArray[$arrayKeys[$i]].'",'; } if($sqlInsert != "") { $sqlInsert = substr($sqlInsert,0,strlen($sqlInsert)-1); $sqlValues = substr($sqlValues,0,strlen($sqlValues)-1); } $sSql = "INSERT INTO $tableName ($sqlInsert) VALUES ($sqlValues)"; $inser_general_result=mysql_query($sSql) or die(mysql_error()); $lastID=mysql_insert_id(); $_false="0"; $_true="1"; if(mysql_affected_rows()=='0') { return $_false; } else { return $lastID; } } // End Of Function
While many PHP newbies (myself included) begin working with databases from good ole' mysql_connect/query/etc., I can't help suggest that you look into PDO, PHP Data Objects. Depending on your prior knowledge and programming background, there may be a steeper learning curve. However, it's much more powerful, extensible, etc.; I use PDO in all my production code database wheelings-and-dealings now.