MySQL, iterate over tables [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
“Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given” error while trying to create a php shopping cart
I don't get it, I see no mistakes in this code but there is this error, please help:
mysql_fetch_array() expects parameter 1 to be resource problem
<?php
$con = mysql_connect("localhost","root","nitoryolai123$%^");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("school", $con);
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
?>
<?php while ($row = mysql_fetch_array($result)) { ?>
<table class="a" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#D3D3D3">
<tr>
<form name="formcheck" method="get" action="updateact.php" onsubmit="return formCheck(this);">
<td>
<table border="0" cellpadding="3" cellspacing="1" bgcolor="">
<tr>
<td colspan="16" height="25" style="background:#5C915C; color:white; border:white 1px solid; text-align: left"><strong><font size="2">Update Students</td>
<tr>
<td width="30" height="35"><font size="2">*I D Number:</td>
<td width="30"><input name="idnum" onkeypress="return isNumberKey(event)" type="text" maxlength="5" id='numbers'/ value="<?php echo $_GET['id']; ?>"></td>
</tr>
<tr>
<td width="30" height="35"><font size="2">*Year:</td>
<td width="30"><input name="yr" onkeypress="return isNumberKey(event)" type="text" maxlength="5" id='numbers'/ value="<?php echo $row["YEAR"]; ?>"></td>
<?php } ?>
I'm just trying to load the data in the forms but I don't know why that error appears. What could possibly be the mistake in here?

You are not doing error checking after the call to mysql_query:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
if (!$result) { // add this check.
die('Invalid query: ' . mysql_error());
}
In case mysql_query fails, it returns false, a boolean value. When you pass this to mysql_fetch_array function (which expects a mysql result object) we get this error.

$id = intval($_GET['id']);
$sql = "SELECT * FROM student WHERE IDNO=$id";
$result = mysql_query($sql) or trigger_error(mysql_error().$sql);
always do it this way and it will tell you what is wrong

Give this a try
$indo=$_GET['id'];
$result = mysql_query("SELECT * FROM student WHERE IDNO='$indo'");
I think this works..

The most likely cause is an error in mysql_query(). Have you checked to make sure it worked? Output the value of $result and mysql_error(). You may have misspelled something, selected the wrong database, have a permissions issue, etc. So:
$id = (int)$_GET['id']; // this also sanitizes it
$sql = "SELECT * FROM student WHERE idno = $id";
$result = mysql_query($sql);
if (!$result) {
die("Error running $sql: " . mysql_error());
}
Sanitizing $_GET['id'] is really important. You can use mysql_real_escape_string() but casting it to an int is sufficient for integers. Basically you want to avoid SQL injection.

Make sure that your query ran successfully and you got the results. You can check like this:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']) or die(mysql_error());
if (is_resource($result))
{
// your while loop and fetch array function here....
}

In your database what is the type of "IDNO"? You may need to escape the sql here:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);

You are using this :
mysql_fetch_array($result)
To get the error you're getting, it means that $result is not a resource.
In your code, $result is obtained this way :
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
If the SQL query fails, $result will not be a resource, but a boolean -- see mysql_query.
I suppose there's an error in your SQL query -- so it fails, mysql_query returns a boolean, and not a resource, and mysql_fetch_array cannot work on that.
You should check if the SQL query returns a result or not :
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
if ($result !== false) {
// use $result
} else {
// an error has occured
echo mysql_error();
die; // note : echoing the error message and dying
// is OK while developping, but not in production !
}
With that, you should get a message that indicates the error that occured while executing your query -- this should help figure out what the problem is ;-)
Also, you should escape the data you're putting in your SQL query, to avoid SQL injections !
For example, here, you should make sure that $_GET['id'] contains nothing else than an integer, using something like this :
$result = mysql_query("SELECT * FROM student WHERE IDNO=" . intval($_GET['id']));
Or you should check this before trying to execute the query, to display a nicer error message to the user.

Related

Deleting users With PDO

Hello every one i have probleme with my form of deliting users , when i submit the button nothing happend what is the problem , everything work on the db when i fetch infos they come but when i click on delete nothing happend
<?php
$host ="localhost";
$dbname ="justnew";
$u_name="root";
$u_pass="youcef02";
echo'
<table border="1px solid #efefef" width="42%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Password</th>
<th>DELETE</th>
</tr>
';
try{
$Conn = new PDO("mysql:host=$host;dbname=$dbname",$u_name,$u_pass);
}
catch(PDOEXCEPTION $e){
echo'There is a prblm' .$e->getMessage();
}
$sql = "SELECT * FROM addu";
$result = $Conn->query($sql);
while($row = $result->fetch(PDO::FETCH_OBJ)) {
echo"
<tr>
<td>" .$row->u_id."</td>
<td>" .$row->u_name."</td>
<td>" .$row->u_pass."</td>
<td><button name='dlt'><a href='attribute.php?
type=dlt&u_id=".$row->u_id."' name='dlt'>DELETE</a></button></td>
</tr>
";
}
if($_GET['type'] == ['dlt']){
$id = intval ($_GET['u_id']);
$Dsql = "DELETE * FROM `addu` WHERE `u_id` ='".$id."'";
$Dresult = $Conn->exec($Dsql);
}
?>
Seeing nobody wanted to post an answer for this, I am submitting the following.
As stated: if($_GET['type'] == ['dlt']) is invalid. The brackets around the dlt need to be removed and would have thrown an syntax error.
if($_GET['type'] == 'dlt')
You should however, check if the GET array is set/not empty though, since without it, that too will throw an undefined index warning having error reporting set on your system.
if(isset($_GET['type']) && $_GET['type'] == 'dlt')
or
if(!empty($_GET['type']) && $_GET['type'] == 'dlt')
Then the DELETE'ing part of your query is also invalid.
It should read as:
$Dsql = "DELETE FROM `addu` WHERE `u_id` ='".$id."'";
https://dev.mysql.com/doc/refman/5.7/en/delete.html
The asterisk is only valid with a SELECT statement:
https://dev.mysql.com/doc/refman/5.7/en/select.html
Having used (PDO) error handling, you'd of surely gotten back an syntax error:
https://php.net/manual/en/pdo.error-handling.php
Now this bit could have adverse effect:
<td><button name='dlt'><a href='attribute.php?
type=dlt&u_id=".$row->u_id."' name='dlt'>DELETE</a></button></td>
</tr>
";
It's (usually) best to have this all in one line:
<td><button name='dlt'><a href='attribute.php?type=dlt&u_id=".$row->u_id."'>DELETE</a></button></td>
</tr>
";
The added spaces could count here.
Note: You used the name attribute twice.
If the above fails, then the <a href></a> shouldn't be inside a <button></button>, just use the <a href></a>.

Table with database values and user input

So I've been wrestling with this issue on and off for quite a while now, and just like driving around lost in a strange city, I am finally breaking down for direction! I am developing table with values from a database, but also need a column that will process user input. I have been able to display the table but my input is not updating the necessary database element. Code below:
<?php
include("pogsatbetbuddy.inc.php");
$cxn=mysqli_connect($host,$username,$password,$db_name)
or die("Did Not Connect");
$query="SELECT * FROM $tbl2_name ORDER BY $tbl2_name.$col_name ASC";
$result=mysqli_query($cxn,$query)
or die("Query Not Working");
echo"<table border='1'
<form name='payments' action='' method='POST'>
<tr>
<td class='update' colspan='5'>
<button data-theme='b' id='submit' type='submit'>Update</button>
</td>
</tr>
<tr>
<th class='profile'>Last Name</th>
<th class='profile'>First Name</th>
<th class='profile'>Saturday Payment Owing</th>
<th class='profile'>Enter Payment</th>
<th class='profile'>Saturday Balance</th>
</tr>";
while ($row=mysqli_fetch_assoc($result))
{
extract ($row);
echo"<tr>
<td class='profile'>$lastname</td>
<td class='profile'>$firstname</td>
<td class='profile'>$owingsat</td>
<td class='profile'><input type='number' name='paidsat' value=''/></td>
<td class='profile'>$owingsat-$paidsat</td>
</tr>";
}
echo "</form>";
echo "</table>";
This displays the table in the way I want. Having worked through the results of the following code, it seems that I am returning a null value, so I am thinking I have an issue with either the form action or the submit Update button, but can not find the solution after much experimentation and searching. Balance of code below:
if(isset($_POST['paidsat']))
{
$paidsat = $_POST['paidsat'];
if(($paidsat) != null)
{
$stmt = $cxn->prepare("UPDATE $tbl2_name SET paidsat = ? WHERE firstname=? and lastname=?");
$stmt->bind_param('sss', $paidsat, $firstname, $lastname);
$status = $stmt->execute();
if($status === true) //To check if the execute was successful
{
echo("<p class='click'>You have successfully added the payment for $firstname $lastname\n<br /></p>");
}
}
else echo"Not Successful";
}
else echo "<p class='click'>Make your changes as required</p>";
mysqli_close($cxn);
Everything comes to a crashing halt at the second if statement.....or should I say, although things look pretty, they don't function! Thanks in advance, appreciate any help!
Be sure you have a proper value for $tbl2_name checking
var_dump($tbl2_name)
in your code before the update
and for debug try using a string concatenation like
"UPDATE " . $tbl2_name . " SET paidsat = ? WHERE firstname=? and lastname=?";
and try use
if( $paidsat != NULL )
and last check if you have proper value for update
paidsat = ? WHERE firstname=? and lastname=?
Try
var_dump( $paidsat);
var_dump( $firstname);
var_dump( $lastname);
and build a proper select for test if you value math the rows you think and
test this select in you db console

while in while loop doesn't seem to work - PHP

Alright so I've been trying to replace a number from the database for the actual name, unfortunately it only returns nothing at all.
I'm not sure what I'm doing wrong here, Tried it multiple ways, as explained on other related questions, yet it doesn't seem to work.
The first while seems to work, but the second doesn't do its job..(although in this setup it gives nothing at all)
here is my code:
<?php
include_once 'db_connect.php';
$query = "SELECT bestel_nummer, bestel_datum, bestel_tijd, kkt_id, mwr_id
FROM bestellingen";
$response = mysqli_query($mysqli, $query);
if ($response){
echo '<table align="left" cellspacing="5" cellpadding="8">
<td align="left"><b>bestel nummer<b></td>
<td align="left"><b>bestel datum<b></td>
<td align="left"><b>bestel tijd<b></td>
<td align="left"><b>klanten nummer<b></td>
<td align="left"><b>Medewerker<b></td></tr>';
while($row = mysqli_fetch_array($response)){
$mwr_id = $row['mwr_id'];
$query2 = "SELECT 'voornaam' FROM 'medewerkers' WHERE 'mwr_id' = $mwr_id LIMIT 1";
$response2 = mysqli_query($query2, $mysqli);
while($row2 = mysqli_fetch_array($response2)){
echo '<tr><td align="left">'.
$row['bestel_nummer'].'</td><td align="left">'.
$row['bestel_datum'].'</td><td align="left">'.
$row['bestel_tijd'].'</td><td align="left">'.
$row['kkt_id'].'</td><td align="left">'.
$row2['voornaam'].'</td><td align="left">';
echo'</tr>';
}
}
echo'</table>';
}
else{
echo 'couldnt issue database query';
echo mysqli_error($mysqli);
}
mysqli_close($mysqli);
?>
Thanks in advance.
Maybe it's not the while loop, but the mysqli_query
Seems like the arguments in the second query have a wrong order
first query
$response = mysqli_query($mysqli, $query);
second query
$response2 = mysqli_query($query2, $mysqli);
This means no result, no while loop, check the response2 variable, the while loop should work, but actually the code itself looks unperformant.
If you wanna have the most performance you should do it with one query, with something like Group and Join. I don't know your structure but it should be possible.
If you try to query the db, in a loop it's a alway a very bad idea, image 100, 1000 users will trigger this code.. ohoohooo your server will probably go down men.

Inserting specific values into a DB, and displaying it on a table?

I'm trying to insert specific values(knife, and blanket) into a Database, but's not inserting into the DB/table at all. Also, I want to display the inserted values in a table below, and that is not working as well. It is dependant on the insert for it to show on the table. I am sure, because I inserted a value through phpmyAdmin, and it displayed on the table. Please, I need to fix the insert aspect.
The Insert Code/Error Handler
<?php
if (isset($_POST['Collect'])) {
if(($_POST['Object'])!= "knife" && ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}else {
// this makes sure that all the uses that sign up have their own names
$sql = "SELECT id FROM objects WHERE object='".mysql_real_escape_string($_POST['Object'])."'";
$query = mysql_query($sql) or die(mysql_error());
$m_count = mysql_num_rows($query);
if($m_count >= "1"){
echo 'This object has already been taken.!';
} else{
$sql="INSERT INTO objects (object)
VALUES
('$_POST[Object]')";
echo "".$_POST['object']." ADDED";
}
}
}
?>
TABLE PLUS EXTRA PHP CODE
<p>
<form method="post">
</form>
Pick Object: <input name="Object" type="text" />
<input class="auto-style1" name="Collect" type="submit" value="Collect" />
</p>
<table width="50%" border="2" cellspacing="1" cellpadding="0">
<tr align="center">
<td colspan="3">Player's Object</td>
</tr>
<tr align="center">
<td>ID</td>
<td>Object</td>
</tr>
<?
$result = mysql_query("SELECT * FROM objects") or die(mysql_error());
// 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?>
<tr>
<td><label for="<?php echo $row['id']; ?>"><?php
$name2=$row['id'];
echo "$name2"; ?>
</label></td>
<td><? echo $row['object'] ?></td>
</tr>
<?php }// while loop ?>
</table>
</body>
if(($_POST['Object'])!= knife || ($_POST['Object'])!= blanket)
THese value knife and blanket are string. So you may need to use quotes around them to define them as string, or php won't understand ;)
If the primary key of Objects is id and it is set to auto-increment
$sql = "INSERT INTO objects SET id = '', object = '".$_POST['Object']."'";
try
$sql= "INSERT INTO objects(object) VALUES ('".$_POST['Object'].")';
and you should probably put an escape in there too
You insert query is nor correct.
$sql = "INSERT INTO objects (id, object) values('','".$_POST['Object']."') ";
and this code
if(($_POST['Object'])!= "knife" || ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}
will always be executed value of object is knife or blanket, because a variable can have one value. You must use
if(($_POST['Object'])!= "knife" && ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}
Your SQL syntax is wrong. You should change the:
INSERT INTO objects SET id = '', object = '".$_POST['Object']."'
to
INSERT INTO objects ( id, object ) VALUES ('', '".$_POST['Object']."'
If you want your inserts to also replace any value that might be there use REPLACE as opposed to INSERT.

mysql_fetch_array() expects parameter 1 to be resource problem [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
“Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given” error while trying to create a php shopping cart
I don't get it, I see no mistakes in this code but there is this error, please help:
mysql_fetch_array() expects parameter 1 to be resource problem
<?php
$con = mysql_connect("localhost","root","nitoryolai123$%^");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("school", $con);
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
?>
<?php while ($row = mysql_fetch_array($result)) { ?>
<table class="a" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#D3D3D3">
<tr>
<form name="formcheck" method="get" action="updateact.php" onsubmit="return formCheck(this);">
<td>
<table border="0" cellpadding="3" cellspacing="1" bgcolor="">
<tr>
<td colspan="16" height="25" style="background:#5C915C; color:white; border:white 1px solid; text-align: left"><strong><font size="2">Update Students</td>
<tr>
<td width="30" height="35"><font size="2">*I D Number:</td>
<td width="30"><input name="idnum" onkeypress="return isNumberKey(event)" type="text" maxlength="5" id='numbers'/ value="<?php echo $_GET['id']; ?>"></td>
</tr>
<tr>
<td width="30" height="35"><font size="2">*Year:</td>
<td width="30"><input name="yr" onkeypress="return isNumberKey(event)" type="text" maxlength="5" id='numbers'/ value="<?php echo $row["YEAR"]; ?>"></td>
<?php } ?>
I'm just trying to load the data in the forms but I don't know why that error appears. What could possibly be the mistake in here?
You are not doing error checking after the call to mysql_query:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
if (!$result) { // add this check.
die('Invalid query: ' . mysql_error());
}
In case mysql_query fails, it returns false, a boolean value. When you pass this to mysql_fetch_array function (which expects a mysql result object) we get this error.
$id = intval($_GET['id']);
$sql = "SELECT * FROM student WHERE IDNO=$id";
$result = mysql_query($sql) or trigger_error(mysql_error().$sql);
always do it this way and it will tell you what is wrong
Give this a try
$indo=$_GET['id'];
$result = mysql_query("SELECT * FROM student WHERE IDNO='$indo'");
I think this works..
The most likely cause is an error in mysql_query(). Have you checked to make sure it worked? Output the value of $result and mysql_error(). You may have misspelled something, selected the wrong database, have a permissions issue, etc. So:
$id = (int)$_GET['id']; // this also sanitizes it
$sql = "SELECT * FROM student WHERE idno = $id";
$result = mysql_query($sql);
if (!$result) {
die("Error running $sql: " . mysql_error());
}
Sanitizing $_GET['id'] is really important. You can use mysql_real_escape_string() but casting it to an int is sufficient for integers. Basically you want to avoid SQL injection.
Make sure that your query ran successfully and you got the results. You can check like this:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']) or die(mysql_error());
if (is_resource($result))
{
// your while loop and fetch array function here....
}
In your database what is the type of "IDNO"? You may need to escape the sql here:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
You are using this :
mysql_fetch_array($result)
To get the error you're getting, it means that $result is not a resource.
In your code, $result is obtained this way :
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
If the SQL query fails, $result will not be a resource, but a boolean -- see mysql_query.
I suppose there's an error in your SQL query -- so it fails, mysql_query returns a boolean, and not a resource, and mysql_fetch_array cannot work on that.
You should check if the SQL query returns a result or not :
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
if ($result !== false) {
// use $result
} else {
// an error has occured
echo mysql_error();
die; // note : echoing the error message and dying
// is OK while developping, but not in production !
}
With that, you should get a message that indicates the error that occured while executing your query -- this should help figure out what the problem is ;-)
Also, you should escape the data you're putting in your SQL query, to avoid SQL injections !
For example, here, you should make sure that $_GET['id'] contains nothing else than an integer, using something like this :
$result = mysql_query("SELECT * FROM student WHERE IDNO=" . intval($_GET['id']));
Or you should check this before trying to execute the query, to display a nicer error message to the user.

Categories