insert blob not working (mysql_real_escape_string) - mysql-real-escape-string

I am trying to copy image blobs from one table to another, and it is not working, since the mysql_real_escape_string () is no longer available. The special characters in the blob are blocking the insert and I can't figure out how to correct this. Your help would be appreciated. Thank you.
foreach ($dbh->query($query_images) as $images-1) {
$ins = "INSERT INTO images-2 SET image_blob='".images-1['image_blob']."'";
$dbh->exec($ins);
}

First you have:
$ins = "INSERT INTO images-2 SET image_blob='".images-1['image_blob']."'";
when you likely want:
$ins = "INSERT INTO images-2 SET image_blob='".$images-1['image_blob']."'";
but that could just be a typo in your post.
You can do this in pure MySQL and not have to iterate through each row in the images-1 table:
INSERT INTO images-2 (image_blob) VALUES (SELECT image_blob FROM images-1)
If it is some kinda of escaping problem I would suggest going with the PDO stuff in PHP:
$pdo = new PDO('mysql:host=hostname;dbname=db', $user, $pass);
foreach($dbh->query($query_images) as $images-1) {
$sth = $pdo->prepare("INSERT INTO images-2 SET image_blob=?")
$sth->execute([$images-1['image_blob']]);
}
I did not test any of this code but just put it together based on documentation and experience.

Related

Executing simple query issue in Zend 2

I want to execute two queries in zend 2 :
This is the content of my model file:
$email = $getData['login_email'];
$password = $getData['login_password'];
$select = $this->adapter->query ("select count(*) as counter from users where email = '$email' and password = '".md5($password)."'");
$results = $select->execute();
if ($results->current()['counter'] == 1 ){
// $update_user = $this->adapter->query("UPDATE users SET session_id = '".$session_id."' WHERE email = '".$email."'");
try {
$update_user = $this->adapter->query("select * from users");
} catch (\Exception $e) {
\Zend\Debug\Debug::dump($e->__toString()); exit;
}
$update_session = $update_user->execute();
For some reason if i remove one random query, the another one will be executed. I know it is weird but i believe there is a rational answer to it. The result of the try catch part is:
I did not write it wrong the query. AS you can see I tried a simple select query and i got the same result. Actually I have no idea what is wrong this. Please help with this, I'm looking up for an answer on the internet during the last 5-6 days and I found nothing. If you want me to provide any more information, please ask. THX
As this answer suggests, this is an issue with the mysqli driver using unbuffered queries by default.
To fix this, you have to buffer the result of the first query before running the next one. With ZF2, the Result interface has a buffer() method to achieve this :
$results = $select->execute();
$results->buffer();

Zend framework 2 CSV data as an array or string

I am still very new to Zend and running into some issues on exporting my data to a CSV.
I found a great resource that explains the headers and download part here however I am running into issues when trying to export the actual data.
If I create a variable like $content = "test" the export works fine using the code above.
However when I duplicate my indexAction code, make some changes, and bring it into my downloadAction, I am getting issues that I believe are due to my content being returned as an Object rather than an array or string.
My Module is grabbing the SQL by using:
public function fetchAllMembers($order = null , $order_by = null, $selectwhere = null) {
$session = new SessionContainer('logggedin_user');
$sql = new Sql($this->adapter);
$select = new Select();
$select->from(array('u' => 'tbl_all_data'));
if ($selectwhere != null){
$select->where($selectwhere);
}
$select->order($order_by . ' ' . $order);
$selectString = $sql->getSqlStringForSqlObject($select);
$results = $this->adapter->query($selectString, Adapter::QUERY_MODE_EXECUTE);
$results->buffer();
return $results;
}
and my Controller is calling that SQL by using:
$content = $modulesTable->fetchAllMembers($order, $order_by, $where);
Any help would be greatly appreciated, and I don't need anyone to write the code for me just help with pointoing me in the right direction.
$this->adapter->query returns a Zend\Db\ResultSet object. So you need to call $results = $results->toArray(); to send an array.
Also you need to loop through the array and echo it out in your view file.
Results, returned by adapter are ResultSet type. I guess you need to call at least
current()
method to grab some data. And they will be of array type, so, again you need to do something with them.
toArray() is often used to quickly get data.
More sophisticated way to get data, is to use next() method with current():
$firstThing = $result->current();
$result->next();
$result->next();
$thirdThing = $result->current();
It's just an example, but it can be useful in some cases.

Fetch values of aggregated columns in Propel

I am trying to make following query in Propel:
$criteria = new Criteria();
$criteria->clearSelectColumns();
$criteria->addSelectColumn(TableName::COLUMN1)
->addSelectColumn(TableName::COLUMN2)
->addAsColumn('alias1', 'DATE('.TableName::INIT_TIME.')')
->addAsColumn('alias2', 'COUNT('.TableName::DOWNLOAD_START_TIME.')')
->addGroupByColumn('DATE('.TableName::INIT_TIME.')')
->addGroupByColumn(TableName::DOWNLOAD_START_TIME);
$logs = TableName::doSelect($criteria);
It seems that everything OK and according to MySQL log file query generated and saved to server right. However I cannot get values of aggregated columns.
doSelect returns array of TableName objects which have no methods to fetch aggregated columns. So, how can I do it?
PS: I am talking about symfony 1.4 with Propel if it matters.
You should avoid the use of Criteria, use the ModelCriteria API instead (documentation available at: http://www.propelorm.org/reference/model-criteria.html)
The following query:
<?php
$criteria = new Criteria();
$criteria->clearSelectColumns();
$criteria->addSelectColumn(TableName::COLUMN1)
->addSelectColumn(TableName::COLUMN2)
->addAsColumn('alias1', 'DATE('.TableName::INIT_TIME.')')
->addAsColumn('alias2', 'COUNT('.TableName::DOWNLOAD_START_TIME.')')
->addGroupByColumn('DATE('.TableName::INIT_TIME.')')
->addGroupByColumn(TableName::DOWNLOAD_START_TIME);
$logs = TableName::doSelect($criteria);
Can be rewritten as below:
$query = TableNameQuery::create()
->select(array('Column1', 'Column2'))
->withColumn('DATE(InitTime)', 'alias1')
->withColumn('COUNT(DownloadStartTime)', 'alias2')
->groupBy('alias1')
->groupByDownloadStartTime()
;
$logs = $query->find();
Note you won't select both columns alias1 and alias2 as you didn't add them to the selected columns in your code. You can do that by adding the two alias to the select() clause:
->select(array('Column1', 'Column2', 'alias1', 'alias2'))
I used this snippet to retrieve and fetch data when I followed this same approach, but selecting only one column in my criteria through addSelectColumn:
$logs = TableName::doSelectStmt($criteria);
$data = $logs->fetchAll(PDO::FETCH_COLUMN, 0);
I hope this can help you.
My method is to make a query and iterate through a recordset. As suggested I use FETCH_BOTH to get array positions, but names as well. I take those values and hydrate my object, but also manually populate the properties of the object that are meant to hold the aggregate values. I pass those objects back to my application and use them as normal objects would be used in my view.
$stmt = self::doSelectStmt($c);
// empty array for now
$results = array();
// lets iterate through this
while($row = $stmt->fetch(PDO::FETCH_BOTH)) {
// we need to create a new object
$division = new Division();
// and we'll hydrate each row turning into an object so we can use it easily
$division->hydrate($row);
// now here's the magic, this object did not exist from our tables, we'll fix that
$division->setNumPlayers($row['num_players']);
$division->setNumTeams($row['teams']);
// set the output object
$results[] = $division;
}
return $results; // array of objects including aggregate values

Symfony propel criterion inside for loop

$record_values = new Criteria();
$record_values->add(TblfieldsPeer::CUSTOMER_ID, $company_qu_id);
$record_values->add(TblfieldsPeer::RECORD_TYPE_ID, $query_rtype);
for($fieldid_arrayCount=0;$fieldid_arrayCount<count($fieldIds);$fieldid_arrayCount++)
{
$currentFieldId = $fieldIds[$fieldid_arrayCount];
if(isset($query_values[$fieldid_arrayCount]))
{
$criterion1 = $record_values->getNewCriterion(TblfieldsPeer::FIELDS_ID, $currentFieldId);
$criterion1->addAnd($record_values->getNewCriterion(TblfieldsPeer::FIELD_VALUES, $query_values[$fieldid_arrayCount]));
$record_values->add($criterion1);
}
}
$record_values_results = TblfieldsPeer::doSelect($record_values, $con1);
But only last criterion is added. I check the databases in debug toolbar only the last criterion is there. What could be the problem.
Please help me....
I'm not a propel expert but maybe you could try to use 2 alternative changes:
to use addAnd statement instead of add one in $record_values->add($criterion1)
to put $record_values->add($criterion1) outside the (of course after) cycle changing $criterion1 in a field outer the cycle and using only the addAnd statement for $criterion1

DBF Large Char Field

I have a database file that I beleive was created with Clipper but can't say for sure (I have .ntx files for indexes which I understand is what Clipper uses). I am trying to create a C# application that will read this database using the System.Data.OleDB namespace.
For the most part I can sucessfully read the contents of the tables there is one field that I cannot. This field called CTRLNUMS that is defined as a CHAR(750). I have read various articles found through Google searches that suggest field larger than 255 chars have to be read through a different process than the normal assignment to a string variable. So far I have not been successful in an approach that I have found.
The following is a sample code snippet I am using to read the table and includes two options I used to read the CTRLNUMS field. Both options resulted in 238 characters being returned even though there is 750 characters stored in the field.
Here is my connection string:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\datadir;Extended Properties=DBASE IV;
Can anyone tell me the secret to reading larger fields from a DBF file?
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = string.Format("SELECT ITEM,CTRLNUMS FROM STUFF WHERE ITEM = '{0}'", stuffId);
using (OleDbDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
stuff.StuffId = dr["ITEM"].ToString();
// OPTION 1
string ctrlNums = dr["CTRLNUMS"].ToString();
// OPTION 2
char[] buffer = new char[750];
int index = 0;
int readSize = 5;
while (index < 750)
{
long charsRead = dr.GetChars(dr.GetOrdinal("CTRLNUMS"), index, buffer, index, readSize);
index += (int)charsRead;
if (charsRead < readSize)
{
break;
}
}
}
}
}
}
You can find a description of the DBF structure here: http://www.dbf2002.com/dbf-file-format.html
What I think Clipper used to do was modify the Field structure so that, in Character fields, the Decimal Places held the high-order byte of the size, so Character field sizes were really 256*Decimals+Size.
I may have a C# class that reads dbfs (natively, not ADO/DAO), it could be modified to handle this case. Let me know if you're interested.
Are you still looking for an answer? Is this a one-off job or something that needs doing regularly?
I have a Python module that is primarily intended to extract data from all kinds of DBF files ... it doesn't yet handle the length_high_byte = decimal_places hack, but it's a trivial change. I'd be quite happy to (a) share this with you and/or (b) get a copy of such a DBF file for testing.
Added later: Extended-length feature added, and tested against files I've created myself. Offer to share code with anyone who would like to test it still stands. Still interested in getting some "real" files myself for testing.
3 suggestions that might be worth a shot...
1 - use Access to create a linked table to the DBF file, then use .Net to hit the table in the access database instead of going direct to the DBF.
2 - try the FoxPro OLEDB provider
3 - parse the DBF file by hand. Example is here.
My guess is that #1 should work the easiest, and #3 will give you the opportunity to fine tune your cussing skills. :)

Resources