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.
Related
I am trying to learn PHP, but I am stuck on something. Was wondering if any of you could help me out.
The thing is, I've got a variable like this:
$sql = "SELECT * FROM `settings` WHERE `key` LIKE 'signing_key'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$key = $row['value'];
}
mysqli_free_result($result);
}
}
$Settings['SIGNING_KEY'] = $key;
As you can see the $key variable get's it's contents from a while loop and outputs - let's just say - '12345'.
Everything looks correct, when I:
echo $Settings['SIGNING_KEY'];
it does output the '12345' on screen, as expected.
The weird thing is: when I enter:
$Settings['SIGNING_KEY'] = '12345';
in my file, the module that I am trying to modify seems to work correctly. But when I enter:
$Settings['SIGNING_KEY'] = $key;
for some reason the module cannot get the right signing key.
Can someone please explain to me what I am doing wrong?
Thanks in advance and sorry for not understanding PHP that much yet!
Edit:
Just a little extra explanation:
I am trying to get a string ($key) from the database instead of putting it hardcoded in a PHP file, so it (the $key variable) can be edited by everyone that has access to my website's control panel.
Is is possible $key isn't assigned probably? If you only want the first matching row change the while to an if. Also try dumping the value of $key and adding some error handling to your queries (as in: mysqli_query($link, $sql) or die(mysqli_error($link))).
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.
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..
I've run into a problem that is making me go a bit crazy. I have imported some csv data into a table in my phpadmin database and am now using a php script with mysql_query() to run a simple select query on the database and convert the result into json format - e.g. SELECT clients FROM TABLE 29.
Basically, some of the columns in the table result in a json string after passing them through mysql_query() but others simply return a blank. I have fiddled for hours now and can't figure out why this is. The last bit of my code looks like this:
$myquery = "SELECT `clients` FROM `TABLE 29`";
$query = mysql_query($myquery) or die(mysql_error());
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);
Any help would be greatly appreciated. Could it be something about the data in the table? I'm at a loss.
thank you!
UPDATE: the length of the strings in the column clients seems to be having an effect. When I replace all the text with something shorter (e.g. aaa instead of something like company name 111 - 045 - project name - currency - etc) it works. However, I need it to be able to handle long strings as I want it to just take whatever users happen to import into it... what am I doing wrong?
No, its not about the table, its about how you loop them. Example:
$data = array();
while($row = mysql_fetch_assoc($query)) { // While a row of data exists, put that row in $row as an associative array
$data[] = $row;
}
echo json_encode($data);
mysql_close($server);
exit;
Note: mysql is depreacted and no longer maintained. Use the improved version of the mysql extension which is mysqli or use PDO instead.
After checking all the rows of the data I discovered that the source of the problem was a 'é' - yes, an 'e' with an accent. Once I replaced it with a regular 'e' the problem went away. So much lost time for something so tiny :(
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);