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. :)
Related
I have this code:
$query="Select SUBJECT,NOTES from CAMPNOTIFICATION
where TYPE LIKE 'message_blackboard' AND VALIDAFTER <= GETDATE() AND (VALIDUNTIL >= GETDATE() OR VALIDUNTIL IS NULL)";
$encode = array();
//$query = strtr($query, array('{$raum}' => $raum));
$query_result = mssql_query($query);
while ($row = mssql_fetch_row($query_result))
{
$encode[] = $row;
$text = $row[1];
$text = str_replace("<br />","\n",$text);
$text = str_replace("<br>","\n",$text);
$text = str_replace("<br/>","\n",$text);
$text = str_replace("<p>","\n",$text);
$text = str_replace("\r","",$text);
$text = strip_tags($text);
$text = str_replace("\n","<br>",$text);
$text = str_replace("<br>\r<br>","",$text);
$text = str_replace("<br><br>","<br>",$text);
echo "<h2>" . $row[0] . "</h2>" . $text . "<br>";
}
I have to change the connections to the sqlsrv model. I managed to do it this way:
$query="Select SUBJECT,NOTES from CAMPNOTIFICATION
where TYPE LIKE 'message_blackboard' AND VALIDAFTER <= GETDATE() AND (VALIDUNTIL >= GETDATE() OR VALIDUNTIL IS NULL)";
//$params = array(SQLSRV_PHPTYPE_*);
$encode = array();
$query_result = sqlsrv_query($connection, $query);
if ($query_result === false){
die(print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_object($query_result))
{
//echo "Contenido de Row ". $row -> NOTES;
$encode[] = $row;
$text = $row -> NOTES;
$text = str_replace("<br />","\n",$text);
$text = str_replace("<br>","\n",$text);
$text = str_replace("<br/>","\n",$text);
$text = str_replace("<p>","\n",$text);
$text = str_replace("\r","",$text);
$text = strip_tags($text);
$text = str_replace("\n","<br>",$text);
$text = str_replace("<br>\r<br>","",$text);
$text = str_replace("<br><br>","<br>",$text);
echo "<h2>" . $row -> SUBJECT . "</h2>" . $text . "<br>";
}
But I need to keep the structure in which I use the position of the array instead of calling the object.
Does anyone know of any way? Thank you very much.
Solution:
Function mssql_fetch_row() is part of the MSSQL PHP extension (mssql_ functions) and fetches one row of data as a numeric array. If you want to get the data in similar way using PHP Driver for SQL Server (sqlsrv_ functions), you should use sqlsrv_fetch_array() with SQLSRV_FETCH_NUMERIC as second parameter value.
Your code should look like this:
<?php
....
while ($row = sqlsrv_fetch_array($query_result, SQLSRV_FETCH_NUMERIC)) {
$encode[] = $row;
// Additional code here ...
}
...
?>
Additional explanations:
If the SELECT statement returns more than one result set, you need to use sqlsrv_next_result() to make the next result of the specified statement active.
Example, using MSSQL extension:
<?php
// Connection
$server = "server\instance";
$database = "database";
$username = "username";
$password = "password";
$conn = mssql_connect($server, $username, $password);
mssql_select_db($database, $conn);
// Statement
$sql = "
SELECT [name], [age] FROM [dbo].[persons];
SELECT [name], [salary] FROM [dbo].[jobs];
";
$stmt = mssql_query($sql, $conn);
// Fetch data
do {
while ($row = mssql_fetch_row($stmt)) {
echo print_r($row, true);
}
} while (mssql_next_result($stmt));
// End
mssql_free_result($stmt);
mssql_close($conn);
?>
Example, using SQLSRV extension:
<?php
// Connection
$server = "server\instance";
$database = "database";
$username = "username";
$password = "password";
$info = array(
"Database" => $database,
"UID" => $username,
"PWD" => $password
);
$conn = sqlsrv_connect($server, $info);
// Statement
$sql = "
SELECT [name], [age] FROM [dbo].[persons];
SELECT [name], [salary] FROM [dbo].[jobs];
";
$stmt = sqlsrv_query($conn, $sql);
// Fetch data
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo print_r($row, true);
}
} while (sqlsrv_next_result($stmt));
// End
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>
Function equivalence:
The table below displays more information about the equivalence between the functions from each extension:
--------------------------------------------------------------------------------------
MSSQL PHP extension PHP Driver for SQL Server
--------------------------------------------------------------------------------------
mssql_fetch_assoc($stmt) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)
mssql_fetch_row($stmt) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)
mssql_fetch_array($stmt, MSSQL_ASSOC) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)
mssql_fetch_array($stmt, MSSQL_NUM) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)
mssql_fetch_array($stmt, MSSQL_BOTH) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_BOTH)
mssql_next_result($stmt) sqlsrv_next_result($stmt)
I am passing value from android using POST and run the query in SQL DB using PHP. I am always getting
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '' at line 1.
The code is working fine if i pass the values directly insted $_POST[].
I've gone through SO but no questions solved my problem. I tried with mysql_real_escape_string($searchTermBits) also but that doesn't worked.
PHP:
<?php
$username = "xxxx";
$password = "xxxx";
$host = "xxxx";
$database = "xxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$search = $_POST["deskey"];
$search = explode(" ", $search);
$commonwords = "a,an,and,I,it,is,do,does,for,from,go,how,the,etc,in,on,are";
$commonwords = explode(",", $commonwords);
foreach ($search as $value)
{
if (!in_array($value, $commonwords))
{
$query[] = $value;
}
}
$query = implode(" ", $query);
$searchTerms = explode(" ", $query);
$searchTermBits = array();
foreach ($searchTerms as $term)
{
$term = trim($term);
if (!empty($term))
{
$searchTermBits[] = "description LIKE '%$term%'";
}
}
$myquery = "SELECT * FROM `logins` WHERE " . implode(' OR ', mysql_real_escape_string($searchTermBits)) . "";
$query = mysql_query($myquery);
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);
?>
What changes can i make this code to work with $_POST[].
For some reason I am getting this notice in my code.
Variable $conn seems to be uninitialized
I don't understand why I'm seeing this notice. I think I'm including my include in the right place.
Class Calendar {
public function show() {
include './includes/dbconn.php';
include_once './includes/functions.php';
for ($i=0; $i<$weeksInMonth; $i++) {
// Create days in a week
for ($j=1;$j<=7;$j++) {
$cal_date = (string)$this->currentDate;
$tutor_date = display_tutor_schedule($conn,$cal_date);
if(isset($tutor_date[$j]['date'])) {
$content .= $this->_showDay($i*7+$j, $tutor_date[$j]['date']);
}
else {
$content .= $this->_showDay($i*7+$j, 0);
}
}
$content .="</tr>";
}
}
}
My $conn variable is coming from include './includes/dbconn.php';. Since I am not getting any PHP database error, such as "Not connected to the database" or something like that, I assume that my connection is right.
functions.php
function display_tutor_schedule($conn,$tutor_date) {
$query = "select * from [dbo].[TUTOR_SCHEDULE] "
. "LEFT JOIN [dbo].[TUTOR] "
. "ON [dbo].[TUTOR_SCHEDULE].tutor_id = [dbo].[TUTOR].tutor_id "
. "LEFT JOIN [dbo].[STATUS] "
. "ON [dbo].[STATUS].status_id = [dbo].[TUTOR_SCHEDULE].status_id "
. "WHERE [dbo].[TUTOR_SCHEDULE].date = '$tutor_date' " ;
$stmt = sqlsrv_query($conn, $query);
$i = 0;
$appt_detail = array();
while ($row = sqlsrv_fetch_array($stmt)) {
$appt_detail[$i]['date'] = $row['date'];
$appt_detail[$i]['t_shedule_id'] = $row['t_shedule_id'];
$appt_detail[$i]['start_time'] = $row['start_time'];
$appt_detail[$i]['end_time'] = $row['end_time'];
$appt_detail[$i]['tutor_fname'] = $row['tutor_fname'];
$appt_detail[$i]['tutor_lname'] = $row['tutor_lname'];
$appt_detail[$i]['status_name'] = $row['status_name'];
$appt_detail[$i]['status_id'] = $row['status_id'];
$i++;
}
return $appt_detail;
}
my_class.php
<?php
$calendar = new Calendar();
echo $calendar->show();
?>
dbconn.php
$serverName = "myserver";
$connectionInfo = array("Database" => "my_database", "UID" => "user", "PWD" => "pwd");
$conn = sqlsrv_connect($serverName, $connectionInfo);
If you are using NetBeans or PhpStorm, then this might be IDE issue.
Check https://netbeans.org/projects/php/lists/users/archive/2013-03/message/49 and PhpStorm warning PHP variable might not have been defined
However, it is advisable that you show us the files you include to check them.
Don't use includes or global for your variables. It's bad.
Instead you should be using classes:
class Database {
private $conn;
public function __construct(){
$serverName = "myserver";
$connectionInfo = array("Database" => "my_database",
"UID" => "user",
"PWD" => "pwd");
$this->conn = sqlsrv_connect($serverName, $connectionInfo);
}
public function get_connection(){
return $this->conn;
}
}
Calendar.php
class Calendar
{
private $conn;
public $weeksInMonth;
function __construct($conn){
$this->conn = $conn;
}
public function show()
{
$content = "";
for ($i = 0; $i < $this->weeksInMonth; $i++) {
//Create days in a week
for ($j = 1; $j <= 7; $j++) {
$cal_date = (string)$this->currentDate;
$tutor_date = display_tutor_schedule($cal_date);
if (isset($tutor_date[$j]['date'])) {
$content .= $this->_showDay($i * 7 + $j, $tutor_date[$j]['date']);
} else {
$content .= $this->_showDay($i * 7 + $j, 0);
}
}
$content .= "</tr>";
}
return $content;
}
function display_tutor_schedule($tutor_date)
{
$query = "select * from [dbo].[TUTOR_SCHEDULE] "
. "LEFT JOIN [dbo].[TUTOR] "
. "ON [dbo].[TUTOR_SCHEDULE].tutor_id = [dbo].[TUTOR].tutor_id "
. "LEFT JOIN [dbo].[STATUS] "
. "ON [dbo].[STATUS].status_id = [dbo].[TUTOR_SCHEDULE].status_id "
. "WHERE [dbo].[TUTOR_SCHEDULE].date = '$tutor_date' ";
$stmt = sqlsrv_query($this->conn, $query);
$appt_detail = array();
while ($row = sqlsrv_fetch_array($stmt)) {
$appt_detail[] = $row;
}
return $appt_detail;
}
}
Usage
$db = new Database();
$conn = $db->get_connection();
$calendar = new Calendar($conn);
$calendar->weeksInMonth = 4;
echo $calendar->show();
Since the variable is first initialized in the dbconn.php, the IDE might not recognize it. Insert
$conn = null;
after the line
public function show() {
I am trying to fetch the values from mysql table based on the certain values. below is my php script where i am getting json values from android and then parse it to array the passing array in to the select query.
So, when i open the script in IE i am getting values as null instead of []. What is wrong here.
php
<?php
$username = "xxxxx";
$password = "xxxxxx";
$host = "localhost";
$database="xxxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$JSON_received = $_POST["JSON"];
$obj = json_decode($JSON_received,true);
foreach ($obj['ilist'] as $key => $value)
{
//echo "<br>------" . $key . " => " . $value;
$im[] = $value;
}
$myquery = "SELECT * FROM Movies WHERE im_rat IN ('$im')";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
Can anyone help ?
I have two rows in my MySQL data that I would like to have code echoed only if the MySQL row data is equal to '1' (as opposed to '0'). Here's the code so far, which seems to have some severe errors:
$query = "SELECT 162, 164 FROM search WHERE title = $title";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row()) {
if ($row["162"] = 1) {
echo '<div id="162link">1.6.2</div>';
}
}
if ($row["164"] = 1) {
echo '<div id="162link">1.6.2</div>';
}
}
}
$result->close();
}
$mysqli->close();
As it says in the code above the two rows are "162" and "164" in the database.
Use:
if ($row["162"] == 1)
Instead of:
if ($row["162"] = 1)
and:
if ($row["164"] == 1)
I tried for you something like this if it gives you some idea:
$host = "localhost";
$user = "myusername";
$pass = "mypassword";
$database = "WorldEngine";
$mysqli = new mysqli($host, $user, $pass, $database);
$title = "My Good News";
$query = "SELECT `162`, `164` FROM search WHERE title = '$title';";
if ($result = $mysqli->query($query)) {
$i = 0;
while ($row = $result->fetch_row()) {
if ($row["162"] == 1) {
echo '<div id="162link' . $i . '">1.6.2</div>';
}
if ($row["164"] == 1) {
echo '<div id="164link' . $i . '">1.6.4</div>';
}
$i++;
}
$result->free();
}
$mysqli->close();
The index $i is appended to the div ID in order to produce unique DOM element ID's in the HTML document. I would also suggest you to change your numerical column names into alphabet-starting names like c162, c164, ...
Hope this will help you.