How to use strings from php array in postgresql query? - php

need help with using php variables in postgresql query.
I am trying to make several queries to postgresql database using php array elements, but it does't work. Can anybody help?
// $nums array with strings like - "983458999893440"
for ($i=0; $i<count($nums); $i++){
$tm = pg_escape_string($nums[$i]);
$sql = "SELECT SUM(sp.summ) FROM tk.sp_tran sp WHERE sp.long_pan ='{$tm}'";
$panSum = dbCon::conn($sql);//return result of pg_fetch_all();
//Code above don't work
//Code below is ok
$tm = pg_escape_string("983458999893440");
$sql = "SELECT SUM(sp.summ) FROM tk.sp_tran sp WHERE sp.long_pan ='{$tm}'";
$panSum = dbCon::conn($sql);//return result of pg_fetch_all();
//Please help to understand what is wrong?

I find a space symbol before first letter of the string in csv file. So code is ok. It is just my an inattention(((

Related

Escaping apostrophe in a dynamically created array in 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!

Convert sql result (object) to string variable for future input into sql table (I do not want to echo the result)

I have read most of the questions here and read the php manual in regards to the problem of converting an sql result to a string, however none of them is working for me. The examples given I understand, however they are echoing the sql results, I do not want the result to be echoed, I just want it to be stored in a variable so I can immediately insert it into a next sql table.
This is my code:
$cnt_fips = mysqli_query($con, "SELECT cc_fips FROM location2 WHERE location_name = '$cnt'");
$row = mysqli_fetch_assoc($cnt_fips);
These are the codes I have used to convert to string but failed with
$myStr = !is_array($row) ? trim(addslashes($row)):'';
and
$myStr = (string)$row;
and
$myStr = print_r($row,true);
and also
$myStr = (string)$row;
And insert into the table below
$query2 = mysqli_query($con, "INSERT INTO location3 VALUES ('','$myStr')");
$row is always an array with column names as the keys, use:
$myStr = $row['cc_fips'];
Also, I'm pretty sure you can do that all in one insert with a sub-select (though maybe not if a row with $cnt doesn't exist). If so, maybe someone will post it.

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 checking array values

Hey all i am trying to figure out a way to see what all values are within the array:
$sql = "select * from product where type = ? limit 1";
$query = self::$__CONN__->prepare($sql);
$query->execute(array($type)) or die(print_r($query->errorinfo()));
I am new at PHP and im not sure what all that is doing to populate the query string. I am guessing that the first query is connecting to the server and sending out the query but how do i see what its returning back in the array above?
Any help would be great!
Just dump the $type variable
var_dump($type);
Or if you are interested in the array wrapper itself
var_dump(array($type));

Categories