mixing and matching mysql & mssql whileloop within an if case - php

Please take a look at the following code and tell me if there is a way around it.
if ($current_server_is_mysql):
while ($row = mysql_fetch_assoc($RS)) {
else:
while( $row = sqlsrv_fetch_array( $RS, SQLSRV_FETCH_ASSOC)){
endif:
Depending on the server I'm working with, I'd like to compile my records into the $RS recordset the proper/native way. If I can get pass this part, the rest should be all right cause both mysql and mssql $row can be tapped into the same way. For example, $row['fieldname'] will give me the field value whether the row was a mysql or mssql resource. So it all boils down to the above snippet failing.
The error I get points to the else: part in the above snippet.
Parse error: syntax error, unexpected T_ELSE in D:\Hosting\5291100\html\blueprint\pages\populate_migration_table.php on line 415
I can understand why I am getting this error.
But, I'm hoping you guys can offer a work-around it without me resorting to duplicate the entire while loop she-bang.

You've got some syntax mismatches, and putting your code in a function like this worked for me:
if ($current_server_is_mysql):
while ($row = mysql_fetch_assoc($RS)) {
ProcessThisRow($row);
}
else:
while( $row = sqlsrv_fetch_array( $RS, SQLSRV_FETCH_ASSOC)){
ProcessThisRow($row);
}
endif;
function ProcessThisRow ($row) {
/*Put your code in this function */
return true;
}

Related

Using php Session Variables To Fetch Data From MySQL Database

I'm trying to use php session variables in a SELECT Statement to fetch the data stored in a multiple array database.
However, I am facing some challenges with my code below:
<?php
if(!empty($_SESSION['array'])) {
if($_SESSION['array'] == 'arrayname') {
$query = "SELECT '{$_SESSION['option']}' FROM '{$_SESSION['array']}' WHERE '{$_SESSION['key']}'='".mysqli_real_escape_string( $link, '{$_SESSION['value']}')."'";
if ($result=mysqli_query( $link, $query)) {
while ($row = mysql_fetch_array($result)) {
echo $row['{$_SESSION['value']}'];
}
}
mysqli_close($link); // Closing Connection with Server
}
} ?>
Any attempt to fetch the data with the above code rather displays an error messages, like;
Parse error: syntax error, unexpected 'value' (T_STRING) in C:\xampp\htdocs\content\fetchData.php on line 5
I will be much grateful for a way out to deal with this challenge.
Thanks in advance!
For your query, get your variable first:
$value = mysqli_real_escape_string( $link, $_SESSION['value']);
Then use $value rather than try and embed like you have above.
You don't need the single quotes or the curly braces around $_SESSION when you are echoing the value. Just do this:
echo $row[$_SESSION['value']];
That should fix your current error, however you still have more issues with your code. Namely you are mixing mysql and mysqli functions, which won't work. Move your code over to mysqli completely.

Strange Illegal string offset in foreach from mysqli_fetch_array() and mysqli_fetch_assoc()

I am just testing out a data set I am looking to return from the DB.
I am running this in command line mode. When I var_dump() the data, I can see data being returned, but when I try to traverse the array, which has duplicate data in it, I get the warning message below and can not print the array item.
I am sure to some that is obvious to some, but I do not know why this is happening. I am sure I am doing something wrong here...but what?
Consider:
$link = mysqli_connect("localhost","username","password","mydatabase") or die("Error " . mysqli_error($link));
$query = "SELECT * FROM citizen_application";
$execute = $query or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($execute);
$data = mysqli_fetch_array($result); // also tried mysqli_fetch_assoc() and the issue persists
//display information:
//var_dump($data); //This show duplicates in the array returned???
foreach($data as $data_unit){
print_r($data_unit["dob"]."\r");
}
The warning in the logs:
Illegal string offset 'dob'
There seems to be no way to do this with a foreach() when running the script in command line mode. But I found a solution below that gives me what I was looking for:
while($data = mysqli_fetch_assoc($result)) {
print_r($data["dob"]."\n");
}
I noticed all the examples in the documentation where doing this way. I thought it was just a preference. It does not seem so. I hope this helps someone else, because this was quite irritating. You used to be able to do this easily with the previous mysql functions.
mysqli_fetch_array returns an array, you're traversing the array with the foreach, $data_unit will most likely be a single element and not an array... try just
foreach($data as $data_unit){
echo $data_unit."\r";
}
or use mysqli_fetch_assoc() and try
foreach($data as $fieldname => $data_unit){
echo "$fieldname = $data_unit\r";
}

MySQL time-exceeded error

I am currently working on an AJAX testing platform. I am experiencing stupid errors in PHP programming. Here is my code. I get the error: Maximum execution time of 30 seconds exceeded.
<?php
$resultFromJson;
$databaseConnection = mysql_connect("localhost", "root", "password");
if($databaseConnection)mysql_select_db("fastdata", $databaseConnection);
else echo mysql_error($databaseConnection);
if(isset($_GET['command'])){
switch($_GET['command']){
case "loadPeople":
{
$sqlCommandString = "SELECT * FROM `people` LIMIT 0 , 30";
$people = array();
$index = 0;
while($row = mysql_fetch_assoc(mysql_query($sqlCommandString))){
$people[$index] = $row;
$index++;
}
echo json_encode( $people );
}
break;
}
}
if(!isset($_GET['command']))echo json_encode( "Error#001" );
?>
What can I do to solve this error? What actually causes the error?
P.S. I am currently testing my PHP script directly in the browser with main.php?command=loadPeople as URL.
Execute the query, then loop through the results; don't try to re-execute the query in every iteration of the while
$resultset = mysql_query($sqlCommandString);
while ($row = mysql_fetch_assoc($resultset)) {
As you're clearly just learning the basics, I'd suggest that you learn to use MySQLi or PDO rather than the deprecated MySQL library... being able to use prepared statements and bind variables doesn't affect this query, but knowing how to use them will become more important later
i haven't written any PHP code in a while so this is a wild guess but in this piece of code:
while($row = mysql_fetch_assoc(mysql_query($sqlCommandString)))
you essentially have a neverending loop because $row will be assigned every time mysql_fetch_assoc(mysql_query($sqlCommandString)) returns a result
you need to save mysql_query($sqlCommandString) into a variable and then mysql_fetch_assoc from that variable in a loop

PHP PDO MySQL query prints blank

Going through a PHP MySQL tutorial and switching the PHP out for PDO; at any rate, my query is coming up blank.
$get_cat = $that->dbh->query("SELECT `cat_name`, `cat_desc` FROM `categories`");
if(isset($get_cat))
{
while($row = $get_cat->fetch(PDO::FETCH_ASSOC))
{
printf("
<tr>
<td>".$row['cat_name']." : ".$row['cat_desc']."</td>
</tr>
");
}
}
else
{
echo '<tr><td>return is false</td></tr>';
}
$That refers to:
include('db.php');
$that = new lib();
OLD:
So, why is my query blank? Before putting the die in it would return Boolean and give in an error in the loop with the die in it just comes up blank. The categories table has data in it and the page is refreshed on submission for new entries.
NEW:
Fatal error: Call to a member function fetch() on a non-object in C:\wamp\www\forum\create_category.php on line 36
Line 36 is the while loop line.
mysql_fetch_array is not PDO. You would need something like:
while($row = $get_cat->fetch(PDO::FETCH_ASSOC))
To get your rows.
Nor can you use mysql_error() to get the error. You could use for example $that->dbh->errorInfo() but you should look into exceptions for a more robust way to catch all errors.
Edit: You should check what the error is. Using isset is pointless as you have just assigned a value to it, so it will always be set.
You need to tell PDO to throw errors.
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$res = $that->dbh->query("SELECT cat_name, cat_desc FROM categories");
while($row = $res->fetch())
{
echo "<tr><td>$row[cat_name] : $row[cat_desc]</td></tr>\n";
}
run your code, read the error message and take appropriate action
Don't forget to add the first line into your db.php file, to make the setting permanent
Your query is incorrect -- is this what you're trying to do?
SELECT `categories`.`cat_name`, `categories`.`cat_desc` FROM `categories`
Hard to know without seeing you table structure.

custom function for mysqli queries

I'm trying my hand at custom functions in PHP in order to streamline a lot of stuff I'm otherwise doing manually. I'm damn new to custom functions so I'm not sure the limitations. Right now I'm trying to get data with MySQLi using custom functions Here's the code, and then I'll explain the issue:
function connect_db($db = 'db_username') {
iconv_set_encoding("internal_encoding", "UTF-8");
mb_language('uni');
mb_internal_encoding('UTF-8');
# $mysqli = new mysqli('host',$db,'password',$db);
if(mysqli_connect_errno())
{
die('connection error');
}
}
This one seems to be working fine. It's the next function I'm having more trouble with.
edit: Updated thanks to Jeremy1026's response
function do_query($db = 'default_db', $query) {
connect_db();
$result = $mysqli->query($query);
if(!$result){
trigger_error("data selection error");
}
while($row = $result->fetch_assoc()){
$result_array[] = $row;
}
return $result_array;
}
My host forces database names and usernames as the same, so if the db name is 'bob' the username to access it will be 'bob' as well, so that's why $db shows up twice in the connection.
The problem I'm having is that these two functions are in functions.php and being called from another page. I want to be able to pull the results from the query in that other page based on the column name. But I also need to be able to do this with formatting, so then maybe the while() loop has to happen on that page and not in a function? I want this to be as universal as possible, regardless of the page or the data, so that I can use these two functions for all connections and all queries of the three databases I'm running for the site.
God I hope I'm being clear.
Big thanks in advance for any suggestions. I've googled this a bit but it's tough to find anything that's not using obsolescent mysql_ prefixes or anything that's actually returning the data in a way that I can use.
Update: I'm now getting the following error when accessing the page in question:
Fatal error: Call to a member function query() on a non-object in /functions.php`
with the line in question being $result = $mysqli->query($query);. I assume that's because it thinks $query is undefined, but shouldn't it be getting the definition from being called in the page? This is that page's code:
$query = "SELECT * FROM `table`";
$myArray = do_query($db, $query);
echo $myArray['column_name'];
In your 2nd function you aren't returning any data, so it is getting lost. You need to tell it what to return, see below:
function do_query($db = 'default_db', $query) {
connect_db();
$result = $mysqli->query($query);
if(!$result){
trigger_error("data selection error");
}
while($row = $result->fetch_assoc()){
$result_array[] = $row;
}
return $result_array;
}
Then, when using the function you'll do something like:
$myArray = do_query($db, 'select column from table');
$myArray would then be populated with the results of your query.
This is a half-answer. The following single function works in place of the two.
function query_db($database, $new_query) {
$sqli = new mysqli('host', $database, 'password', $database);
$sqli->set_charset("utf8");
global $result;
if($result = $sqli->query($new_query)){
return $result;
}
}
By adding global $result I was able to access the results from the query, run from another page as
query_db("username","SELECT * FROM `column`");
while($row = $result->fetch_assoc()){
print_r($row);
}
It's more streamlined than I have without functions, but it's still not idea. If I have the connection to the database in another function, it doesn't work. If I try to put the while loop in the combined function, it doesn't work. Better than nothing, I guess.

Categories