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);
Related
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.
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 have a list of url's(link) in my database and can echo the data to the page fine but instead of outputting it, I need to store that info(I was thinking an array) into a variable to perform php tasks using the provided links. I have yet to figure out how to do this.
The code has been updated I removed any references to using the soon to be deprecated mysql_* functions and opted for the mysqli version.
Heres my code
$query = "SELECT `Link` FROM `Table1` WHERE `Image` ='' AND `Source`='blah'";
if ($result = mysqli_query($dblink, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
$link = $row['Link'];
// echo ''.$link.'<br>';
$html = file_get_html($link);
foreach ($html->find('div.article') as $e) {
$result = $e->find('img', 0);
$imgsrc = $result->src . '<br>';
echo $imgsrc;
}
}
}
This code is working through one iteration: It will find the first link stored in the DB, use that $link in the bottom foreach() statement and output the desired result. After the first iteration of the loop, an error occurs stating:
"mysqli_fetch_assoc() expects parameter 1 to be a mysql result"
I think I understand why the problem is occurring - Since the $result is declared outside of the while loop, it is never set again after the first iteration/or changes in some way.
or
I should be using mysqli_free_result() possibly, If that were the case I am not sure where it would go in the code.
Thanks for any help you can offer!
When you do this:
$result = mysqli_query($dblink, $query);
The functions return a link identifier you store in $result. This identifier we need to pass to fetch functions in order to be able to show it from which result to fetch. It shouldn't be changed until you are done fetching all the results you want.
This goes right the first time:
$row = mysqli_fetch_assoc($result)
But then, in the foreach, you overwrite that variable with other information:
$result = $e->find('img', 0);
As such, when the next iteration comes around, it is no longer a valid result identifier, so MySQL doesn't know what to do with it.
The fix is actually rather simple, you need to change the name of the variable you are using in the foreach:
$result = $e->find('img', 0);
$imgsrc = $result->src . '<br>';
Becomes:
$found= $e->find('img', 0);
$imgsrc = $found->src . '<br>';
And voila, it should work...
Your snippet is full of potential errors:
1) Not checking if query succeeded
$query_run = mysql_query($query)
You execute a query, but you never check if your query succeeded by verifying if $query_run is an actual resource and not FALSE.
2) Validation of rows returned
Your validation for the number of rows returned by the query is useless:
if (mysql_num_rows($query_run)==NULL) {
echo 'No results found.';
}
This is never true, as mysql_num_rows() returns an inte or FALSE, never NULL.
3) Use of variable with potentially invalid value
Using
while ($query_row = mysql_fetch_assoc($query_run)) { ... }
is risky as you never check if $query_run is an actual resource, which is required by mysql_fetch_assoc().
4) Misunderstanding of while loop
The following lines are probably wrong too:
while ($query_row = mysql_fetch_assoc($query_run)) {
$link = $query_row['Link'];
// echo ''.$link.'<br>';
}
$html = file_get_html($link);
You iterate over all rows returned by the query. After the while loop exits, $link only contains the value of the last row as single variable cannot contain the values of multiple rows.
Conclusion
I strongly recommend you improve your error checking and improve the overall quality of your code. Also consider using one of the newer extensions like mysqli or PDO, the mysql extension is deprecated.
If you want to add all links to an array try this:
$link[] = $query_row['Link'];
Instead of:
$link = $query_row['Link'];
You were close but you weren't using square brackets you were using parentheses as shown here:
$link = $query_row($link);
Also, try taking $query_run out of the if statement. It should look something like this:
$query = "SELECT `Link` FROM `Table1` WHERE `Value1` ='' AND `Source`='blah'";
$query_run = mysql_query($query);
if ($query_run) {
echo 'Query Success!<br><br>';
if (mysql_num_rows($query_run) == NULL) {
echo 'No results found.';
}
while ($query_row = mysql_fetch_assoc($query_run)) {
$link[] = $query_row['Link'];
// echo ''.$link.'<br>';
}
$html = file_get_html($link);
foreach ($html->find('div.article') as $e) {
$result = $e->find('img', 0);
$imgsrc = $result->src . '<br>';
echo $imgsrc;
}
}
You should revisit the PHP Language Reference.
The foreach loop syntax is
foreach($array as $element)
or
foreach($array as $key=>$value)
But you seem to have other weak points that I fear are not in the scope of Stackoverflow to mend. For example your own code would work quite well by just moving a single } from line 11 down a few lines.
i've just changed from ASP to php and i'm a bit confused about the way php is handling recordsets.
i'd like to know if there's an easier way to iterate a recordset by creating a php class.
here's the ASP syntax to show what i mean:
sq = "select * from myData"
set rs = db.execute(sq)
do while not rs.eof
response.write rs("name") // output data (response.write = echo)
rs.movenext
loop
any ideas?
thanks
You'd pretty much do the same thing...
$sql = "select * from myData";
$result = mysql_query($sql) or die(mysql_error()); //executes query
while($row = mysql_fetch_array($result)){ //will automatically return false when out of records
echo $row['name'];
}
You're probably looking for a function contains word fetch in it's name.
E.g. mysql_fetch_assoc() or $pdo->fetchAll().
Most of database API functions in PHP returns some sort of pointer variable called "resource", which can be passed to the fetch-family function, like this:
$res = mysql_query();
while($row = mysql_fetch_assoc($res)){
echo $row['name'];
}
However, some of them (like PDO's fetchAll method) returns but regular PHP array, which you can iterate using as regular foreach operator.
i'm having a strange problem with php + recordsets.
my code:
$rc = mysql_query("select * from myTable",$db);
if (!$row = mysql_fetch_assoc($rc))
{
$eof=true;
}else{
echo "there is data!<br>";
$rs = mysql_fetch_array($rc);
echo $rs[id];
echo $rs[txt];
}
the strange thing - the query is correct - it's echoing "there is data" but when echoing the actual field values returns empty strings .. :(
any ideas what could be wrong?
In your else block, you are re-fetching some data from the database, using mysql_fetch_array().
But a first row has already been fetched earlier, by mysql_fetch_assoc().
So, basically :
In the if's condition, you are fetching a first row
If it succeed, you enter the else block
where you try to fetch a second row
and using the returned (or not) data, without testing the success of that second fetch.
You should probably do only one fetch -- using either mysql_fetch_assoc or mysql_fetch_array -- but not two.
you already fetched data, use mysql_num_rows() instead
$rc = mysql_query("select * from myTable",$db);
if (mysql_num_rows($rc))
{
echo "there is data!<br>";
$rs = mysql_fetch_array($rc);
echo $rs[id];
echo $rs[txt];
}else{
$eof=true;
}
Be consistent in your use of if mysql_fetch_assoc($rc)...
$rs = mysql_fetch_array($rc);
will return an enumerated array, so $rs['id'] doesn't exist only $rs[0], $rs[1], etc.
Use
$rs = mysql_fetch_assoc($rc);
to return an associative array with $rs['id']
Your first test also fetches and discards a row
And quote the indexes in $rs: $rs['id'] rather than $rs[id]