php data_seek in user function - php

I have connection with mysql & need to get query results many times.
I use:
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
Then query:
$query = "CALL raport6('2014-01-01', '2014-12-31', 300);";
$result = $mysqli->query($query);
I have function in separate file which gives me header names:
function headers($result) {
global $result;
$field_cnt = $result->field_count;
$string ="";
while ($finfo = $result->fetch_field()) {
$currentfield = $result->current_field;
$string .= "'" . $finfo->name . "'";
if ($currentfield == $field_cnt) {break;}
$string .= ",";
}
$result->data_seek(0);
return $string;
}
Then I call this function twice, and get only 1 (first) result:
echo "function 1:" . headers($result);
echo "function 2:" . headers($result);
I used $result->data_seek(0); to reset pointer... but it doesn't work in function. If I use function code in file twice - then it works.
Do you know why?
Cheers!

You could make that function a whole lot simpler
function headers($result) {
$string = '';
while ($finfo = $result->fetch_field()) {
$string .= sprintf("'%s',", $finfo->name);
}
// and here is the fix
$result->field_seek(0);
// to remove last comma if required
// return rtrim($string, ',');
return $string;
}

Related

php simple html dom return array?

I'm trying to create an app using the simple HTML DOM php script, but im running into a wall currently with it - hope you can help.
The aim is to read product numbers from mySQL database, concat these numbers with a url constant and then parse this resulting website for a specific class. The result should then be printed to the screen.
My problem is that the script is returning only the first result from the function array, i have tried a few things, such as trying to call $prices->children[4], but nothing seems to help.
When i trigger the function get_prices_array() with a url, it brings back multiple results -> but when i return this inside my while loop it only brings back the first result in the array.
Heres my code, hope you can point me in the right direction!
Thanks!
<?php
include('simple_html_dom.php');
function get_prices_array($url) {
$x = file_get_html($url);
foreach ($x->find('span.price')as $dom) {
$y = $dom->outertext;
return $y;
}
$x->clear();
}
$con = mysqli_connect("localhost", "***", "***", "***");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$result = mysqli_query($con, "SELECT * FROM articles");
while ($row = mysqli_fetch_array($result)) {
$constant = '***';
$prices = get_prices_array($constant . $row["product_number"]);
echo $row["product_number"] . " - " . $prices . '<br />';
}
mysqli_close($con);
?>
// EDIT //
I changed the function get_prices_array() to loop through each span price class and add the result to an array, the array is then returned from the function. The first 5 results from the array are then stored to variables and added to the return string. Thanks for your help!
<?php
include('simple_html_dom.php');
function get_prices_array($url) {
$x = file_get_html($url);
$y = array();
foreach ($x->find('span.price')as $dom) {
$x = ($dom->outertext);
$y[] = $x;
}
return $y;
//$x->clear();
}
$con = mysqli_connect("localhost", "***", "***", "***");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$result = mysqli_query($con, "SELECT * FROM articles");
while ($row = mysqli_fetch_array($result)) {
$constant = '***';
$prices = get_prices_array($constant . $row["product_number"]);
$pos1 = $prices[0];
$pos2 = $prices[1];
$pos3 = $prices[2];
$pos4 = $prices[3];
$pos5 = $prices[4];
echo $row["product_number"] . " - " . $pos1 . " - " . $pos2 . " - " . $pos3 . " - " . $pos4 . " - " . $pos5 .'<br />';
}
mysqli_close($con);
?>
I think problem is because of return used in foreach loop of function get_prices_array($url).
it is executing foreach loop only once. There is no meaning of loop if you are returning without condition inside loop.

How to check on the if statement for the contain text on PHP dom?

I'm stored the website link in MYSQL database where I can output the data in PHP and I'm using PHP DOM to extract the data. I have output the text which I got "CBS This Morning: Saturday NEW" using this code:
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'myusername');
define('DB_PASSWORD', 'mypassword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
function clean($var)
{
return mysql_real_escape_string(strip_tags($var));
}
$channels = clean($_GET['channels']);
$id = clean($_GET['id']);
if($errflag)
{
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
echo implode('<br />',$errmsg_arr);
}
else
{
$insert = array();
if(isset($_GET['channels']))
{
$insert[] = 'channels = \'' . clean($_GET['channels']) .'\'';
}
if(isset($_GET['id']))
{
$insert[] = 'id = \'' . clean($_GET['id']) . '\'';
}
if($channels && $id)
{
$qrytable1="SELECT id, channels, links FROM tvguide WHERE channels='$channels' && id='$id'";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
$links = $row['links'];
include ('simple_html_dom.php');
$html = file_get_html($links);
$title1 = $html->find('li[id=row1-1]', 0)->plaintext; // with this
if ($html->find('li[id=row1-1]', 0)->plaintext == ('NEW'))
{
$output = preg_replace('/\d:\d+/', '', $title1);
$output = '<span id="title1">'.str_replace(array("\t", ' ', '<BR>','</BR>', 'AM','PM'), '', $output).'</span><br><br>';
$output = str_replace('<span id="title1"> ', '<span id="title1">', $output);
$output = str_replace(' "', ': ', $output);
$output = str_replace(' NEW', '', $output);
echo $output;
}
}
}
?>
Here's the HTML source:
<span id="title1">CBS This Morning: Saturday NEW</span><br><br>
In this case, I'm trying to look for a contain text at the end whether if the conttain text have a text called "NEW" then it will be replaced to an empty text. I tried to use it with if ($html->find('li[id=row1-1]', 0)->plaintext == ('NEW')) to look for a contain text before do something, but it doesn't check it out. I think I might have done it wrong, but I'm not really sure. Does anyone know how I can check for a contain text at the end of the text using if statement so I can replace the contain text to an empty text?
== does an exact match of the entire string. You need to use a function that searches for a substring:
if (strpos($title1, 'NEW') !== false) {
...
}
If you only want to recognize it at the end of the title, you can use a regular expression:
if (preg_match('/NEW$/', $title1) {
...
}
or you could use substr():
if (substr($title1, -3) == 'NEW') {
...
}

how to split the data into array?

I have stored the data in a mysql database, I want to know how I can split the data in each different array before output them in php?
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'myusername');
define('DB_PASSWORD', 'mypassword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
if($errflag)
{
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
echo implode('<br />',$errmsg_arr);
}
else
{
$qrytable1="SELECT id, mydata FROM mydb ";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
echo "<tr><td>".$row['mydata']."</td></tr>";
}
}
?>
On my PHP page it show something like this:
<tr><td>my data 1</td></tr><tr><td>my data 2</td></tr><tr><td>my data 3</td></tr><tr><td>my data 4</td></tr>
I want to split them up by turn into array and output them with each different array to something like this:
mydata1
mydata2
mydata3
mydata4
How I can split the data into array before I could output them in my php?
Are you looking for something like this?
(consider it as an example, but, as #BenM, consider using PDO)
$sql = 'SELECT * FROM country';
$query = mysql_query($sql);
$countries = array();
while ($country = mysql_fetch_assoc($query)){ $countries[] = $country; }
This will allow you to use
foreach ($countries as $country) {
echo $country['name'];
}
Your data is already in an array. That's what this line does:
while ($row = mysql_fetch_array($result1))
{
echo "<tr><td>".$row['mydata']."</td></tr>";
}
If you need to access the array outside of the while loop you could do this..
$myArray = array();
while ($row = mysql_fetch_array($result1)){
echo "<tr><td>".$row['mydata']."</td></tr>";
foreach($row as $key=>$val){
$myArray[$key] = $val;
}
}
actually.. assuming your query returns multiple rows it would be a multidimensional array..
$myArray = array();
$i = 0;
while ($row = mysql_fetch_array($result1)){
echo "<tr><td>".$row['mydata']."</td></tr>";
foreach($row as $key=>$val){
$myArray[$i][$key] = $val;
$i++;
}
}
If I am right than along with getting data in array you want to remove the space in between the data
try this
while ($row = mysql_fetch_array($result1))
{
echo "<tr><td>".$row['mydata']."</td></tr>";
$myArr[] = $row['mydata'];
}
foreach($myarr as $key=>$value)
{
$myArr[$key] = str_replace(" ","",$value);
}
str_replace will remove the spaces.
You can used this,
$db->setQuery($query);
$rows = $db->loadObjectList();
$i=0;
foreach($rows as $row){
//$row;
$image = json_decode($row->images);
// split code
$str = utf8_encode($row->introtext);
$order = array("<p>", "</p>", "\n", "\r");
$replace = '';
$introtext = str_replace($order, $replace, $str);
$introtext_split = explode("|", $introtext);
$data[0]->designation = preg_replace('#<br />?#', "\n", $introtext_split[0]);
$data[0]->description = preg_replace('#<br />?#', "\n\n", $introtext_split[1]);
$data[0]->small_description = preg_replace('#<br />?#', "\n\n", $introtext_split[2]);
}
In data used any tag, Or this tag replace using following section :
$str = utf8_encode($row->introtext);
$order = array("<p>", "</p>", "\n", "\r");
I think its useful to you.

Exporting Data from SQl to Excel Using PHP [duplicate]

This question already has answers here:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, object given [duplicate]
(2 answers)
Closed last year.
So the admin has the choice to choose what he want to export to excel by selecting checkboxes which i stored in col[]...
here's my code for exporting
session_start();
$HOST = 'localhost';
$USERNAME = 'root';
$PASSWORD = '';
$DB = 'fyp_db';
$link = mysqli_connect($HOST, $USERNAME, $PASSWORD, $DB);
if (is_array($_POST['col'])) {
$sql = "SELECT ";
foreach ($_POST['col'] AS $value) {
$sql .= "{$value}, ";
}
$sql = substr($sql, 0, -2);
$sql .= " FROM account, coursedetail, coursecategory";
/*echo "sql= " . $sql . "<br /><br />\n";*/
} else {
echo "No column was selected<br /><br />\n";
}
function cleanData(&$str) { $str = preg_replace("/\t/", "\\t", $str); $str = preg_replace("/\r?\n/", "\\n", $str); if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"'; }
$filename = "website_data.xls";
header("Content-Type: text/plain");
$flag = false;
$result = mysqli_query($link, $sql) or die(mysqli_error($link));
while(false !== ($row = mysql_fetch_assoc($result))) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
I got the error of..
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, object given in C:\xampp\htdocs\project\export_successful.php on line 28
why? :(
You're mixing up mysqli and mysql calls. The two libraries are NOT compatible and handles/statements returned by one cannot be used in the other.
$result = mysqli_query($link, $sql) or die(mysqli_error($link));
^--- note the 'i'
while(false !== ($row = mysql_fetch_assoc($result))) {
^--- note the LACK of an 'i'

PHP - bind_result to array

I'm using a prepared statement for a query that returns multiple results, which I'd want to have in an array. But bind_result won't work with arrays, so this is how I do it:
$read_items = $db->stmt_init();
$read_items->prepare("SELECT item_id, item_name FROM items");
$read_items->execute();
$read_items->bind_result($var1, $var2);
while ($read_items->fetch()) {
$item_id[] = $var1;
$item_name[] = $var2;
}
Is there clearer/better/more elegant way to put results into $item_id and $item_name arrays?
As it's visible from above, I'm using $var1 and $var2 like "intermediates" - and constantly have feeling there must be a better way.
Thanks.
I can't take credit for it, but the PHP manual has a nice solution (pasted verbatim):
<?php
// blah blah...
call_user_func_array(array($mysqli_stmt_object, "bind_result"), $byref_array_for_fields);
// returns a copy of a value
$copy = create_function('$a', 'return $a;');
$results = array();
while ($mysqli_stmt_object->fetch()) {
// array_map will preserve keys when done here and this way
$results[] = array_map($copy, $byref_array_for_fields);
}
You can use the Argument unpacking(...) operator.
$results = array(null, null);
$read_items->bind_result(...$results);
while ($read_items->fetch()) {
$item_id[] = $result[0];
$item_name[] = $result[1];
}
I really don't see the point of putting your item id's and item names in different arrays, you're breaking up a single object in two collections for ??? no reason . yes.
So, going back to this, what you should be doing is :
$items[$i]['var1']=$var1;
$items[$i]['var2']=$var2;
But this of course is still not very good.
The correct solution is to have a function that maps your mysqli result to an array so you can directly start working on that, whatever the query, here's mine - works in a few db's but not all are up to date at the moment :
function connectmysqldb($database,$host,$port,$user,$password){
global $conn;
$conn=mysqli_connect($host, $user, $password, $database,$port);
if (!$conn){
die('Error: Could not connect: ' . mysqli_connect_error());
}
return $conn;
}
function connectpgdb($database,$host,$port,$user,$password){
$connectString = 'host=' . $host . ' port=' . $port . ' dbname=' . $database . ' user=' . $user . ' password=' . $password;
$conn = pg_connect ($connectString);
if (!$conn)
{
die('Error: Could not connect: ' . pg_last_error());
}
return $conn;
}
function connectmssqldb($dbname,$host,$port,$uid,$pw){
$connectionOptions = array("UID"=>$uid,"PWD"=>$pw);
$conn = sqlsrv_connect( $host, $connectionOptions);
if (!$conn)
{
die('Error: Could not connect: ' . print_r( sqlsrv_errors(), true));
}
return $conn;
}
function sqlec($query,$dbtype,$dbname,$host,$port,$uid,$pw){
switch($dbtype){
default:
$res="Database Type not Recognized : $dbtype";
break;
case "mysql":
global $conn;
if(!isset($conn)){
$conn=connectmysqldb($dbname,$host,$port,$uid,$pw);
}
$clone=mysqli_multi_query($conn,$query);
if(!$clone){
die('Error: ' . mysqli_error($conn));
}else{
$clonearray=array();
$i=0;
if ($clone = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_assoc($clone)){
$clonearray[$i]=$row;
$i++;
}
mysqli_free_result($clone);
}
$res=$clonearray;
}
break;
case "postgres":
$conn=connectpgdb($dbname,$host,$port,$uid,$pw);
$clone=pg_query($conn,$query);
if (!$clone)
{
die('Error: ' . pg_last_error());
}else{
$clonearray=array();
$i=0;
while ($row = pg_fetch_row($clone))
{
$count = count($row);
$y = 0;
while ($y < $count)
{
$c_row = current($row);
$clonearray[$i][pg_field_name($clone,$y)] = $c_row;
next($row);
$y = $y + 1;
}
$i = $i + 1;
}
pg_free_result($clone);
pg_close($conn);
$res=$clonearray;
}
break;
case "mssql":
$conn=connectmssqldb($dbname,$host,$port,$uid,$pw);
$res=sqlsrv_query($conn,$query);
if (!$res)
{
die( "Error in statement execution.\n".print_r( sqlsrv_errors(), true));
}else{
$i=0;
$sqlsarray=array();
while( $row = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC))
{
if($i==0){
$arrk=array_keys($row);
}
$j=0;
while($j<count($arrk)){
$sqlsarray[$i][$arrk[$j]]=$row[$arrk[$j]];
$j++;
}
$i++;
}
$res=$sqlsarray;
}
break;
}
return $res;
}
function local_sqlec($query){
global $db_server;
global $db_db;
global $db_port;
global $db_username;
global $db_password;
return sqlec($query,"mysql",$db_db,$db_server,$db_port,$db_username,$db_password);
}
Which I use like this :
$r=local_sqlec("SELECT test1,test2 FROM test");
$i=0;
echo "last id =".($r[0]['test1'])."<br>";
echo "Row count =".($r[0]['test2'])."<br>";
while($i<$r[0]['test2']){
echo "inserted id =".($r[0]['test1']+$i)."<br>";
$i++;
}

Categories