SQL Query causing page to go blank - php

I'm making a website using php and I'm having some trouble with an SQL query.
$dataArray = array();
$result = mysql_query("SELECT * FROM test WHERE web_id='$websiteID'")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$k = $row['kfoo'];
$v = $row['vbar'];
$dataArray[$k] = $v;
}
That's the code as it should be, however that causes the page to go blank (i.e. simply display all white). I've double checked and web_id is definitely the correct name and the correct case.
If I change web_id in the query to be, for instance, 'foo' (basically anything other than web_id), then the page will display, but with the error message "Unknown column 'foo' in 'where clause'".
Does anybody have any idea what could be causing this? Here's the code where I create the table test:
$dataDB = "CREATE TABLE test
(
data_id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(data_id),
web_id INT,
kfoo TEXT,
vbar TEXT
)";
mysql_query($dataDB,$con);
Update
Based on some of the answers here, I removed the quotes from around $websiteID and displayed errors using
error_reporting(E_ALL);
ini_set('display_errors', 1);
This displayed a lot of errors, including a syntax error earlier on that I've now fixed on. However, many errors remain and they don't make much sense to me. Here's the full code for my method:
function getOutputSQL($websiteID,$userInput) {
$result = mysql_query("SELECT * FROM websites WHERE websiteID=$websiteID")
or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$url = $row['url'];
$exp = $row['exp'];
$output= $row['textPrint'];
$endUrlStart = $row['outUrlStart'];
$endUrlEnd = $row['outURLEnd'];
$image = $row['image'];
$print = $row['print'];
$post = $row['post'];
$dataSource = $row['dataSource'];
$dataSourceName = $row['dataSourceName'];
}
// construct array of data names and values
$dataArray = array();
$result = mysql_query("SELECT * FROM test WHERE web_id=$websiteID")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$k = $row['kfoo'];
$v = $row['vbar'];
$dataArray[$k] = $v;
}
// construct array of expressions and replacements
$result = mysql_query("SELECT * FROM regex WHERE web_id=$websiteID");
$expArray = array();
while ($row = mysql_fetch_array($result)) {
$e = $row['ex'];
$r = $row['re'];
$expArray[$e] = $r;
}
return getOutput($userInput,$url,$exp,$output,$endUrlStart,
$endUrlEnd,$dataSource,$dataSourceName,$post,$image,$print,
$expArray,$dataArray);
}
The errors I'm getting are all like this -
Notice: Undefined variable: output in /home/daniel/web/resultsTest.php on line 113"
That repeats several times for url, exp, output, endUrlStart, endUrlEnd, dataSource, dataSourceName, post, image and print Line 113 is the large return line.
The thing is, as far as I can tell these variables are defined, and I know the table isn't empty, because I can display it on another page.
Solved
Sorted. The problem was actually in another part of my code - I was calling getOutputSQL incorrectly, but I've fixed it now!

I expect that your actual code actually does out put anything, If this is all the code you have it makes sence nothing is outputted since you don't when there is no error (no echo's or prints are templates or anything)
Also make sure you set both error_reporting and display_errors are set. You can do this from the top of your script using
error_reporting(E_ALL);
ini_set('display_errors', 1);
That way uou'll see all errors.
EDIT
PHP has multiple types of errors, including fatal errors, warnings and notices. Notices tell you when your using undefined variables or deprecated functions, you can pretty much ignore them. You can change the setting so you won't see them using:
error_reporting(E_ALL ^ E_NOTICE);
Then you will only see real errors (warnings and fatal errors).
More Edit
Then those variables are truly unset, try something like this before you call getOutput():
echo "<pre>";
var_dump($userInput);
var_dump($url);
//etc.
echo "</pre>";
and see if the variables are really set.

In general a blank page in php indicates disabled error notifications. At first you should enable them via .htaccess or php.ini.
BTW: As far as I know integers shouldn't be quoted in SQL.

Try this instead:
$dataArray = array();
if(is_numeric($websiteID){
$result = mysql_query("SELECT * FROM test WHERE web_id=$websiteID") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$k = $row['kfoo'];
$v = $row['vbar'];
$dataArray[$k] = $v;
}
}
Notice I removed the '' around the websiteID variable. This means mysql won't treat it as a string but as an int, which is what you specified in the mysql table creation. I also check to see if the websiteID is a number. If it is not, then there is no point in doing the sql query, as you will get zero results. This protects against sql injections.

Variables you define inside loops are destroyed at the end of the loop. That means the output variable you create in the first while loop does not exist after the loop. You should define them outside the while loop and then set the values inside the loop:
function getOutputSQL($websiteID,$userInput) {
$result = mysql_query("SELECT * FROM websites WHERE websiteID=$websiteID")
or die(mysql_error());
$url = "";
$exp = "";
$output = "";
//... etc for all the other variables you need in the function at the end.
while ($row = mysql_fetch_array($result)){
$url = $row['url'];
$exp = $row['exp'];
$output= $row['textPrint'];
$endUrlStart = $row['outUrlStart'];
$endUrlEnd = $row['outURLEnd'];
$image = $row['image'];
$print = $row['print'];
$post = $row['post'];
$dataSource = $row['dataSource'];
$dataSourceName = $row['dataSourceName'];
}
// the rest of your function...

Related

Mysql results as PHP named variables

I have a table in mysql called site_settings that looks like this
Table in PHPMyAdmin
I am trying to store all of my website settings in mysql and want to pull them into PHP as variables.
I want to pull all values from the variable_name column as the $variable names in PHP and have their values set to whats in the variable_type column.
$site_name = Vexed
$registration_enabled = False
here is my code:
$sql = connect($database_address, $database_username, $database_password, $database);
$query = "SELECT * FROM site_settings";
$result = $sql->query($query);
//$row = $result->fetch_all(MYSQLI_ASSOC);
while($row = $result->fetch_assoc())
{
$$row['variable_name'] = $row["variable_type"];
}
$arr = get_defined_vars();
print_r($arr);
the last two lines i am using to see if the variable have been created but i cant get it to work. the best result i have got so far is
[Array] => Array
(
[variable_name] => Vexed
)
Can anyone tell me where i am going wrong?
Thanks in advance to anyone who can help.
What you're trying to duplicate is PHP's extract() builtin function.
It's generally considered a bad practice, because it will make your code harder for readers to understand or debug.
What is so wrong with extract()?
How to demonstrate an exploit of extract($_POST)?
https://dzone.com/articles/php-bad-practice-use-extract
https://blog.josephscott.org/2009/02/05/i-dont-like-phps-extract-function/
What I think is happening is that when you call $$arr['variable_name'] it's actually doing $$arr first (which evaluates to $Array after the string conversion), and then trying to assign into assign the ['variable_name'] key into $Array.
I would expect this minor modification to work:
$sql = connect($database_address, $database_username, $database_password, $database);
$query = "SELECT * FROM site_settings";
$result = $sql->query($query);
//$row = $result->fetch_all(MYSQLI_ASSOC);
while($row = $result->fetch_assoc())
{
$name = $row['variable_name'];
$$name = $row["variable_type"];
}
$arr = get_defined_vars();
print_r($arr);
Edit: I'll also echo, that it's a little bit weird to dynamically create variables in this way and it will make your code hard to follow.

Undefined index PHP - FPDF

When im trying to read some data from my data class i get a notice : undefined index.
Here is the script :
$data = $data_aanbieding->week_aanbieding($week, $jaar);
$productnaam = $html_entities->html_ent($data['p_productnaam']);
$verkoopprijs = $html_entities->html_ent($data['a_verkoopprijs']);
$aanbiedingsprijs = $html_entities->html_ent($data['a_aanbiedingsprijs']);
$hoeveelheid = $html_entities->html_ent($data['p_hoeveelheid']);
$eenheid = $html_entities->html_ent($data['p_eenheid']);
Those indexes i get the notice on, here the data class :
$result = $this->mysqli->query(
<<<EOT
SELECT
aanbiedingen.id as a_id,
aanbiedingen.product_id as a_product_id,
aanbiedingen.week as a_week,
aanbiedingen.jaar as a_jaar,
aanbiedingen.verkoopprijs as a_verkoopprijs,
aanbiedingen.aanbiedingsprijs as a_aanbiedingsprijs,
producten.product_id as p_id,
producten.productnaam as p_productnaam,
producten.hoeveelheid as p_hoeveelheid,
producten.eenheid as p_eenheid
FROM aanbiedingen
INNER JOIN producten ON producten.product_id = aanbiedingen.product_id
WHERE week={$week}
AND jaar={$jaar}
ORDER BY p_productnaam
EOT
);
if($result){
$waardes = array();
while ($row = $result->fetch_assoc()) {
$waardes[]=$row;
}
return $waardes;
}
It is simply a notice, meaning that one of your array keys (indexes) has not been defined. You can turn of notice reporting using the error_reporting() function or setting it in your php.ini file. You could also make sure that all the array records you're using actually have a value.
error_reporting(E_ALL & ~E_NOTICE); might do the trick (at the top of your script).
EDIT
Judging from your own reply, you should be looking at $data[0]['p...'] instead of just $data['p...]; the data you want seems to be stored inside a nested array, through which you should loop to access all the fetched $data records.

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.

My while loop won't work

In this script, I basically want to echo out data from a mysql table when the certain row record matches the name in browser address bar. But for some reason, no data is echoed. Any reason my while loop doesn't work?
$users = $_GET['username'];
$other_friend_query = mysql_query("SELECT * FROM friend WHERE RelatingUser='$users'");
$other_friend_assoc = mysql_fetch_assoc($other_friend_query);
while ($other_friend_assoc = mysql_fetch_assoc($other_friend_query)) {
$friend_related = $other_friend_assoc['RelatedUser'];
echo $friend_related;
}
That's because you call mysql_fetch_assoc before your while loop. When you call this, it fetches a result. Then when you go to your loop, that result has already been fetched. Just remove that and you'll be good to go. As stated in the comments, stop using mysql_ functions. The code below will escape your posted variable and also check for errors. It's also better practice to use a column list, instead of SELECT *.
$users = mysql_real_escape_string($_GET['username']);
$other_friend_query = mysql_query("SELECT * FROM friend WHERE RelatingUser='$users'") or die( mysql_error() );
while( $other_friend_assoc = mysql_fetch_assoc($other_friend_query) ) {
$friend_related = $other_friend_assoc['RelatedUser'];
echo $friend_related;
}
Any reason my while loop doesn't work?
May not be the only reason, but you're skipping the first result.
// the following line is unused and therefore unnecessary
$other_friend_assoc = mysql_fetch_assoc($other_friend_query);
while ($other_friend_assoc = mysql_fetch_assoc($other_friend_query)) {

PHP code works on server but throws errors in localhost

for($i=0;$cast_row = mysql_fetch_array($res);$i++)
{
$cast['id'][] = $cast_row['user_id'];
$cast['role'][] = $cast_row['role'];
$cast['role_name'][] = $cast_row['role_name'];
$cast['is_approved'][] = $cast_row['is_approved'];
$cast['movie_id'][] = $cast_row['movie_id'];
}
for($i=0;$i<count($cast['id']);$i++) //LINE 31
{
$output .= "<tr>";
$mname = getMovieNameById($m_id);
$output .= "<td><a href='single.php?id=$m_id'>$mname</a></td>";
$aname = getArtistNameById($cast['id'][$i]);
$output .= "<td><a href=project.php?id={$cast['id'][$i]}>$aname</a></td>";
}
This code works fine in the web server but throws errors(notice) when executed on localhost
Notice: Undefined index: id in C:\wamp\www\Tinyflick\managemovie.php on line 31
What can be the problem? The rest of the code seems to work just fine
It kind of a silly mistake..
Its solved. Thanks to nico's comment
The error reporting level in localhost is different from the one on the server.
Changing that will do the trick.
The following code will show the all the errors and warnings
error_reporting(E_ALL)
Warnings are usually disabled on a production server. For more info refer the documentation of the said function
i guess the mysql result is just empty ! :)
try dumping the content of the row you get back.
btw, you could improove your code by doing something like this:
while($row = mysql_fetch_array($res)) { // iterates as long there is content
//do something with the $row... like your second for block! ;)
}
it turns out that $cast array is empty as you are not properly fetching the data from database.
if the error reporting is turned off in your server then you will not see any errors.
instead of for loop use the while loop, to iterate through the data fetched from database.
$cast = array();
while($row = mysql_fetch_array($res)) {
$cast['id'][] = $row['user_id'];
$cast['role'][] = $row['role'];
$cast['role_name'][] = $row['role_name'];
$cast['is_approved'][] = $row['is_approved'];
$cast['movie_id'][] = $row['movie_id'];
}
and then you can run the for loop.
I guess that if you want supress those notices, add the following line before the loop:
$cast = array('id'=>array(), 'role'=>array(), 'role_name'=>array(), 'is_approved'=>array(), 'movie_id'=>array() );
to initialize the variable.

Categories