MYSQL to JSON for Autocomplete jQueryUI - php

My code below show what I'm doing. Basically the aim is to retrieve data from a database and convert it to a JSON format for jQueryUI. With the method below and a method that didn't use the array_to_json function I was able to get JSON data returned. Eg.:
[ { "name": "Kurt Schneider" }, { "name": "Sam Tsui" }, { "name": "Christina Grimmie" } ]
But the issue is that it still doesn't function with the autocomplete. I replaced the below code with the search.php that was provided with the example, so it's obviously an issue with this code.
I began with only this code:
<?php
include 'connect.php';
mysql_select_db("database", $con);
$search = mysql_query("SELECT name FROM artist");
$rows = array();
while($row = mysql_fetch_assoc($search)) {
$result[] = $row;
}
print json_encode($result);
?>
Which achieved affectively the same results as the below code (besides some differences in spacing):
(The array_to_json function was copied direct from the example).
<?php
include 'connect.php';
mysql_select_db("database", $con);
$search = mysql_query("SELECT name FROM artist");
$rows = array();
while($row = mysql_fetch_assoc($search)) {
$result[] = $row;
}
function array_to_json( $array ){
if( !is_array( $array ) ){
return false;
}
$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
if( $associative ){
$construct = array();
foreach( $array as $key => $value ){
// We first copy each key/value pair into a staging array,
// formatting each key and value properly as we go.
// Format the key:
if( is_numeric($key) ){
$key = "key_$key";
}
$key = "\"".addslashes($key)."\"";
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "\"".addslashes($value)."\"";
}
// Add to staging array:
$construct[] = "$key: $value";
}
// Then we collapse the staging array into the JSON form:
$result = "{ " . implode( ", ", $construct ) . " }";
} else { // If the array is a vector (not associative):
$construct = array();
foreach( $array as $value ){
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "'".addslashes($value)."'";
}
// Add to staging array:
$construct[] = $value;
}
// Then we collapse the staging array into the JSON form:
$result = "[ " . implode( ", ", $construct ) . " ]";
}
return $result;
}
echo array_to_json($result);
?>

<?php
include 'connect.php';
mysql_select_db("database", $con);
$search = mysql_query("SELECT name FROM artist");
$rows = array();
while($row = mysql_fetch_assoc($search)) {
//don't add the array, just the name.
$result[] = $row["name"];
}
print json_encode($result);
?>
The code above should return the JSON
["Kurt Schneider", "Sam Tsui", "Christina Grimmie"]

Related

simpleXmlIterator->valid() returns false for valid xml

I am trying to use the simpleXmlIterator to iterate through the following xml. Which xmlspy and notepad++ claim are valid. The simplexmlelement->asXML() returns the same input. However simpleXmlIterator->valid() returns false even after simpleXmlIterator->rewind().
Why does the function simpleXmlIterator->valid() consider it invalid?
My php code which echos N
$xml = new simpleXmlIterator( $xmlstring );
$xml->rewind();
echo $xml->valid() ? "Y" : "N";
XML used in $xmlstring
<tns1:transaction xmlns:tns="http://www.cancerresearchuk.org/di/r17/commonTypes" xmlns:tns1="http://www.cancerresearchuk.org/di/r17/supplier/newdonate" xsi:schemaLocation="http://www.cancerresearchuk.org/di/r17/commonTypes commonTypesDI.xsd http://www.cancerresearchuk.org/di/r17/supplier/newdonate supplier_newdonate_Version4.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<tns1:reference>DG007</tns1:reference>
<tns1:supporter>
<tns1:primaryExternalReferenceId>DeepsSceThree</tns1:primaryExternalReferenceId>
<tns1:primaryDataSourceCode>ND</tns1:primaryDataSourceCode>
<tns1:secondaryExternalReferenceId></tns1:secondaryExternalReferenceId>
<tns1:secondaryDataSourceCode></tns1:secondaryDataSourceCode>
<tns1:forename>TT</tns1:forename>
<tns1:startDate>2014-07-15T13:11:20.000000000</tns1:startDate>
<tns1:source>12XSU7006</tns1:source>
<tns1:statusCode>Live</tns1:statusCode>
<tns1:statusDate>2014-07-29</tns1:statusDate>
<tns1:surname>GuptaSceThree</tns1:surname>
<tns1:title>Sir</tns1:title>
<tns1:address>
<tns1:addressLine1>28 Cadmus Court</tns1:addressLine1>
<tns1:addressLine2></tns1:addressLine2>
<tns1:addressLine3></tns1:addressLine3>
<tns1:city>London</tns1:city>
<tns1:country>United Kingdom</tns1:country>
<tns1:county>Cheshire</tns1:county>
<tns1:postalCode>OX4 2WB</tns1:postalCode>
<tns1:startDate>2014-01-13</tns1:startDate>
<tns1:validationStatus>NV</tns1:validationStatus>
</tns1:address>
<tns1:contactInfo-Phone>
<tns1:phoneNumber>01231231221</tns1:phoneNumber>
</tns1:contactInfo-Phone>
<tns1:contactInfo-Email>
<tns1:emailAddress>james#johnson.com</tns1:emailAddress>
</tns1:contactInfo-Email>
<tns1:contactInfo-Mobile>
<tns1:mobileNumber>07516655678</tns1:mobileNumber>
</tns1:contactInfo-Mobile>
<tns1:directDebit>
<tns1:accountName>JessiAccName</tns1:accountName>
<tns1:amount>20.12</tns1:amount>
<tns1:bankAccountNumber>43608868</tns1:bankAccountNumber>
<tns1:bankSortCode>050370</tns1:bankSortCode>
<tns1:bankAccountCode-CRUK>121</tns1:bankAccountCode-CRUK>
<tns1:frequency>Monthly</tns1:frequency>
<tns1:product>CRDD</tns1:product>
<tns1:reference>Deeps3</tns1:reference>
<tns1:source>Donations</tns1:source>
<tns1:paymentDay>19</tns1:paymentDay>
<tns1:toBeGiftAided>Y</tns1:toBeGiftAided>
<tns1:letterCodeGAD>09DTDVGC</tns1:letterCodeGAD>
<tns1:methodGAD>Written</tns1:methodGAD>
<tns1:inMemoryName>TOM</tns1:inMemoryName>
<tns1:motivation>MEM</tns1:motivation>
<tns1:dataSource>ND</tns1:dataSource>
</tns1:directDebit>
<tns1:listOfSuppressionsPreferences>
<tns1:suppressionsPreferences>
<tns1:startDate>2014-08-18</tns1:startDate>
<tns1:suppressionPreferenceCode>SMS</tns1:suppressionPreferenceCode>
<tns1:source>12XSU7009</tns1:source>
</tns1:suppressionsPreferences>
</tns1:listOfSuppressionsPreferences>
<tns1:listOfMailingActivities>
<tns1:mailingActivities>
<tns1:originatorActivityID>SK-ACT-OID0048</tns1:originatorActivityID>
<tns1:category>Donate in Memory</tns1:category>
<tns1:endDate>2014-08-20T21:21:01.000000000</tns1:endDate>
<tns1:letterCode>1VGA</tns1:letterCode>
</tns1:mailingActivities>
</tns1:listOfMailingActivities>
</tns1:supporter>
</tns1:transaction>
The reason behind this is that I want to convert the XML to array/json and the standard solutions are not working because of namesapce. I found this code which claims to work but fails to get through the first hurdle of main while loop, so I assume it is my XML that is the problem. Here is the code I am using
public function xmlToArray( $xml, $namespaces )
{
$a = array();
$xml->rewind();
echo $xml->valid() ? "Y" : "N";
while( $xml->valid() )
{
$key = $xml->key();
if( !isset( $a[$key] ) )
{
$a[$key] = array(); $i=0;
}
else
{
$i = count( $a[$key] );
}
$simple = true;
foreach( $xml->current()->attributes() as $k=>$v )
{
$a[$key][$i][$k]=(string)$v;
$simple = false;
}
if( $this->namespaces )
{
foreach( $this->namespaces as $nid=>$name )
{
foreach( $xml->current()->attributes( $name ) as $k=>$v )
{
$a[$key][$i][$nid.':'.$k] =( string )$v;
$simple = false;
}
}
}
if( $xml->hasChildren() )
{
if( $simple ) $a[$key][$i] = $this->xmlToArray( $xml->current(), $this->namespaces );
else $a[$key][$i]['content'] = $this->xmlToArray( $xml->current(), $this->namespaces);
}
else
{
if($simple)
{
$a[$key][$i] = strval( $xml->current() );
}
else
{
$a[$key][$i]['content'] = strval( $xml->current() );
}
}
$i++;
$xml->next();
}
return $a;
}

Getting error with prepared statement query

I'm facing a problem for several days now, and I'm staring blind at it, and can't seem to find the source myself.
I've made a class to execute my queries. The actual query executing part looks like this:
<?php
public function query( $method, $table, $data, $where_text='', $where_data='' ) {
$this->check_db_status();
$method = strtoupper( $method );
$fieldsArray = array();
$valuesArray = array();
$paramsArray = array();
$format = '';
$queryText = '';
switch( $method ) {
case 'SELECT' :
$queryText = 'SELECT %s FROM ' . $table . ' ';
foreach( $data as $field => $value ) {
$fieldsArray[] = $value;
}
break;
case 'UPDATE' :
$queryText = 'UPDATE ' . $table . ' SET %s ';
foreach( $data as $field => $value ) {
$fieldsArray[] = $field.'=?';
$format .= $this->get_value_type( $value );
$paramsArray[] = $value;
}
break;
case 'DELETE' :
$queryText = 'DELETE FROM ' . $table . ' ';
break;
case 'INSERT' :
$queryText = 'INSERT INTO ' . $table . ' (%s) VALUES (%s) ';
foreach( $data as $field => $value ) {
$fieldsArray[] = $field;
$format .= $this->get_value_type( $value );
$valuesArray[] = '?';
$paramsArray[] = $value;
}
break;
default :
$this->get_error( 'Error in method switch' );
break;
}
if( $where_text ) {
$queryText .= $where_text;
if( $where_data ) {
foreach( $where_data as $value ) {
$format .= $this->get_value_type( $value );
$paramsArray[] = $value;
}
}
}
$fields = implode( ',', $fieldsArray );
$values = implode( ',', $valuesArray );
$query = sprintf( $queryText, $fields, $values );
// DEBUG
echo '<pre>';
echo 'query: ' . $query . '<br />
echo 'format: ' .' . $format . '<br />';
print_r( $paramsArray );
echo '</pre>';
$stmt = $this->mysqli->prepare( $query );
if( $stmt === false or $stmt == NULL ) {
$this->get_error( 'Error while preparing the statement' );
}
if( $format and $paramsArray )
call_user_func_array( 'mysqli_stmt_bind_param', array_merge( array( $stmt, $format ), $paramsArray ) );
if( $stmt->execute() ) {
$result = 0;
switch( $method ) {
case 'INSERT' :
$result = ($stmt->insert_id) ? $stmt->insert_id : true;
break;
case 'UPDATE' :
case 'DELETE' :
$result = ($stmt->affected_rows) ? $stmt->affected_rows : true;
break;
case 'SELECT' :
$meta = $stmt->result_metadata();
$fields = $result = array();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
call_user_func_array(array($stmt,'bind_result'),$fields);
$i = 0;
while( $stmt->fetch() ) {
$result[$i] = array();
foreach( $fields as $k => $v)
$result[$i][$k] = $v;
$i++;
}
break;
}
$stmt->close();
$this->query_cnt++;
return $result;
}
else {
$this->get_error();
}
}
?>
Now I'm trying to make an other class to store my sessions in my own database. The write function looks like this:
<?php
public function write_session( $session_id, $session_data ) {
$query = $this->sql->query( 'INSERT', 'sessions', array( 'ses_id'=>$session_id, 'ses_time'=>time(), 'ses_start'=>time(), 'ses_data'=>$session_data, 'ses_check'=>$this->check ), 'ON DUPLICATE KEY UPDATE ses_time=?, ses_data=?', array(time(),$session_data));
if($query) {
return true;
}
else {
return false;
}
}
?>
I keep getting this error:
Warning: mysqli::prepare() [mysqli.prepare]: Couldn't fetch mysqli in /.../class.db.php on line 124
Line 124 is the line with $stmt = $this->mysqli->prepare( $query );. It is triggered by the first line of the write_session.
If put in a debug part in the database class to show the query, it gives this output:
query: INSERT INTO sessions (ses_id,ses_time,ses_start,ses_data,ses_check) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE ses_time=?, ses_data=?
format: [siissis]
Array
(
[0] => a98696a8416fc898f2c07e05f39735dc
[1] => 1402201705
[2] => 1402201705
[3] => test|s:11:"someValuess";
[4] => 40b17cb572d9bf5eaadad99b7904e0a4889a31d0
[5] => 1402201705
[6] => test|s:11:"someValuess";
)
Which seems fine to me.... what am I overlooking?
Edit
Table definition of sessions:
sessions (
ses_id varchar(32) NOT NULL,
ses_time int(11) NOT NULL,
ses_start int(11) NOT NULL,
ses_data text NOT NULL,
ses_check varchar(40) NOT NULL,
PRIMARY KEY (ses_id)
)
A pointed out in the link provided in the comments, your problem appears to be
4. You mixed OOP and functional calls to the database object.
Specifically, you use a mysqli object here
$stmt = $this->mysqli->prepare( $query );
But then proceed to make a functional mysqli call here
if( $format and $paramsArray )
call_user_func_array( 'mysqli_stmt_bind_param', array_merge( array( $stmt, $format ), $paramsArray ) );
So try replacing the code above with its corresponding OOP version
if($format and $paramsArray) {
$stmt->bind_param($format,$paramsArray);
}
Also replace
call_user_func_array(array($stmt,'bind_result'),$fields);
With
$stmt->bind_param($format,$fields);
http://www.php.net//manual/en/mysqli-stmt.bind-param.php
Implement __wakeup
Another possibility is that your db connection may have been closed due to serialization. Try reconnecting by implementing __wakup i.e.
public function __wakeup()
{
$this->mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
}

array to string php

Hy every one I have this problem with an array I start like this...
$name = array($_POST['names']);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
$nameId[] = array('ids' => $row['id'] );
}
which gives me arrays like this..
$name:
array('0'=>'name1,name2,name3')
$names:
array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
how can I bring this in an string/form like this..
array('0'=>'61,6,1')
The idea is to save the ids to the Database.
Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database?
many thanks in advance.
Change your assignment to this:
$nameId[] = $row['id'];
$name = array(name1,name2,name3);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
//below line changed
$nameId[] = $row['id'] ;
}
$string = implode(',',$nameId);
Try this :
$array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1'));
$result = implode(",",call_user_func_array('array_merge', $array));
Please note : Here all are numeric keys, so change your code to :
$nameId[] = array($row['id'] ); , remove key 'ids' from here
Output :
61,6,1
Thats what I think
$nameId[] = $row['id'];
$stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it.
function CustomFindJoinArray( $needly, $array )
{
$results = array();
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
$results = array_merge($results, foo( $needly, $value ));
}
else if ( $key == $needly )
{
$results[] = $value;
}
}
return $results;
}
echo implode( ",", CustomFindJoinArray( "ids", $your_array ) );
where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
OR More simple
foreach ($your_array as $key => $ids) {
$newArray[] = $array[$key]["ids"];
}
$string = implode(',', $newArray);
$ids = array();
foreach($nameId as $curr) {
$ids[] = $curr['ids'];
}
$str = "(".implode(",",$ids).")";

Modify syntax of this function to exclude several arrays instead of one

I'm a newbie to PHP and don't know how to modify the syntax of this function so that it can be used to exclude several arrays instead of only one. This code automatically INSERTS every value that's input in a form without having to specify the fields and excludes one array (called 'submit'), and is a slightly modified version of code that I found at http://www.abeautifulsite.net/blog/2007/10/inserting-an-array-into-a-mysql-database-table/
I have several arrays which are being posted that I want to exclude from my INSERT function since they are either being processed and inserted separately or trigger where the user is redirected once the form is processed.
function mysql_insert_array($db, $data, $exclude = array()) {
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
}
}
$fields = implode(",", $fields);
$values = implode(",", $values);
if( mysql_query("INSERT INTO `$db` ($fields) VALUES ($values)") ) {
} else {
return array( "mysql_error" => mysql_error() );
}
}
$result = mysql_insert_array("db", $_POST, "submit");
The exclude argument could be an array of array:
function mysql_insert_array($db, $data, $excludes = array()) {
$fields = $values = array();
if( !is_array($excludes) ) $excludes = array($excludes);
foreach($excludes as $exclude ) {
$data = array_diff_assoc($data, $exclude);
}
foreach( array_keys($data) as $key ) {
$fields[] = "`$key`";
$values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
}
$fields = implode(",", $fields);
$values = implode(",", $values);
if( !mysql_query("INSERT INTO `$db` ($fields) VALUES ($values)") ) {
return array( "mysql_error" => mysql_error() );
}
}
Then, you could use it like this :
$array1 = array('toto', 'titi', 'tata');
$array2 = array('submit', 'foo');
$parent_array = array ($array1, $array2);
$result = mysql_insert_array("db", $_POST, $parent_array);

Encoding JSON with double quotes instead of single quotes

I have a json.php file which delivers results like this:
{ "markers": [ {'a1_id':"4213CK58", etc.
The problem is that the Google Maps API doesn't like single quotes and so I need my results like this:
{ "markers": [ {"a1_id":"4213CK58", etc.
Replacing ' by " in the code doesn't deliver...
<?php
// Iterate over the rows
$nextRow= $result->nextRow();
$r = 1;
$info = array();
while ( $nextRow ) {
$nextColumn = $result->nextColumn();
// Has this column been printed already
if ( $unique )
{
$d = $result->getDataForField($unique);
if ( array_key_exists($d, $already) )
{
$nextRow= $result->nextRow();
continue;
}
$already[$d] = true;
}
echo '{';
// Iterate over the columns in each row
while ( $nextColumn )
{
// Get the variable
$variable = $result->getOutputVariable();
$name = $variable->getName(true);
$data = $result->getDataForField();
if ( !isset($info[$name]) ) {
$info[$name]['translate'] = $variable->shouldTranslate();
$info[$name]['type'] = $variable->getDataType();
$info[$name]['linkable'] = $variable->isLinkable();
}
// Translate the data if requested
if ( $info[$name]['translate'] ) {
$data = LQMTemplate::_($data);
}
$data = $variable->format($data, false);
$type = $info[$name]['type'];
if ( ($type == 'bool') or ($type == 'boolean') )
{
$data = $data ? '1' : '0';
echo "'$name':$data";
} elseif ( $encode ) {
// Can we use json_encode ?
// str_replace because some versions of PHP have a bug that will over escape forward slashes
echo "'$name':".str_replace('\\/', '/', json_encode($data));
} else {
$data = LQMUtility::jsonEscape($data, '"');
echo "'$name':\"$data\"";
}
// Conditionally print the next column
$nextColumn = $result->nextColumn();
if ( $nextColumn ) echo ",\n ";
}
// Conditionally print the next column
$nextRow = $result->nextRow();
echo $nextRow ? "},\n" : "}\n";
$r++;
}
unset($result);
echo ']}';
}
}
Create an array containing the data you want to encode and then use PHP's builtin json_encode() function.

Categories