mysql query not working in php? - php

My mysql table has 6 fields bkid bkname bkauth bkpub bkedn bkstock.
This program is just for testing you may see some extra lines which I have commented out because I am not using the commented lines for now.
Just for now I am trying to get bkid from the html form and then use it in a query to find out the last column of the retrieved result in $row as $row[5] which is books in stock bkstock. So,I need to find out the no of books in stock from the bkid provided by the user in the form and clicking the button to submit the form.
The query given below does not work.
Notice: Undefined offset: 5 in C:\xampp\htdocs\projects\library\incstockbook.php on line 41
<HTML>
<HEAD>
<h1 align="center">THIS PAGE ADDS STOCK OF BOOKS TO THE LIBRARY</h1>
</HEAD>
TO INCREASE THE STOCK OF BOOKS TO INCLUDE TO THE LIBRARY
<FORM action="incstockbook.php" method="POST">
<table>
<tr>
<td>ENTER THE BOOK ID :</td>
<td><input type=text name="bkid">
</TR>
<TR>
<td>ENTER THE NO. OF BOOKS TO INCLUDE TO THE LIBRARY:</td>
<td><input type=text name="bkstock">
</tr>
</table>
<BR>
CLICK HERE STOCK MORE BOOK :<input type="submit" value="ADD STOCK" name="submit"></br></br>
</FORM>
<?php
$server="localhost";
$username="root";
$password="pramit";
$db="test";
$mysqli = new mysqli($server,$username,$password);
if ($mysqli->errno)
{
printf("Unable to connect to the database:<br /> %s",
$mysqli->error);
exit();
}
$mysqli->select_db($db);
$query1 = "select bkstock from books where bkid=";
if(isset($_POST['submit']))
{
$bkid=$_POST['bkid'];
// $bkstock=$_POST['bkstock'];
$query1.="'$bkid'";
$result=$mysqli->query($query1,MYSQLI_STORE_RESULT);
$row = $result->fetch_array(MYSQLI_NUM);
echo "$row[5]";
}
$mysqli_close;
?>

First thing to do in such cases is to use var_dump(). It'll tell you what is in $row variable and allow you to fix that problem. And problem is the fact that you're trying to get sixth item from row when there is only one, so it should be $row[0].
But there are some more to fix here.
Check $mysqli_close; statement, maybe you wanted to use $mysqli->close()? Because like that it doesn't make any sense.
Next, never use raw user input data in queries. It's dangerous! You have to filter it, or better use prepared statements.

$row[5] tries to retrieve the 6th element from your array. Since this row maps to 1 row (the first) of your query result, the number of elements contained in the row is exactly the number of selected columns from your table. select bkstock from... indicates there will only be one element in your array, so only $row[0] will work.
And as an extra: there is no need to wrap it in a quote when you echo it. just echo $row[0]; should be fine.

Related

update database record in while loop php

I am trying to develop a simple page in php to update attendance days.I have set the query to display the records from db and added a check box with data displayed from db.I want to update the specific record of db on which check box is checked.i want to update the the attendance column with 1 to existing value.for this i just tried written code to display the data from db and added a check box but dnt know to update the record where check box is checked on submit button.here is my initial code.any one help
<?php
require_once("../db/db_connect.php");
$db = new DB_CONNECT();
$sql = "SELECT cv_id, cd_id, cv_fomfeeback FROM candidateverification;";
$res = pg_query($sql) or die ($sql);
// output data of each row
while($row = pg_fetch_row($res)){
echo "cd id: " . $row[0]. " cv id: " . $row[1]. " atn: " . $row[2]. "<input type='checkbox' value='1'/> <br>";
}
?>
<html lang="en">
<head>
<body>
<input type="button" action="update" value="Submit"/>
</body>
</html>
I want to update cv_fomfeeback column with +1 if check box is checked.
First you need to name your checkbox. You must do this in a way, so that you get all the checkboxes (-> array) and know the row id of the checkes boxes (-> associative array).
Your checkbox could look like this:
echo "<input type=\"checkbox" name=\"boxes[{$row[0]}]\" value=\"1\">";
On the page that is called after submit has been done (see the comment of #TheNAkos) you will find all checked boxes in the associative array accessible via
$_POST["boxes"]
From there you need to loop through the array and update the rows accordingly.
I will not post a complete example, but those hints should help you find the solution by yourself.

Retrieving and inserting multiple entries in MySQL/PHP

I'm trying to create a form that retrieves data from a database and then allows me to add data to one column for multiple entries.
Every entry has an ID, a lot of other fields, and a category. I am trying to add these categories for every ID in the database using one form.
I came up with the solution below, but (of course)this only inserts the LAST entry in the form, because the variable ID is changed with every new row.
The form I have now shows me what I want to see, but it does not save it the way I need it to.
The question is, (how) can I make a form that has all entries in the database with a dropdown menu next to it,
lets me select the right category from the dropdown, and save it to the database?
The form:
$result = mysqli_query($con,"SELECT * FROM aw");
while($row = mysqli_fetch_array($result))
{
echo '<tr><td><input type="hidden" name="ID" value="'.$row[ID].'."> '.$row[ID].'</td><td>';
echo '
<select name="cat" onchange="this.form.submit()">
<option value="C1">category1</option>
<option value="C2"">category2</option>
</select></td></tr>
';
}
?>
<tr><td><input type="submit" title="SAVE" ></td></tr>
</form>
The insert.php
$sql="REPLACE INTO aw (ID,cat)
VALUES
('$_POST[ID]','$_POST[cat]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
I changed my code according to Tom's answer and I now have the following:
This does print the values like they should be, but it still saves only the last entry into the database. I'm sure I must be missing something here..
$name = $_POST['ID'];
$category = $_POST['cat'];
foreach( $name as $key => $n ) {
$sql="REPLACE INTO aw (ID,cat)
VALUES
('$n','$category[$key]')";
print "The id is ".$n.", category is ".$category[$key]."<br>";
}
First of all, use PDO::Mysql, the SQL functions you are using are a bit deprecated and do not focus much on security. At the moment your code is vulnerable to SQL injections and your output is sensitive to XSS attacks (always sanitize output).
I was wrong, MySQL is deprecated but MySQLi is not! I do prefer using PDO::Mysql because of the range of databases it supports (MySQLi only supports a MySQL database, PDO::Mysql supports many more)
Now to your original question, you can create a sort of array. By making name="ID" to name="ID[]" and name="cat" to name="cat[]".
Now you can do
$name = $_POST['ID'];
$category = $_POST['cat'];
foreach( $name as $key => $n ) {
print "The id is ".$n.", category is ".$category[$key];
}
The problem is your using the name elements regardless of how many rows..
So name="ID" & name="cat" needs to change on each row or have an array type
you could use something like name="ID[]" as this would append/ create an array to $_POST['ID']... but you still would want to change your SQL query to handle each of these.
EDIT
If i understand, you want to be able to identify a row from the table so you can use that in the database?? One way todo this is when creating the table.. Give the TR a id/name attribute that is the row id from the database.
Then can simply know by checking that if your using the select menu from row #4, you check the id/name attribute of the current row and you have your database id.
<tr id='my_row_1'>
<td class='colName'>John</td>
<td class='colPhone'>1111</td>
<td class='colOther'>....</td>
</tr>
<tr id='my_row_2'>
<td class='colName'>Bill</td>
<td class='colPhone'>2222</td>
<td class='colOther'>....</td>
</tr>
<tr id='my_row_3'>
<td class='colName'>Roger</td>
<td class='colPhone'>3333</td>
<td class='colOther'>....</td>
</tr>
With something like the above, Say i had a button in on of the columns... When i click on that button.. all i have todo is find the parent TR and get its id value.... Then explode it by "_" and get the last piece to have the id..
So your PHP would generate the id easily... Also, using a form would not be the best case here.. Using multiple forms within a table is... wasteful... sort of ..
I would suggest more so, having a button that simple calls a js function which will then post/ajax/jquery what you need from that row.
--- Trying to understand exactly what you need??

PHP Updating row in record to yes instead of no but it still shows even though code is for where X = no only

The page is set to show all rows where isthisapproved equals no. This is working how I want by updating isthisapproved to yes. However, after updating isthisapproved from no to yes I don't want it to show anymore... but it is. I'm guessing I have some code in the wrong spot so it isn't "refreshing" the isthisapproved=no query.
<form method='post'>";
$query="SELECT * FROM table WHERE isthisapproved='no'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
echo "<p>$count need approval</p>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$id=$row['id'];
echo "
<table>
<tr>
<td>ID:</td>
<td>$id <input type='hidden' name='id[]' value='$id'></td>
</tr>
<tr>
<td>
<center><input name='submit' type='submit' value='Change To Yes'></form></center>
</td>
</tr>
</table><br>
";}
if($_POST['submit']) {
$update = "UPDATE table SET isthisapproved='yes' WHERE id='$id' LIMIT 1";
if(mysql_query($update)) $count++;
else die("Error in query:<br>$sql<br>");
echo "<p><b>$name approval changed to yes</b></p>";
}
?>
I'd also like to put the notice that the approval worked to be at the top of the page after an update is made instead of at the bottom. I'm not sure how to go about that.
The select query and the update query are using different column names.
$query="SELECT * FROM table WHERE approved='no'";
^^^^^^^^
$update = "UPDATE table SET isthisapproved='yes' WHERE id='$id' LIMIT 1";
^^^^^^^^^^^^^^
Your code is very vulnerable to SQL injection consider using PDO..
Your id is an array so upon submit all of the ids will be sent to your script as it is all contained in one form.
You could wrap it in individual forms and there would also be no need for id to be an array... OR you could place a check box for each user and have the name as id[] then upon submit. you can do this...
foreach($_POST['id'] as $v){
//query goes here. $v is the ID
}
This could however be more efficient and generate a string to be sent as one query to update all users in one go.
First of all you are using "approved" column for select query and "isthisapproved" for update query. So anyway I am assuming it as a typo error. (If not then fix it).
Now pointing out some issue :
Correct your form starting tag and closing tag. Even though it is closing properly. So here form closing tag should be after finishing the table.
After submitting the form you are not receiving the id through $_POST. You are using direct $id which is wrong.
So here you should recieve the id like this and then pass it to update query :
$id = $_POST['id'];

hidden ID column and other column which shows data

I've been having trouble with this one piece of code, and can't seem to sort out the problem.
I've looked online and the error im currently getting has something to do with a failed query but as i follow the steps to solve this problem it doesent seem to work.
What I need to do is have two separate columns one for the id, and the other for the data which the ids hold and I need it to pull information from my table called tbl typeofbusiness
This is my code :
<tr>
<td>Type of Business:</td>
<td>
<select name="typeofbusiness">
<option value=''> - select type of business -</option>
<?php
$sql = "SELECT tbl_typesofbusiness.ID, tbl_typesofbusiness.Agent
FROM tbl_typesofbusiness";
$res = mysqli_query($con,$sql)or ("Error: ".mysqli_error($con));
while (list($id, $tob) = mysqli_fetch_row($res)); {
echo "<option value='$id'>$tob</option>\n";
}
?>
</select>
</td>
<td>
<span class="error">*
<?php if (isset($errors['typeofbusiness']))
echo $errors['typeofbusiness']; ?>
</span>
</td>
</tr>
This creates the dropdown box and has a default value : select type of business, but it does not seem to pull the data from the database, as there are no other options under that. It also shows an error message.
Which I no how to solve by changing or to or die but when i make that change all code under or die dosent appear and i have another 6-7 fields which really isn't convenient and even worse when I do this no error message appears.
I need someone to help me with removing these problems so that it pulls information from the database and all the other errors no longer appear.
The error is:
Warning: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\AddLeads\addeadstemplate.php on line 256 Call Stack # Time Memory Function Location 1 0.2188 192992 {main}( ) ..\addeadstemplate.php:0 2 2.1875 205216 mysqli_fetch_row ( ) ..\addeadstemplate.php:256
While Loop close before the $error variable.
And Fetch array function not used for $error
<?php
$errors= mysql_fetch_array($res);
?>
<td><span class="error">* <?php if (isset($errors['typeofbusiness'])) { echo$errors['typeofbusiness']; }?></span></td>
</tr>
Try this.

Using input checkboxes with a database

So I'm trying to help a friend out by writing his guild an attendance tracker for raiding and whatnot. Right now my concept is to do a select * from the user column, and make a checkbox for each user, assuming that person showed up to raid, it would pass a "1" through the form, and their raid attendance would be incremented by 1. On the users page the overall attendance would be calculated as (raidAtt / raidsTotal)*100 (since joining).
My issue right now is that I don't really know how to get all this information passed using a single loop...
Right now my code is something like this:
<form action="raidattend.php" method="post">
<?php
mysql_connect("$database",$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM attend WHERE UserName = $v_member ORDER BY date desc";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
?>
<table>
<tr>
<th>Member</th>
<th>Attended?</th>
</tr>
<?php
$i=0;
while ($i < $num) {
$f1=mysql_result($result,$i,"UserName");
}
<tr>
<td><?php echo $f1; ?></td><td input type="checkbox" checked value="1">
And that's where I ran into issues. I'm not sure how to pass each user and the result of the checkbox back to the database. Once I understand how to do that it's just as simple as incrementing, but I'm pretty lost.
Thanks for any help!
Edit: To clarify, what I'm unsure of is how to break it up so each member gets updated, I understand that I need to use a submit and all that.
Edit 2: Stray }
You should change your checkbox so that they all have the same name (ie name="member[]"). This way, when you submit your form, all of the checked members will be in $_POST['member']. Then, just loop through $_POST['member'] and update your table.
<td><?php echo $f1; ?><td> <input type="checkbox" name="member[]" value=<?php echo "'$f1'"; ?> /></td>
This should give you the list of checkboxes with the names of the members that attended.
Here is a quick overview of how to do the update:
1.Loop through $_POST['member'] and increment the amount that person has attended :
foreach($_POST['member'] as $member)
{
mysql_query("update table_name set attended=(attended+1) where username='$member'");
}
2.After you update each member that attended, do an update on the entire table to increment the total number of raids that have happened:
mssql_query("update table_name set total=(total+1)");
on form:
<input type=checkbox name=selected[] value='" . $f1 . "'>
on raidattend.php:
$selected=$_POST['selected'];
while (list ($key,$val) = #each ($selected)) {
//$val will hold the username
}

Categories