I'm working on code for a poll. The admin can create questions and delete them. The user can choose answers from a dropdown menu to answer the questions. This dropdown menu is filled dynamically with a query request.
Now I want the user's name to be inserted in the database when he completes a poll, so he can't do that poll twice. That's what the code here is for. This is the query I'm using:
$idfind = "SELECT `id` FROM `Umfragenteilnahme` WHERE `Username` ='$user'";
$id = mysql_query($idfind) or die (mysql_error());
if($id) {
while($rpw = mysql_fetch_assoc($id)) {
$id = $rpw['id']; // Using $rpw->id doesnt work
echo $id; // it gives the right answer and everything works fine
//id= 4 for example
}
}
else {
echo "Fehler"; // it does not report a fail
}
I know I should use the new mysqli_...
tags. The code works absolutely fine and the query gives the right answer and works in MySql database as well.
But every time it gives this error
mysql_fetch_assoc() expects parameter 1 to be resource, string given in
or for the (mysql_error())
this one:
mysql_error() expects parameter 1 to be resource, string given in.
Everything works fine, but it shows these errors. Why are these errors happening? How can I avoid them?
Edit:
Now i placed this in the beginning of the code after the first <?php
:
set_error_handler ( function($errno, $errstr, $errfile, $errline) {
if (false!==stripos($errstr, 'mysql')) {
$file = file($errfile);
$code = '';
for($i=max(0, $errline-8); $i<min($errline+8, count($file)); $i++) {
$code .= sprintf('%4d | %s', $i+1, $file[$i]);
}
printf('<fieldset><legend>%s (%d), %s@%d</legend>
<pre>%s</pre></fieldset>',
htmlspecialchars($errstr), $errno,
htmlspecialchars($errfile), $errline,
htmlspecialchars( $code )
);
}
else {
return false;
}});
The output is this :
Benutzer id: 4
mysql_fetch_assoc() expects parameter 1 to be resource, string given (2), /censored/censored/www/Website2.0/btn_lehrer.php@36
29 | /* The $user is defined at start of code */
30 | /* With the next query i get the user-id from this specific user */
31 |
32 | $idfind = "SELECT `id` FROM `Umfragenteilnahme` WHERE `Username` = '$user'";
33 | $id = mysql_query($idfind)or die (mysql_error());
34 | if($id){
35 |
36 | while($rpw = mysql_fetch_assoc($id)){
37 | $id = $rpw['id'];
38 | echo "Benutzer id: $id "; //fehler (Warning: mysql_fetch_assoc() expects parameter 1 to be resource, string given line 15)
39 | }
40 |
41 | }
42 | else{
43 | echo "Fehler bei der Bestimmung der Benutzer id!";
44 | }
I hope that you dont mind that it took so long but as i said i completely restructured my code. Thanks for all the help so far maybe now someone has the answer to my problem. :)
You are assigning a string to $id within the loop, $id = $rpw['id'];
. The next time mysql_fetch_assoc($id) is executed, $id is a string, hence the warning message.
while($rpw = mysql_fetch_assoc($id)) {
echo "Benutzer id: ", $rpw['id'], "\r\n";
}