How to make select queries repeatedly with php? - php

Basically what I need is to make queries that depend on the values ​​of a text file that I'm reading.
This is the code that I have.
$con = mysqli_connect($host,$name,$pass,$db);
$file = fopen($_FILES["file"]["tmp_name"], "r") or die("Unable to open file!");
while(!feof($file))
{
$codigo = fgets($file);
$result = mysqli_query($con,"SELECT column FROM table WHERE column='". $codigo."'");
$row = mysqli_fetch_array($result);
echo $row;
}
fclose($file);
mysqli_close($con);
But I can´t get that I want. I have some values in my text file but when I excecute this I only get the query of the last value of my text file.
Any suggestion?
If I add this line inside the while:
echo $codigo . "<br>";
All the content of my text file are printed, so I think the problem is in the result variable. All the values of the text file return a null value when I make the query except the last.

Try
print_r($row);
or
echo $row["column"];
instead of
echo $row;
Otherwise you will always have "Array" returned.

The solution is someting stupid, when I read a file line by line, PHP also read the newline (\n) so when I make a query the where condition never is true.
A quick solution is make a substring.

What you are doing wrong is this line:
$row = mysqli_fetch_array($result);
And that's why you only see the last result. You keep overwriting that value with the new result. Instead of rewriting the string, keep adding to the array, then after the loop var_dump or print_r the array.
$row[] = mysqli_fetch_array($result);
It also might help you to use mysqli in an object-oriented fashion, the way it was designed:
$result = $con->query($query);

Related

PHP while loop. Why does this work?

I'm creating my first php site using tutorial for reference. I can't get my head around why the following works:
while ($row = mysql_fetch_array($result)){
echo $row[1]. " ".row[2]."<br/>";
}
Specifically, how does the loop increment to the next row?
UPDATE:
Thanks to all who bothered to provide an answer, including those who implored me to RTM. My problem was not understanding how while loops work, rather simply I couldn't see how the loop increments.
THE ANSWER:
From the PHP docs,
mysql_fetch_array: Returns an array that corresponds to the fetched row and moves the internal data pointer ahead
I see now, all is well.
You can rewrite that code to this equivalent:
$row = mysql_fetch_array($result); // fetch and advance
while ($row !== false) { // compare result against false
echo $row[1]. " ".row[2]."<br/>";
$row = mysql_fetch_array($result); // fetch and advance
}
An assignment yields a value which can then be used in a condition, though it's a good practice to put parentheses around the assignment:
// fetch and advance, compare fetched result against false
while (($row = mysql_fetch_array($result)) !== false) {
echo $row[1]. " ".row[2]."<br/>";
}
mysql_fetch_array() will take a $result and save into $row in form an array. Using while loop, your program will loop the data in the array from the beginning until the end.
By the way, your codes should be like
while ($row = mysql_fetch_array($result)){
echo $row['someData1']. " ".row['someData2']."<br/>";
}
If you want to iterate through the index, then the code looks like following but it will print the word Array as you will print the result in "that" specific index.
$indexCounter = 0;
while ($row = mysql_fetch_array($result)){
echo $row[$indexCounter]."<br/>";
}
Hope this helps! Thank you.
The mysql_fetch_array take the first element of $result then is $result have elements this work... is like take cards from a deck
Take a read though the PHP While documentation. It might also be useful to learn what mysql_fetch_array() does and how it works. After you're done reading about that, don't use the mysql_* functions again because they're deprecated. Instead, use mysqli_* or PDO.

How to run a mysql loop from a posted array and extract results to a CSV file

I have searched for hours to try and find a simple answer to this query I am having. I'm very sure it is covered in many ways, by other answers at least partially. I need a clear answer specific to what I am doing because I'm having difficulty trying to put together an answer that works for me from a bunch of other differently formatted and structured questions/answers.
I have a form which is posting a range of results intended to be used as keys for a mysql lookup loop. This is working fine - my post results in a successful array. For example:
$payarr = $_POST['pay'];
print_r($payarr);
Results in:
Array ( [0] => 12 [1] => 7 [2] => 1 )
Which is good given that the I want to run a mysqli process select the rows where claim_id is each of the values in $payarr. I then want to use fputcsv to write each of these rows fully, into a CSV file that is uniquely named by the days date and time that this is all run.
I have fragments of code that don't work and my frustration at trying to cobble something together that does work is getting a bit nuts. Can someone please show me how to do this effectively?
At the moment my code looks like this (but fails miserably):
<?php
include ("../conf/dbconfig.php");
include ("../conf/funcs.php");
include ("../conf/privs.php");
if($privs == 500) {
$view = $_POST['view'];
$payarr = $_POST['pay'];
$ts = date('Ymd-His');
print_r($payarr); //Testing to make sure our array to select from has arrived here ok.
//ob_start();
$fp = fopen('../csv/ResultsFile_'.$ts.'.csv', 'w');
foreach($payarr as $val) {
$result = mysqli_query($con, "'SELECT * FROM claims' WHERE claim_id='$val'");
//$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
while ($row = mysqli_fetch_array($result)) {
echo $payarr;
echo $val;
//fputcsv($fp, $row);
print_r($row);
}
}
fclose($fp);
// return ob_get_clean();
} else {
header("Location: http://www.google.com.au/");
die;
}
?>
I'm willing (and happy) to rewrite the entire thing just as long as it works, so any help and suggestions are very appreciated!
Thanks in advance.
BTW - The $view value is not important in this process but is here as it will be passed back to the resulting header once this all works.
A few rough suggestions (you may need to adapt):
1) Change your query to use IN for the possible values, so you only have to execute one DB query:
$result = mysqli_query($con, "SELECT * FROM claims WHERE claim_id IN (" . implode(",",$payarr) . ")");
2) Make sure you are actually getting a DB result, instead of just assuming:
if(!$result || mysqli_num_rows($result) == 0) {
die("We didn't get any results from the DB!"); // Obviously you'll want better error handling
}
3) Now you can open your file, knowing that you need it. Make sure to verify it worked, since you could easily hit a permissions issue:
$fp = fopen('../csv/ResultsFile_'.$ts.'.csv', 'w');
if(!$fp) {
die("We couldn't open the CSV file for writing, check permissions!"); // Obviously you'll want better error handling
}
4) Now loop through your DB results and store them:
while ($row = mysqli_fetch_array($result)) {
fputcsv($fp, $row);
}
5) Does your CSV file need a header row? If so change mysqli_fetch_array() to mysqli_fetch_assoc() and stick this inside your loop:
while ($row = mysqli_fetch_assoc($result)) {
if(!isset($header)) {
$header = array_keys($row);
fputcsv($fp, $header);
}
fputcsv($fp, $row);
}
6) Only now should you close your file (in your code you do it inside the foreach loop):
fclose($fp);
7) Sanitize your $payarr. It could be as simple as:
$payarr = is_array($_POST['pay']) ? array_map('intval', $_POST['pay']) : array();
You may want to do more than that. But at least you're guaranteed to have an array with only integer values (and as long as you have no claim_id values of 0, it's harmless to have zeros in the array).
Hope that helps, at least track down where your code is failing.

PHP mysqli_fetch_assoc to store data in an array

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.

How to perform a function for every row in a mysql array?

UPDATE: I solved it using a for loop:
for ($i=0; $i < mysql_num_rows($result); $i++) {
$row = mysql_fetch_assoc($result);
echo $row['name'];
}
ORIGINAL QUESTION:
This looks kinda stupid. I'm sure im missing something that's very simple, since I was able to accomplish this before. Anyways, I want to echo some text for every item in an array. This array is derived from mySQL.
here's the code
while ($row = mysql_fetch_assoc(mysql_query("SELECT * FROM files"))) {
echo $row['name'];
}
can you post the complete code? I think you forgot the database connection.
Try this:
$result = mysql_query("SELECT * FROM files") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
var_dump($row['name']);
}
This will throw an error, I guess you made a mistake over there. Also, var_dump() your $row in the while to make 100% sure you have "a" value.
Also, are you sure the row does exist? If don't have any records, the echo on your $row will not work sinc it does not exist.
Also, set error reporting to E_ALL like so.
error_reporting(E_ALL);
Also, since you are running your query inside the while() loop, it will continue to run forever. So first run the query, and put it in a variable, and then loop through the results. (see my piece of code above)
You can execute query individual instead of while loop because if your query return more than 1 rows it will goes under the loop. show your loop print only first data of result and your loop is infinite.
From your question it seems so simple, try this way it's working.
$sql="SELECT name From files";
$names = $db->query($sql);
while($name1 = $db->fetchByAssoc($names))
{
echo $name1['name'];
}

Outputting Query to Textfile

I have this code (which thanks to the users of stackoverflow I got the markup I needed :) ). However, I have come to a road that I have no knowledge of what so ever. I need to output this formatted table of the query to a text file on the server.
<?php
// Make a MySQL Connection
mysql_connect("hostname.net", "user", "pass") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM cards ORDER BY card_id")
or die(mysql_error());
echo "";
echo " Name AgeTitlebar ";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "";
echo $row['card_id'];
echo "";
echo $row['title'];
echo "";
echo $row['item_bar'];
echo "";
}
echo "";
?>
I know I could use something similar to
<?php
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
fclose($fh);
?>
but I am sure that it cant be the best solution. So I guess my question is does anyone know how to achieve this?
The nicest solution, particularly if you are short on memory, would be to put the writing into the loop:
$fh = fopen('cards.csv', 'w');
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
fputcsv($fh, array($row['card_id'], $row['title'], $row['item_bar']), "\t");
}
fclose('cards.csv');
Note that I have used fputcsv to output the data in CSV format (using a tab as the delimiter). This should be easy to read by hand, and will also be easily understood by, for instance, a spreadsheet program. If you preferred a custom format, you should use fwrite as in your question.
Have a look at:
http://dev.mysql.com/doc/refman/5.0/en/select.html
especially:
[INTO OUTFILE 'file_name' export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [, var_name]]
Something like this?
// Make sure the file exists, do some checks.
// Loop trough result set and append anything to the file.
while (false !== ($aRow = mysql_fetch_assoc($rResult))) {
$sCreateString = $aRow['field1'].';'.$aRow['field2'];
file_put_contents('example.txt', $sCreateString, FILE_APPEND);
}
// Done
If you need an exact dump of the database table, there are better options. (much better actually).
If you want to write a text file, then there's nothing wrong with what you've suggested.
There's lots of information in the PHP manual: http://www.php.net/manual/en/ref.filesystem.php
It depends entirely on how you want to store the data inside the file. You can create your own flat-file database format if you wish, and extract the data using PHP once you've read in the file.

Categories