I would like to create a simple select drop down, to be populated by a table in my MYSQL database.
Here is my code:
$q = 'SELECT * FROM Shipmethods';
$result = mysqli_query($connection, $q);
echo '<select name="shipmethod">';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC));
{
echo '<option value="' . $row['shipmethodid'] . '">' . $row['shipmethoddesc'] . '</option>';
}
echo '</select>';
mysqli_free_result($result); // free up the results
}
There is no connection error, no typos in table name or column names. The HTML output shows that a select option exists, but it is empty. I would like to use mysqli for this.
There seem to be countless topics already on this subject, but as far as I can see, my code matches the correct answers of those already answered questions.
Thanks in advance.
Remove ; from this line, rest code seems fine to me, let me know if it works or not --
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC));
To
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
First off, based on the evidence we have, the most likely issue, other than an empty result set, is the issue that swapnesh identified, which is clearly a logic error. I'm providing this illustration, which simulates the problem to make it clear that it is NOT a syntax error to do what was accidently done here. The misplaced semicolon in essence causes the following block to be entered only after the while loop has been exhausted.
Consider this example:
<?php
$r = array(1,2,3,4);
function fetchit(&$r) {
return array_pop($r);
}
while ($val = fetchit($r))
{
echo $val;
}
This would be the intended use. Now what happens if the script has this code instead?
<?php
$r = array(1,2,3,4);
function fetchit(&$r) {
return array_pop($r);
}
while ($val = fetchit($r));
{
echo $val;
}
Trying these you will see that both scripts run without error. Although unnecessary, php does not care if you randomly include an uneeded block somewhere in your script { }, and it also does not care if an if, while, for etc, is followed by a block. It's in fact common practice for people to shorten up code with:
if (//somecondition)
statement;
Many people frown on that practice but it's legal and programmers use it all the time.
Related
I got a little problem here with my SQL query...
I debugged where the problem resides and realized that the varchar/text column seemed to stop my php function.
Here is my code:
$queryTest = mysqli_query($link, "SELECT dos_nom,dos_id FROM dossier");
while($dataTest = mysqli_fetch_assoc($queryTest)) {
if($dataTest['dos_id'] == $myparameter) {
$toreturn.= '<option class="text-'.$dataTest['dos_id'].'" value="'.$dataTest['dos_nom'].'" selected>'.$dataTest['dos_nom'].'</option>';
}
}
The problem is in the value $dataTest['dos_nom']. Without which my query works (it prints the page normally), but I don't know why. With it, it doesn't work (it prints the top of the page, and nothing from/after my php function)...
To be precise, i use it in an ajax function.
Thanks in advance!
EDIT: I tried to print only 1 row from 'dos-nom', it works! But i when try to print out more than 1 row, the function stops!
My code:
$queryTest2 = mysqli_query($link, "SELECT * FROM dossier");
while($dataTest2 = mysqli_fetch_assoc($queryTest2))
{
$test[0] = $dataTest2['dos_nom'];
}
if($dataTest['dos_id'] == $dos_id)
{
$toreturn.= '<option class="text-'.$dataTest['dos_id'].'" >'.$test[0].'</option>';
}
It prints only the last line this way. If i put a WHERE in the query it will stop the function, so i don't know what to do!
ANSWER:
É / À were in my database, i replaced them by E and A, problem solved!
try to use addslashes() function like
addslashes($dataTest['dos_nom'])
maybe the value contains some backslash or some junk characters which may be breaking your code
I see nothing wrong with your code, except the logic - you only output when option is selected.
So as you said (it prints nothing)
Let's try print something:
$queryTest = mysqli_query($link, "SELECT dos_nom,dos_id FROM dossier");
while($dataTest = mysqli_fetch_assoc($queryTest)) {
$selected = ($dataTest['dos_id'] == $myparameter)?' selected ':' ';
$toreturn.= '<option class="text-'.$dataTest['dos_id'].'" value="'.$dataTest['dos_nom'].'" '.$selected.'>'.$dataTest['dos_nom'].'</option>';
}
I have a problem. I have an array of values from database, when I try to pass it to a string with commas, it works fine on my localhost, but when I upload it to my online server, the string doesn't show any values. For example: select from table where in (,,) only shows the commas and in my xampp server it works excellent. Any ideas what this can be?
Here's the code:
<?php
$sql = "select id from users where gid = 1";
$result = mysql_query( $sql);
$cat_titles=array();
while( $row=mysql_fetch_assoc($result) )
{
$cat_titles[] = $row['id '];
// do stuff with other column
// data if we want
}
mysql_free_result( $result );
echo "<p>\n";
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
echo "</p>\n";
$cat_titles = implode(',',$cat_titles);
$cat_titles = substr($cat_titles,0,-2);
echo $cat_titles;
echo "select * from users where IN (".$cat_titles.")";
?>
A number of potential issues here:
You are not handling error conditions around you database access, so if you are having issue with your queries you would never know.
Your second select query doesn't specify a field in the WHERE clause, so it will never work
This section of code does absolutely nothing and is in fact where you problem likely lies.
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
Here $row['id'] won't have a value, so you are basically looping throguh your existing array and appending empty value to new indexes.
In all likelihood you could do this with a single query, it might help if you explain what you are actually trying to do.
You should not be using mysql_* functions. They are deprecated. Use mysqli or PDO instead.
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'];
}
I have a submission script that I wrote in PHP. It is used by multiple surveys at our organization. The surveys are created by other users. When they submit to the script, PHP puts the data into the appropriate table in MySQL. The error that I run into sometimes is that the user(s) update the form. They add a field, or rename an input and the script doesn't account for it since it expects everything to be the same. So, I am trying to find a way to make it accomodate for when a new field is added. Here is what I have:
if( mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$survey."'"))){
echo "table exists";
$sql = "SELECT * FROM " . $survey . ";";
$result = mysql_query($sql)
or die(mysql_error());
$i=0;
while($row = mysql_fetch_row($result));{
echo $row[0];
foreach($_POST as $k => $v){
$i++;
if($k != $row[$i]){
$query = "ALTER TABLE " . $survey . " ADD " . $k . " VARCHAR(100);";
mysql_query($query)
or die(mysql_error());
}
}
}
}
I am used to doing while loops in JS, so I don't know if using i works here (actually, I know it doesn't work... because it doesn't work...). What I am trying to say is that if a key doesn't match a current field name, then add it to the table. How can I return $row correctly?
When I submit to the script it says:
Duplicate column name 'V4'
I have echo $row[0] but it returns a 1. Which is the is the int used in the primary key for the for the first record.
You have a ; at the end of your while loop declaration that shouldn't be there. Not sure if that is causing the problem as you don't say what the above code does do. Update the question if the ; is not the issue.
Your while loop declaration should look like this: while($row = mysql_fetch_row($result)) {
Also, as Marc B so diplomatically put it in a comment to your question, you should be escaping any user input that goes directly into a query.
The easiest way to do this is to use $survey = mysql_real_escape_string($survey), before your first use of $survey, as a start or switch to PDO/MySQLi and use input binding (prepared statements). Here are the prepared statements docs for PDO. More can, and should, be done to protect yourself, but the above is a good start.
Hello everyone this is my first post on stack overflow.com
I am trying to create shopping cart. Values are being stored in a session in two dimension table. First value represents item id in database, second - quantity of item.
foreach($cart_array as $row){
$sql = "SELECT * FROM prod_table WHERE id=".$row['0']."";
$cart_result = mysql_query($sql, $conn);
while ($array = mysql_fetch_array($cart_result)) {
echo "<tr><td>". $array[manufacturer] . "</td>";
echo "<td>". $array[model]."</td>";
echo "<td>".$row['1']."</td>";
$cart_value = $array[price]*$row['1'];
//sum and store value of all products
$total_cart_value += $cart_value;
echo "<td>£" .$cart_value. "</td>";
echo "<td><a href='search.php?kick_id=".$row['0']."'>Remove</a></td></tr>";
OK, to remove item form cart user clicks remove and then he is being send back to the same page ( for some reason I had difficulty to use $_SERVER['PHP_SELF'} with GET method... )
and then different part of code is being triggered which is going to remove pair of values from $cart_array, using unset function.
if(isset($_GET['kick_id'])) {
$t = count($cart_array);
for( $u = 0; $u < $t; $u++){
if ($cart_array[$u]['0'] == $_GET['kick_id']){
unset($cart_array[$u]['0']);
unset($cart_array[$u]['1']);
echo " Item has been removed from your cart";
$cart_array = array_values($cart_array);
And it actually removes pair of values but, now instead of running smoothly it displays error message :
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource ...
I assume that there must be some "trace" of deleted values in session array which is causing error.
How to fix code ?
Is there any other method/approach to delete values ??
You don't appear to have unset($cart_array[$u]), just the two keys it contains. Don't bother unsetting $cart_array[$u]['0'] and '1', just unset $cart_array[$u].
I assume that...
that is what you are doing wrong.
A programmer should never "assume". A programmer can (and should) be certain.
Assumptions will lead you astray and waste your time (as well as other people's time when you ask a question).
So, you have to do some debugging - an investigation to find the actual cause of the problem.
supplied argument is not a valid MySQL result resource error means there was an error in the query. So, you have to see what error it was. So, run all yoiur queries in the manner which let you to see any error occurred. A simplest way would be
$cart_result = mysql_query($sql, $conn) or trigger_error(mysql_error()." in ".$sql);
and run your code again.
you will find an sql error in their usual place - a screen or a log file.
If you'll be unable to get the meaning of the error and correct your code yourself - it's time to ask a question. A certain and direct question, not vague question out of some assumptions. Gotcha?
There are two ways to solve this:
1) on your first part:
foreach($cart_array as $row){
if(empty($row[0])
continue;
$sql = "SELECT * FROM prod_table WHERE id=".$row['0']."";
[...]
2) when you remove the item, instead of unset($cart_array[$u]['0']); why don't you do unset($cart_array[$u]); ?
Probably this
while ($array = mysql_fetch_array($cart_result)) {
is causing the problem. based on error you see. before you try fetch result check if there is any results available by
if(mysql_num_rows($cart_result)>0){
while ($array = mysql_fetch_array($cart_result)) {
//rest code here
}