Get column information from results of mysql query in php? - php

I am trying to print out the column headers for any query entered. I have other code that connects to the database and actually prints the results, but I am having trouble with the line
'$result .= $heading->name;'
I keep getting this error:
'Catchable fatal error: Object of class mysqli_result could not be converted to string in...'
Could someone explain what the problem is? According to the php manual this should give me the right information. I am fairly new to php though, so if you improve the code could you please explain how you did it?
I have the following code so far that gets a result from a query:
$result = mysqli_query($conn,$query);
if($result){
if( mysqli_num_rows($result)>0){
$columnNo = mysqli_num_fields($result);
for($i=0;$i<$columnNo;$i++){
$heading = mysqli_fetch_field_direct($result,$i);
$result .= $heading->name;
}
}
}

$result is an object being used by mysqli. Then you try to append a string onto the end of it.
Just use a different variable name besides $result which will be a string in which you will collect the names of your columns. Or you might save the names in an array like this:
$var[] = $heading->name;

since $result is an object you are using for executing the query, i won't be able to store any other data coming from db. you have to take another variable (say $variable) to store the data coming from db. Follow the below code:
$result = mysqli_query($conn,$query);
$variable=''; // add this
if($result){
if( mysqli_num_rows($result)>0){
$columnNo = mysqli_num_fields($result);
for($i=0;$i<$columnNo;$i++){
$heading = mysqli_fetch_field_direct($result,$i);
$variable .= $heading->name; //modify here
}
}
}
I hope this will solve the issue..

Related

PHP variable is not working with WHERE clause

My query is not working when I use the variable in the WHERE clause. I have tried everything. I echo the variable $res, it shows me the perfect value, when I use the variable in the query the query is not fetching anything thus mysqli_num_rows is giving me the zero value, but when I give the value that the variable contains statically the query executes perfectly. I have used the same kind of code many times and it worked perfectly, but now in this part of module it is not working.
Code:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
As discussed in the comment. By printing the query var_dump($query), you will get the exact syntax that you are sending to your database to query.
Debugging Tip: You can also test by pasting the var_dump($query) value in your database and you will see the results if your query is okay.
So update your query syntax and print the query will help you.
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
Hope this will help you and for newbies in future, how to test your queries.
Suggestion: Also see how to write a mysql query syntax for better understanding php variables inside mysql query
The problem is the way you're using $res in your query. Use .$res instead. In PHP (native or framework), injecting variables into queries need a proper syntax.

Moving Query to MySQLi

I'm updating some old code that has deprecated MySQL functions. But for some reasons I cannot get all the results from the column. The strange part is that if I run the query directly on the server I get all results fine. So this is an issue with PHP getting the results, not the MySQL server or my query.
Here is the new and old code:
My current updated code:
$sql = "SELECT user, monitor FROM users WHERE `status` = 'y'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// This works. It shows all results
echo $row["user"];
// This does not work! Only shows one result:
$account= $row["user"];
}
else {
echo 'No results';
}
When I use that query directly on DB server, I get all results. So the SQL query is correct. I actually also get all results as well in PHP if I echo the row directly like:
echo $row["user"];
But for some reason when I try to use it with a PHP with variable it only lists one user result.
In the past I used this but the mysql_fetch_array function is now deprecated
while ($row = mysql_fetch_array($result)) {
array_push($data, $row["user"]);
}
foreach($data as $value) {
$account = $value
}
I cannot use my previous code anymore as those MySQL functions are obsolete today. I need to write the results into a file and my old method worked fine. The new one using mysqli does not.
Any suggestions?
You just need to add one of these [, and one of these ].
$account[] = $row["user"];
// ^^ right here.
$account= $row["user"]; means you're storing the value of $row["user"] in $account each time the loop executes. $account is a string, and it gets a new value each time.
$account[] = $row["user"]; means you're appending each value of $row["user"] to an array instead.
You should not use array_push for this. It's overkill for appending a single value to an array. And if the array isn't defined beforehand, it won't work at all.

php array to string conversion odbc_exec count

i'm still new towards php but after searching through multiple topics i can't seem to figure this one out.
$query2 = "SELECT COUNT(MAP_CODE2) FROM TCODE_MAPPING WHERE MAP_CODE2 = 'ABC123'";
$result2 = odbc_exec($connect,$query2);
echo $result2;
i have a query above that i'd like to use to get the total number of rows within the query that i've set, however for some reason i keep getting hit by the error
Array to string conversion in /var/www/html/xxx.php on line 85
Would highly appreciate if anyone could help out on what i'm doing wrong. Thank you!
Problem is:-
You are trying to echo a result-set object of array type.
Solution (check the code comments):-
$query2 = "SELECT COUNT(MAP_CODE2) AS MYCOUNT FROM TCODE_MAPPING WHERE MAP_CODE2 = 'ABC123'"; // given a name to the count
$result2 = odbc_exec($connect,$query2); //prepare and execute query
while (odbc_fetch_row($result2)) { //iterate over result-set object
echo odbc_result($result, "MYCOUNT"), "\n"; // echo count
}
What is happening here is you are echoing an array object type that is also a resource type and php echo only string and other primitive type variables.
so you need to use a loop to access the row or to get row count and access row just use a foreach($results as $result)
to get row count visit this sqlsrv-num-rows . on this official php link you can get more example how to fetch data.

PHP probletm with appending new property into object?

I am starting to learn php for interaction with mysql db.
I have to fetch data from two unrelated tables and form an array of stdClass objects then dump it as json array.
I have so far managed to fetch data from table1 and added some columns from it into an
myobjects[], as follows..
Here $array is an array of primary keys , also i pass a reference to myobjects array
function load_from_table1($array , &$myobjects)
{
foreach($array as $num)
{
$obj=(object)null;
$obj->prop1 = $num;
$sql="SELECT * FROM `table1` WHERE col1=".$num;
$result = mysqli_query($con, $sql);
if($result!=null)
{
$row = mysqli_fetch_assoc($result);
//inserting data into object
$obj->prop2 = $row['col2'];
$obj->prop3 = $row['col3'];
$obj->prop4 = $row['col4'];
}
$myobjects[]=$obj;
}
}
It is fine so far now i need add two more properties to all items in myobjects array obtained from table2.
function load_from_table2(&$data)
{
for($i=0;$i<sizeof($data);$i++)
{
$obj=(object)$data[$i];
$id=$obj->prop1;
$sql="SELECT * FROM `table2` WHERE col1=".$id;
$result = mysqli_query($con, $sql);
if($result!=null)
{
$row = mysqli_fetch_assoc($result);
//$temp=$row['name'];
//echo $temp;
//$obj->name = "test1";
$obj->name = $row['name'];
//$temp=$row['description'];
//echo $temp;
//$obj->description = "test2";
$obj->description = $row['description'];
}
}
When i dump myobjects as json there is no output. But $temp echos properly , also when i us direct values every thing seems to work fine.
Can some one help me with this, also an explanation on what i am doing wrong would be greatly appreciated. Thank You.
Some Details on the working Environment , Because of the answer i provided ,
I am using wampserver 2.5 64 bit , and for now executing the php file off firefox browser.
The situation is quiet confusing as i can read the value and print it or save to variable , but not save it as object property.
I got it to work, But the problem was not with the code. It seems that the column in the table that i was reading has collation set to ' utf8_general_ci ' not sure what that means. But when i removed that setting , it all worked as expected. But i feel the collation is not the actual underlying reason. So i will keep this question open in hopes some might provide an explanation.
It seems i was looking for the wrong issues. Reading up on collation i found that some character sets are not supported fully , so i tried to echo the contents of the object array instead of json_encode and found it printed.
searching to that end i found another qst here on stackoverflow that solved my problem.
Simply added this line :: mysqli_set_charset($con,'utf8'); before i started any queries on that table and json_encode started working.

Passing PHP MySQL Result Object to Function

I'm trying to take a MySQL result row and pass it to a function for processing but the row isn't getting passed. I'm assuming this is because the actual row comes back as a object and objects can't get passed to function?
E.G
function ProcessResult($TestID,$Row){
global $ResultArray;
$ResultArray["Sub" . $TestID] = $Row["Foo"] - $Row["Bar"];
$ResultArray["Add" . $TestID] = $Row["Foo"] + $Row["Bar"];
}
$SQL = "SELECT TestID,Foo,Bar FROM TestResults WHERE TestDate !='0000-00-00 00:00:00'";
$Result= mysql_query($SQL$con);
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
$nRows = mysql_num_rows($Result);
for ($i=0;$i<$nRows;$i++)
{
$Row = mysql_fetch_assoc($Result);
$TestID = $Row[TestID];
ProcessResult($TestID,$Row);
}
}
What I need is $ResultArray populated with a load of data from the MySQL query. This isn't my actual application (I know there's no need to do this for what's shown) but the principle of passing the result to a function is the same.
Is this actually possible to do some how?
Dan
mysql_query($SQL$con); should be mysql_query($SQL,$con); The first is a syntax error. Not sure if this affects your program or if it was just a typo on here.
I would recommend putting quotes around your array keys. $row[TestID] should be $row["TestID"]
The rest looks like it should work, although there are some strange ideas going on here.
Also you can do this to make your code a little cleaner.
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
while($Row = mysql_fetch_assoc($Result))
{
$TestID = $Row['TestID'];
ProcessResult($TestID,$Row);
}
}
mysql_fetch_assoc() returns an associative array - see more
If you need an object, try mysql_fetch_object() function - see more
Both array and object can be passed to a function. Thus, your code seems to be correct, except for one line. It should be:
$Result= mysql_query($SQL, $con);
or just:
$Result= mysql_query($SQL);

Categories