I can't seem to be able to place the resultset into an array and then use print_r to print out the array. Here's the script:
<?php
require( 'wp-load.php' );
$local = 'xxx';
$user = 'xxx';
$pass = 'xxx';
$data = 'xxx';
$testConnection = mysqli_connect($local,$user,$pass, $data);
if (!$testConnection) {
die('Error: ' . mysqli_connect_errno() . PHP_EOL);
}
echo 'Database connection working!';
global $wpdb;
$result = $wpdb->get_results ( "SELECT * FROM $wpdb->options" );
/* this is commented out but works
foreach ( $result as $row ) {
echo $row->option_id.'<br>';
}
*/
//PART NOT WORKING
$results = [];
while($row = mysqli_fetch_array($result,MYSQLI_NUM))
{
echo "hello"; //never executes?????
$results[] = $row;
}
//$results has all that you need
print_r($results); //empty array???
$testClosed = mysqli_close($testConnection);
if ($testClosed) {
echo "closed";
}
?>
while($row = mysqli_fetch_array($result,MYSQLI_NUM))
{
echo "hello"; //never executes?????
$results[] = $row;
}
Try removing the while statement out of there. Array is going to be given to you with mysqli_fetch_array . So just write it like this :
$row = mysqli_fetch_array($result,MYSQLI_NUM);
$results[] = $row;
You could just access the indexes with $row[...] but still, up to you.
On the other hand :
On the documentation for the function there is such statement :
Return Value: Returns an array of strings that corresponds to the fetched row. NULL if there are no more rows in result-set
. So you might be calling a invalid table from your DB.
Related
In my script i am fetching data from database and storing it in array and output it in json. Everything is going correct just the first array I am getting is null and then the second array has the correct data. I don't understand why am I getting first null array.
My problem solves if I get correct result in array without the null array.
Here is the output I am getting
[[],{"url":"example.com\/sign_pdf\/PDFSign.pdf","name":"PDFSign.pdf","signer":"aman","sequence":"1","message":"Hello","flag":"0"}]
I don't need First null array. Why the hell am I getting that.
Here is the code.
if(($_GET['action'])&&($_GET['username'])&&($_GET['key'])) {
$select = $_GET['action'];
$username =$_GET['username']; //no default
$key= $_GET['key'];
if($key=='abcxyz'){
if($select=='select'){
/* connect to the db */
$connect = mysqli_connect('localhost','root','')or die("Couldn't connect to database!");
mysqli_select_db($connect,'sign') or die ("Couldn't find database");
$query ="SELECT * FROM path WHERE signer ='$username' ";
$result = mysqli_query($connect,$query);
$numrows=mysqli_num_rows($result);
$posts[] = array();
if($numrows!==0) {
while($row = mysqli_fetch_array($result)) {
$post['url'] = $row['url'];
$post['name'] = $row['name'];
$post['signer'] = $row['signer'];
$post['sequence'] = $row['sequence'];
$post['message'] = $row['message'];
$post['flag'] = $row['flag'];
array_push($posts, $post);
}
header('Content-type: application/json');
echo json_encode($posts);
}
}
}
}
You are creating array(array()) by $posts[] = array();
Replace this:
$posts[] = array();
with
$posts = array();
$posts = array(); will create a null array() and not array(array())
Instead of
$posts[] = array();
Which assigns an array to the first element of $posts, use
$posts = array();
Which initialises the variable, what I think you are trying to do.
Your $posts[]=array() should be like $posts=array() And append $post into $posts using $posts[]=$post .
$posts = array();
if ($numrows !== 0) {
while ($row = mysqli_fetch_array($result)) {
$post = array();
$post['url'] = $row['url'];
$post['name'] = $row['name'];
$post['signer'] = $row['signer'];
$post['sequence'] = $row['sequence'];
$post['message'] = $row['message'];
$post['flag'] = $row['flag'];
$posts[] = $post;
}
}
You should remove the $posts array. The array_push($posts, $post) is basically taking your empty $posts array and adding the $post array to it.
I'm trying to get the result of a stored procedure in MySQL into an array with use of php. The code I have:
function get_all_uzovi($dbc) {
//$query = "SELECT diagnose_id, diagnose_code, specialisme_agb_code_fk
// FROM tbl_diagnoses
// WHERE specialisme_agb_code_fk = '$var_chosen_specialism'
// ORDER BY diagnose_code ASC";
$result = mysqli_query($dbc,"CALL spGetUzovi");
//WHAT DOES NOT WORK:
//$data = array();
//while ( $row = $result->fetch_assoc() ) {
// $data[] = $row;
//}
//return json_encode($data);
//WHAT DOES WORK:
while ($row = mysqli_fetch_array($result)){
echo $row[0] . " - " . + $row[1];
}
}
The code under "//WHAT DOES NOT WORK" is what I need: the result as a json format. For some reason it gives me nothing..
The code under "//WHAT DOES WORK", does work, but this is not what I want.
the code for the sp:
CREATE DEFINER=`ziekenh3`#`localhost` PROCEDURE `spGetUzovi`()
NO SQL
SELECT *
FROM tbl_uzovi
the code that I use when working with queries (which does work) instead of sp:
function get_diagnoses($dbc,$var_chosen_specialism) {
$query = "SELECT diagnose_id, diagnose_code, specialisme_agb_code_fk
FROM tbl_diagnoses
WHERE specialisme_agb_code_fk = '$var_chosen_specialism'
ORDER BY diagnose_code ASC";
$result = mysqli_query($dbc,$query);
$data = array();
//while ( $row = $result->fetch_assoc() ) {
while ( $row = mysqli_fetch_assoc($result) ) {
$data[] = $row;
}
return json_encode($data);
}
Any thoughts?
Does this work?
function get_all_uzovi($dbc) {
$result = mysqli_query($dbc,"CALL spGetUzovi");
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
return json_encode($data);
}
I Solved it. A bit of a stupid problem: there where some fields in the result set that contained characters like: , ( . etc. I don't think json likes this..
When I did a SELECT * FROM on another table it worked. So, my code that works now is:
function get_all_uzovi($dbc) {
$q = "CALL spGetUzovi";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_assoc($r)) {
$data[] = $row;
}
return json_encode($data);
}
I'm sorry for the inconvenience!
I have a function in PHP and I would like to export an array from my MYSQL Database and then use the rows in a loop to do some stuff with them.
$DB_Server = "XXX.XXX.XXX.XXX";
$DB_Username = "XXXX";
$DB_Password = "XXXXX";
$DB_Database = "XXXXX";
$conn = new mysqli($DB_Server, $DB_Username, $DB_Password, $DB_Database);
$query = "Select Name, Wert from test.DBPBX";
function show(array $options) {
global $showresult, $master, $conn, $query;
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
$cnlongname = $row["Name"];
$usercontent = $row["Wert"];
$cn = $cnlongname;
$options['config']->value = 1;
$config = $options["config"]->value;
$show = new SimpleXMLElement("<show/>");
$user = $show->addChild("user");
$user->addAttribute("cn", $cn);
if ($config)
$user->addAttribute("config", "true");
print "cmd: " . htmlspecialchars($show->asXML()) . "\n";
$showresult = $master->Admin($show->asXML());
print "result: " . htmlspecialchars($showresult) . "\n";
$mod = "text=".$usercontent;
$modify = new SimpleXMLElement("$showresult");
$user = $modify->user;
$path = explode("/device/hw/", $mod);
$srch = $user;
$nsegments = count($path);
$i = 1;
foreach ($path as $p) {
if ($i == $nsegments) {
// last part, the modification
list($attr, $value) = explode("=", $p);
$srch[$attr] = $value;
} else {
$srch = $srch->$p;
}
$i++;
}
$modify = new SimpleXMLElement("<modify>" . $user->asXML() . "</modify>");
print "cmd: " . htmlspecialchars($cmd = $modify->asXML()) . "\n";
// do it
$result = $master->Admin($cmd);
print "result: " . htmlspecialchars($result);
}
}
For $cn I would like to use $cnlongname (or $row["Name"]). And for $mod I would like to use $usercontent (or $row["Wert"]). However when I would like to use it I get an error after the first loop:
Warning: mysqli_fetch_assoc() expects parameter 1 to be
mysqli_result, string given in /sample.php on
line 175
Line 175 is:
while ($row = mysqli_fetch_assoc($result)) {
Can you please help me?
Inside your while loop you overwrite your result, therefore you lose your mysql result and cannot query it any more.
// do it
$result = $master->Admin($cmd);
Use a different variable there. :)
I try to query a SQL database and save data into a custom array, but the array always repeats last row*num rows on database.
php:
class Cst
{
public $ParagemID;
public $Designacao;
public $DecimalDeGrauY;
public $DecimalDeGrauX;
}
require 'config.php';
$dsn = array( "Database"=>"$database", "UID"=>"$username", "PWD"=>"$password", "LoginTimeout"=> 60);
$db = sqlsrv_connect($server, $dsn);
$sql = "SELECT ParagemID, Designacao, DecimalDeGrauY, DecimalDeGrauX FROM adoParagens WHERE ParagemID >= 20000";
$stmt = sqlsrv_query($db, $sql);
$locations = new Cst();
$location=array();
$i=0;
while( $row = sqlsrv_fetch_object($stmt))
{
$locations->ParagemID = $row->ParagemID;
$locations->Designacao = $row->Designacao;
$locations->DecimalDeGrauY = $row->DecimalDeGrauY;
$locations->DecimalDeGrauX = $row->DecimalDeGrauX;
//echo json_encode($locations);
$location[$i]= $locations;
$i++;
}
echo json_encode($location);
It looks like you're always working with same instance of that object. Updating it for each row will also update all copies of it, as they are in fact the same object.
Try this instead.
...
$location = array();
while( $row = sqlsrv_fetch_object($stmt) )
{
$data = array();
$data['ParagemID'] = $row->ParagemID;
$data['Designacao'] = $row->Designacao;
$data['DecimalDeGrauY'] = $row->DecimalDeGrauY;
$data['DecimalDeGrauX'] = $row->DecimalDeGrauX;
$location[]= $data;
}
...
try using a 2 dimensional array.
$i=0;
while( $row = sqlsrv_fetch_object($stmt))
{
$location[$i][$locations->ParagemID/*put your val*/] = $row->ParagemID;
$location[$i][$locations->Designacao/*put your val*/] = $row->Designacao;
$location[$i][$locations->DecimalDeGrauY/*put your val*/] = $row->DecimalDeGrauY;
$location[$i][$locations->DecimalDeGrauX/*put your val*/] = $row->DecimalDeGrauX;
//echo json_encode($locations);
$i++;
}
MySql query returns me a multi-dimensional array :
function d4g_get_contributions_info($profile_id)
{
$query = "select * from contributions where `project_id` = $profile_id";
$row = mysql_query($query) or die("Error getting profile information , Reason : " . mysql_error());
$contributions = array();
if(!mysql_num_rows($row)) echo "No Contributors";
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[$cnt]['user_id'] = $fetched['user_id'];
$contributions[$cnt]['ammount'] = $fetched['ammount'];
$contributions[$cnt]['date'] = $fetched['date'];
$cnt++;
}
return $contributions;
}
Now I need to print the values in the page where I had called this function. How do I do that ?
change the function like this:
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[] = array('user_id' => $fetched['user_id'],
'ammount' => $fetched['ammount'],
'date' => $fetched['date']);
}
return $contributions;
Then try below:
$profile_id = 1; // sample id
$result = d4g_get_contributions_info($profile_id);
foreach($result as $row){
$user_id = $row['user_id']
// Continue like this
}