I'm having some problems when returning a large number of rows from SQL Server using PHP + Datatables. My code is using one main loop then some "subloops".
Sometimes, when the number of lines gets up to 1000+ the execution is aborted and the error MSSQL: SQLSTATE[] (null) (severity 0) is shown.
Connection function:
function pdo_mssql($sql){
$host = ***;
$user = ***;
$pass = ***;
$db = ***;
try {
$PDO = new PDO( 'dblib:host=' . $host . ';dbname=' . $db, $user, $pass );;
}
catch ( PDOException $e ) {
echo 'MSSQL error: ' . $e->getMessage(); exit;
}
$result = $PDO->query( $sql );
if (is_array($result)){
$row = $result->fetchAll( PDO::FETCH_ASSOC );
}else{
$row = $result;
}
return $row;
}
Example of the script where the error occurs:
$sql = "SELECT ....";
$return = pdo_mssql($sql);
foreach ($return as $row){
$sql2 = "SELECT ...."
$return2 = pdomssql($sql2);
foreach ($return2 as $row2){
// Do something
}
$sql2 = "SELECT ...."
$return2 = pdomssql($sql2);
foreach ($return2 as $row2){
// Do something
}
$sql2 = "SELECT ...."
$return2 = pdomssql($sql2);
foreach ($return2 as $row2){
// Do something
}
// Show results
}
Does anyone have any suggestion to fix it?
Thanks
Please check the code, $return2 is not being assigned in inner loop. May be you want to do
$sql2 = "SELECT ...."
$return2 = pdomssql($sql2);
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 can get the correct code to work, but i want to be able to use objects and methods, which doesn't work. The same entry in the database is repeated until the query crashes. I saw other people that had queries inside of the while statement, but i thought that the method i am using should only query the statement once, but im likely wrong. Thanks.
<?php
include '/functions/MySQL.php';
$MySQL = new MySQL;
$con = mysqli_connect("host","user","password","db");
$result = mysqli_query($con,"SELECT * FROM reportLogger WHERE Moderator='jackginger'");
while($row = mysqli_fetch_array($MySQL->getReports('jackginger'))) {
$time = $row['Time'];
$moderator = $row['Moderator'];
$reason = $row['Reason'];
// Now for each looped row
echo "<tr><td>".$time."</td><td>".$moderator."</td><td>".$reason."</td></tr>";
}
?>
Seperate class
public function __construct(){
$this->con = mysqli_connect("localhost","root","pass","Minecraft");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
public function getUUID($username) {
$result = mysqli_query($this->con,"SELECT UUID FROM loginLogger WHERE Username='" . $username . "'");
return mysqli_fetch_array($result)[0];
}
public function getReports($username) {
$result = mysqli_query($this->con,"SELECT * FROM reportLogger WHERE UUID='" . $this->getUUID($username) . "'");
return $result;
}
Each time you call while($row = mysqli_fetch_array($MySQL->getReports('jackginger'))) you are making a new query, so it's fetching the samething over and over again.
a solution could be:
<?php
include '/functions/MySQL.php';
$MySQL = new MySQL;
$con = mysqli_connect("host","user","password","db");
$result = mysqli_query($con,"SELECT * FROM reportLogger WHERE Moderator='jackginger'");
$store = $MySQL->getReports('jackginger');
while($row = mysqli_fetch_array($store)) {
$time = $row['Time'];
$moderator = $row['Moderator'];
$reason = $row['Reason'];
// Now for each looped row
echo "<tr><td>".$time."</td><td>".$moderator."</td><td>".$reason."</td></tr>";
}
?>
I have to make a web app that gets information from my database, that gets its info from an API). Then I have to show items under certain conditions.
But when I try to add the data from the API, I got a strange message:
Notice: Trying to get property of non-object in c:\xampp\htdocs\IMP03\inleveropdracht3\libs\php\function.php on line 21
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\IMP03\inleveropdracht3\libs\php\function.php on line 21
Here is my PHP code:
<?php
require_once 'settings.php';
$mysqli = mysqli_connect($db_host, $db_user, $db_password, $db_database);
if (mysqli_connect_error()) {
echo mysqli_connect_error($mysqli) . "We are not able to connect to the online database";
}
jsondecode($mysqli);
if (isset($_GET['club']) && !empty($_GET['club'])) {
jsondecode($mysqli);
} else if (isset($_GET['thuisPoint']) && !empty($_GET['thuisPoint']) && ($_GET['uitPoint']) && ($_GET['uitPoint'])) {
updatePoints($mysqli);
} else {
getWedstrijd($mysqli);
}
function jsondecode($mysqli) {
$apiLink = 'http://docent.cmi.hr.nl/moora/imp03/api/wedstrijden?club=';
// $club = $_GET['club'];
$data = json_decode(file_get_contents($apiLink . "Ajax"));
foreach ($data->data as $info) {
$thuisClub = $info->homeClub;
$uitClub = $info->awayClub;
addWestrijden($mysqli, $thuisClub, $uitClub);
}
}
//querys
function addWestrijden($mysqli, $thuisClub, $uitClub) {
$query = "INSERT INTO wedstrijd VALUES(null, '$thuisClub', '$uitClub')";
$resultAddWedstrijd = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
getWedstrijd($mysqli);
}
function getWedstrijd($mysqli) {
$query = "SELECT * FROM wedstrijd ORDER BY thuisClub DESC";
$resultGetWedstijd = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
while ($result = mysqli_fetch_assoc($resultGetWedstijd)) {
$rows [] = $result;
}
header("Content-Type: application/json");
echo json_encode($rows);
exit;
}
function updatePoints($mysqli) {
$id = $_GET['id'];
$thuisPoints = $_GET['thuisPoint'];
$uitPoints = $_GET['uitPoint'];
$query = "UPDATE wedstrijd "
. "SET thuisPunt = '$thuisPoints', uitPunt = '$uitPoints') "
. "WHERE id = '$id'";
mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
getWedstrijd($mysqli);
}
I did modify it a bit so it would add data from the API. I really would appreciate it if someone could help me.
Change your foreach to:
foreach ($data as $data => $info)
I have multiple record(s) in PHPMYADMIN and now i am trying to fetch those record(s) using PHP Code, but always i am getting Array ( ) 1 whenever i run my php script using Localhost, however i have 5 rows in table.
Please see below code:
<?php
$objConnect = mysql_connect("localhost","root","");
$objDB = mysql_select_db("mydatabase");
$strMemberID = $_POST["sMemberID"];
$strSQL = "SELECT * FROM order_details WHERE
MemberID = '".mysql_real_escape_string($strMemberID)."' ORDER BY OrderID DESC ";
$objQuery = mysql_query($strSQL);
while($obResult = mysql_fetch_assoc($objQuery))
{
$arr = array();
$arr["OrderID"] = $obResult["OrderID"];
$arr["ItemDetails"] = $obResult["ItemDetails"];
}
mysql_close($objConnect);
echo print_r($arr);
?>
change your code in while loop.
declare $arr outside the loop. declaring array inside loop will clear it before initializing. thats why you are getting a single row in each run.
$arr = array();
while($obResult = mysql_fetch_assoc($objQuery))
{
$arr["OrderID"] = $obResult["OrderID"];
$arr["ItemDetails"] = $obResult["ItemDetails"];
}
Also, to view array elements use echo json_encode($arr) or var_dump($arr) or print_r($arr);
it will definitely work for you
It's not directly an answer to your question but while you're at it try to use PDO and prepared statements
$strMemberID = $_POST["sMemberID"];
$strSQL = 'SELECT * FROM order_details WHERE MemberID = ? ORDER BY OrderID DESC';
try {
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF8', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = $db->prepare($strSQL);
$query->execute(array($strMemberID));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo 'Exeption: ' .$e->getMessage();
$result = false;
}
$query = null;
$db = null;
var_dump($result);
You may like it.
Using the script below, I am trying to execute two queries which store the output from each stored-procedure in two arrays.
The first array is being populated with data while the second is remaining empty. However, if I edit the script to only process the second stored-procedure, this works fine.
Can anybody let me know what I'm doing wrong please?
<?php
$host = 'xxx.xxx.xxx.xxx';
$user = 'xxxx';
$password = '';
$dbName = 'xxxxx';
$dbh = new PDO("mysql:host=$host;dbname=$dbName", $user, $password);
if (!$dbh)
{
die("Error While Connecting to Database");
}
$query1 = 'CALL getRowSet1';
$query2 = 'CALL getRowSet2';
try
{
$rowSet1 = $dbh->prepare($query1);
$rowSet1->execute();
$rowSet2 = $dbh->prepare($query2);
$rowSet2->execute();
}
catch (PDOException $e)
{
echo $e->getMessage();
die();
}
$results_1 = array();
$results_2 = array();
while ($result1 = $rowSet1->fetch(PDO::FETCH_ASSOC))
{
$results_1[] = $result;
}
while ($result2 = $rowSet2->fetch(PDO::FETCH_ASSOC))
{
$results_2[] = $result;
}
var_dump($results_1, $results_2);
Why not just use the pdo::fetchAll method?
$results_1 = $rowSet1->fetchAll(PDO::FETCH_ASSOC);
$results_2 = $rowSet2->fetchAll(PDO::FETCH_ASSOC);
That could take the place of both your while loops.
Your second while loop appends $result instead of $result2 to $results_2
I think it should be:
while ($result1 = $rowSet1->fetch(PDO::FETCH_ASSOC))
{
$results_1[] = $result1;
}
while ($result2 = $rowSet2->fetch(PDO::FETCH_ASSOC))
{
$results_2[] = $result2;
}