how can i insert the values of my checkboxes into my database? - php

i have here my codes regarding my checkboxes, but i got some errors when i click my submit button. though it prints all the values i selected on the checkbox but ive got an error on my sql script saying "Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\project\candidate\president2.php on line 21". i just want to save the values i selected on my database. pls help..
<?php session_start(); ?>
<?php
//server info
$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'user';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
?>
<?php
if ($_POST['representatives']){
$check = $_POST['representatives'];
foreach ($check as $ch){
//this is my line 21 error. what i want here is to save the selected checkbox into my database but i got some error and i couldnt save it to my database
mysqli_query("INSERT INTO sample (name) VALUES ('". $ch ."') ");
echo $ch. "<br>";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<script type="text/javascript">
<!--
function get_representatives_value()
{
for (var i=0; i < document.list.representatives.length; i++)
{
if (document.list.representatives[i].value = true)
{
return document.getElementById('txt').innerHTML =document.list.representatives[i].value
}
}
}
//-->
</script>
title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="candidate.css" rel="stylesheet" type="text/css">
</head>
<body> <p id="txt"></p>
<form name="list" action="president2.php" method="post" onSubmit="return get_representatives_value()">
<div id="form">
<?php
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM candidate_info WHERE position= 'representatives' AND department ='CCEITE' ORDER BY cand_id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr><th>Student ID</th><th>Candidate ID</td><th>Course</th><th colspan = '3'>Name</th></tr>";
while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->cand_studid . "</td>";
echo "<td>".$row->cand_id."</td>";
echo "<td>" . $row->course . "</td>";
echo "<td coslpan ='5'>" . $row->fname . " ". $row->mname ." ". $row->lname ." </td>";
echo "<td><input type ='checkbox' name='representatives[]' id='". $row->studid ."' value='" . $row->fname . " ". $row->mname ." ". $row->lname . "'onchange='get_representatives_value()' /></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
echo "<input type='submit' name='representatives value='Submit' />";
?>
</div>
</form>
</body>
</html>
heres the preview of my output, first pic is i selected 2 candidate and the other is one.

The mysqli_query function requires the $mysqli link to be the first parameter. There are two ways you can fix your error. Below is the ERROR
mysqli_query("INSERT INTO sample (name) VALUES ('". $ch ."') ");
To fix this simply change it to one of the two below > (Id use the first option because you already use it in your code somewhere.)
$mysqli->query("INSERT INTO sample (name) VALUES ('". $ch ."') ");
OR
mysqli_query($mysqli, "INSERT INTO sample (name) VALUES ('". $ch ."') ");

As it says, the function mysqli_query() expects at least two parameters. According to the PHP documentation, the first parameter should be:
A link identifier returned by mysqli_connect() or mysqli_init()
Followed by the query as the second parameter. You don't appear to be using either of those functions in your code. Seeing that you declared a mysqli object, you probably meant to use $mysqli->query() instead.

Just take a look at my example and i'm hoping that it would helps you..:-
<?php
if(isset($_POST['team']))
{
foreach($_POST['team'] as $value){
$insert=mysql_query("INSERT INTO team('team') VALUES ('$value')");
}
}
?>
<html>
<body>
<form method="post" action="lol.php">
<input type="checkbox" name="team[]" value="IN"> India<br />
<input type="checkbox" name="team[]" value="DK"> Dark <br />
<input type="checkbox" name="team[]" value="LA"> lolax <br />
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>

Related

search database with php (new to php)

I am brand new to php and I am trying to teach myself to code. I am hoping that someone here can help a newb out. I have a database with 300 client records in it. I am using the following code to access the database. It works great but I am having two issues that I cannot seem to fix.
1) not all clients have a middle name listed and when the middle name field is blank it adds a
2) all 300 client records display at once. Is there a way I can set it to display only 1 to a max of 10 records at a time and use next previous buttons?
additionally, is there a way to search the database? for example a box, and I enter john in it and click search and it returns all records with John? If there is a video or walkthrough that is detailed enough I can figure it out if no one is able to provide me with the code.
Thank you in advance for the help.
<html>
<head>
</head>
<body>
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die("can not connect: " . mysql_error());
}
mysql_select_db ("new_concepts" ,$con);
if(isset($_POST['update'])){
$UpdateQuery = "UPDATE clients SET ClientID='$_POST[ClientID]', FirstName='$_POST[FirstName]', MiddleName='$_POST[MiddleName]', LastName='$_POST[LastName]', Diagnosis='$_POST[Diagnosis]', Gender='$_POST[Gender]', LevelCare='$_POST[LevelCare]', Counselor='$_POST[Counselor]' WHERE ClientID='$_POST[hidden]'";
mysql_query($UpdateQuery, $con);
};
if(isset($_POST['delete'])){
$DeleteQuery = "DELETE FROM clients WHERE ClientID='$_POST[hidden]'";
mysql_query($DeleteQuery, $con);
};
if(isset($_POST['add'])){
$AddQuery = "INSERT INTO clients (ClientID, FirstName, MiddleName, LastName, Diagnosis, Gender, LevelCare, Counselor) VALUES ('$_POST[uclientid]','$_POST[ufirstname]','$_POST[umiddlename]','$_POST[ulastname]','$_POST[udiagnosis]','$_POST[ugender]','$_POST[ulevelcare]','$_POST[ucounselor]')";
mysql_query($AddQuery, $con);
};
$sql = "SELECT * FROM clients";
$myData = mysql_query($sql,$con);
echo "<table border=1>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Client ID</th>
<th>Diagnosis</th>
<th>Gender</th>
<th>Level of Care</th>
<th>Counselor</th>
</tr>";
while($record = mysql_fetch_array($myData)){
echo "<form action=mydata5.php method=post>";
echo "<tr>";
echo "<td>" . "<input type=text name=FirstName value=" . $record['FirstName'] . " </td>";
echo "<td>" . "<input type=text name=MiddleName value=" . $record['MiddleName'] . " </td>";
echo "<td>" . "<input type=text name=LastName value=" . $record['LastName'] . " </td>";
echo "<td>" . "<input type=text name=ClientID value=" . $record['ClientID'] . " </td>";
echo "<td>" . "<input type=text name=Diagnosis value=" . $record['Diagnosis'] . " </td>";
echo "<td>" . "<input type=text name=Gender value=" . $record['Gender'] . " </td>";
echo "<td>" . "<input type=text name=LevelCare value=" . $record['LevelCare'] . " </td>";
echo "<td>" . "<input type=text name=Counselor value=" . $record['Counselor'] . " </td>";
echo "<td>" . "<input type=hidden name=hidden value=" . $record['ClientID'] . " </td>";
echo "<td>" . "<input type=submit name=update value=update" . " </td>";
echo "<td>" . "<input type=submit name=delete value=delete" . " </td>";
echo "</tr>";
echo "</form>";
}
echo "<form action=mydata5.php method=post>";
echo "<tr>";
echo "<td><input type=text name=ufirstname></td>";
echo "<td><input type=text name=umiddlename></td>";
echo "<td><input type=text name=ulastname></td>";
echo "<td><input type=text name=uclientid></td>";
echo "<td><input type=text name=udiagnosis></td>";
echo "<td><input type=text name=ugender></td>";
echo "<td><input type=text name=ulevelcare></td>";
echo "<td><input type=text name=ucounselor></td>";
echo "<td>" . "<input type=submit name=add value=add" . " </td>";
echo "</form>";
echo "</table>";
mysql_close($con);
?>
</body>
</html>
Ok I changed the page to sqli but now when I try to add a record nothing happens and I cannot find the error, I had it working until I started adding more fields then first/last names. I think I have narrowed the error to
if ($stmt = $mysqli->prepare("INSERT clients (FirstName, MiddleName, LastName) VALUES (?,?, ?)"))
{
$stmt->bind_param("ss", $FirstName, $MiddleName, $LastName);
$stmt->execute();
$stmt->close();
}
But I have no idea how to fix it. I found the error!!! Ive only been learning php and MySQL for a week. I still have a lot to learn...
<?php
/*
Allows the user to both create new records and edit existing records
*/
// connect to the database
include("connect-db.php");
// creates the new/edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($first = '', $middle = '', $last = '', $ClientID = '', $error = '', $ID = '')
{ ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
<?php if ($ID != '') { echo "Edit Record"; } else { echo "New Record"; } ?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1><?php if ($ID != '') { echo "Edit Record"; } else { echo "New Record"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form action="" method="post">
<div>
<?php if ($ID != '') { ?>
<input type="hidden" name="ID" value="<?php echo $ID; ?>" />
<p>ID: <?php echo $ID; ?></p>
<?php } ?>
<strong>First Name: *</strong> <input type="text" name="FirstName"
value="<?php echo $first; ?>"/><br/>
<strong>Middle Name: *</strong> <input type="text" name="MiddleName"
value="<?php echo $middle; ?>"/>
<strong>Last Name: *</strong> <input type="text" name="LastName"
value="<?php echo $last; ?>"/>
<strong>Client ID: *</strong> <input type="text" name="ClientID"
value="<?php echo $ClientID; ?>"/>
<strong>Diagnosis: *</strong> <input type="text" name="Diagnosis"
value="<?php echo $last; ?>"/>
<strong>Gender: *</strong> <input type="text" name="Gender"
value="<?php echo $last; ?>"/>
<strong>Counselor: *</strong> <input type="text" name="Counselor"
value="<?php echo $last; ?>"/>
<p>* required</p>
<input type="submit" name="submit" value="Submit" />
</div>
</form>
</body>
</html>
<?php }
/*
EDIT RECORD
*/
// if the 'ID' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['ID']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'ID' in the URL is valid
if (is_numeric($_POST['ID']))
{
// get variables from the URL/form
$ID = $_POST['ID'];
$FirstName = htmlentities($_POST['FirstName'], ENT_QUOTES);
$MiddleName = htmlentities($_POST['MiddleName'], ENT_QUOTES);
$LastName = htmlentities($_POST['LastName'], ENT_QUOTES);
$ClientID = htmlentities($_POST['ClientID'], ENT_QUOTES);
// check that FirstName and LastName are both not empty
if ($FirstName == '' || $MiddleName == '' || $LastName == '' || $ClientID == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($FirstName, $MiddleName, $LastName, $ClientID, $error, $ID);
}
else
{
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE clients SET FirstName = ?, MiddleName = ?, LastName = ?, ClientID = ?
WHERE ID=?"))
{
$stmt->bind_param("ssi", $FirstName, $MiddleName, $LastName, $ClientID, $ID);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: view.php");
}
}
// if the 'ID' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'ID' value is valid
if (is_numeric($_GET['ID']) && $_GET['ID'] > 0)
{
// get 'ID' from URL
$ID = $_GET['ID'];
// get the recod from the database
if($stmt = $mysqli->prepare("SELECT * FROM clients WHERE ID=?"))
{
$stmt->bind_param("i", $ID);
$stmt->execute();
$stmt->bind_result($ID, $FirstName, $MiddleName, $LastName, $ClientID);
$stmt->fetch();
// show the form
renderForm($FirstName, $MiddleName, $LastName, $ClientID, NULL, $ID);
$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'ID' value is not valid, redirect the user back to the view.php page
else
{
header("Location: view.php");
}
}
}
/*
NEW RECORD
*/
// if the 'ID' variable is not set in the URL, we must be creating a new record
else
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// get the form data
$FirstName = htmlentities($_POST['FirstName'], ENT_QUOTES);
$MiddleName = htmlentities($_POST['MiddleName'], ENT_QUOTES);
$LastName = htmlentities($_POST['LastName'], ENT_QUOTES);
$ClientID = htmlentities($_POST['ClientID'], ENT_QUOTES);
// check that FirstName and LastName are both not empty
if ($FirstName == '' || $MiddleName == '' || $LastName == '' || $ClientID == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($FirstName, $MiddleName, $LastName, $ClientID, $error);
}
else
{
// insert the new record into the database
if ($stmt = $mysqli->prepare("INSERT clients (FirstName, MiddleName, LastName, ClientID) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $FirstName, $MiddleName, $LastName, $ClientID);
$stmt->execute();
$stmt->close();
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare SQL statement.";
}
// redirec the user
header("Location: view.php");
}
}
// if the form hasn't been submitted yet, show the form
else
{
renderForm();
}
}
// close the mysqli connection
$mysqli->close();
?>
First, you're not escaping your value attributes. That's probably the cause of your <td that you're seeing.
You've got:
echo "<td>" . "<input type=text name=MiddleName value=" . $record['MiddleName'] . " </td>";
EDIT To demonstrate, the output from this assuming there was no MiddleName ("" should be: <td><input type=text name=MiddleName value= </td>, that doesn't look right. The output from below would be: <td><input type="text" name="MiddleName" value=""></td> now you can see that empty MiddleName value is "" in the HTML - an empty string there as well.
And it should be:
echo "<td><input type=\"text\" name=\"MiddleName\" value=\"" . $record['MiddleName'] . "\"></td>";
That should resolve that issue. Notice that I've placed \" around your attributes. This is not PHP, this is HTML, all attribute values should be enclosed in quotes (I could have used single quotes (') but I prefer double quotes).
The second problem is also a simple solution but again, not PHP - this is a SQL question.
A search is basically where X is like Y. There is actually an operator for this in SQL, LIKE. Now, this example isn't necessarily the most efficient means of searching, but it's definitely useful.
So you're getting the name from the request.
$name = $_REQUEST["query"];
// NEVER DO THE FOLLOWING, NOT EVER. Never trust input from a user, NEVER.
// Don't even think about putting input from the user in a query like this.
// If this input was: "'; DROP TABLE users; --" then you just lost your
// user database.
// $sql = "SELECT * FROM users WHERE FirstName LIKE '%" . $name . "%';";
// Do this instead (with mysqli, not mysql)
$sql = "SELECT * FROM users WHERE FirstName LIKE '%" . mysqli_real_escape_string($conn, $name) . "%';";
// Now search
$results = mysqli_query($conn, $sql);
// Do something with results.
And of course, finally - pagination. You want to paginate. That's a good idea. Here's a simple way to do that. First things first, you'll want to pass a piece of query data along with your request, like ?page=1 on the end of your URLs. This is important.
const PER_PAGE = 30;
if (array_key_exists($_REQUEST, "page")) {
$page = intval($_REQUEST["page"]);
} else {
$page = 1;
}
$offset = PER_PAGE * ($page - 1);
$sql = "SELECT * FROM users LIMIT " . $offset . ", " . PER_PAGE . ";";
$res = mysqli_query($conn, $sql);
// Render your page links:
// leave php, no need to echo every line of HTML.
// Fetch the count of total users with:
// SELECT COUNT(id) FROM users; -- replace id with your primary key field
// and then get your number of pages by '$count / PER_PAGE'
?>
<?php if ($pageCount > 1) { ?>
<div class="pagination">
<?php if ($page > 1) { ?>
Previous
<?php } else { ?>
<span>Previous</span>
<?php } ?>
<?php for ($i = 1; i < $pageCount; $i++) {
if ($page === $i) { ?>
<span class="current-page"><?php echo $i; ?></span>
<?php } else { ?>
<?php echo $i; ?>
<?php }
} ?>
<?php if ($page < $pageCount) { ?>
Next
<?php } else { ?>
<span>Next</span>
<?php } ?>
</div>
<?php } ?>
It is rather ugly with the embedded PHP, my apologies for that. There are other alternatives but I wouldn't want to push too much into one post for a newbie.
EDIT
Obviously you might want to make your pagination smarter. Like, if you have 10 pages you might not want to see: Previous 1 2 3 4 5 6 7 8 9 10 Next if you're onw page 7, you might just want to show: Previous 5 6 7 8 9 Next or some other alternative to keep your list from getting out of control. I didn't demonstrate this, I demonstrated the basic form of Pagination that you can start with and then you can try to modify that with to achieve your desired goals.
For further study I would like to give you some topics to research once you feel you've gotten a grasp on these and other basic tasks.
Prepared statements - while the way I showed you (using mysqli_real_escape_string()) is safer than adding the string directly to the query, prepared statements are even safer than that.
PDO - A seemingly logical next step up the chain of database access is PDO - basically building an ORM for you Database objects (and, I guess, also ORM).
Different pagination techniques, not just of rendering the links. But try your hand with "infinite scrolling." this will require some knowledge of AJAX.
AJAX - need to know some JavaScript and I'd recommend doing this, at first, without something like jQuery.
Something like jQuery, building interactive applications.
From there, I hope you're already finding new things to learn that are referenced when trying to seek the above. This is all basic web development knowledge that would be good to have.
For first part, you don't have quotes outputting correctly.
echo "<td>" . "<input type=text name=MiddleName value=" . $record['MiddleName'] . " </td>";
should be
echo "<td>" . '<input type="text" name="MiddleName" value="' . $record['MiddleName'] . '"/> </td>';
or
echo "<td><input type='text' name='MiddleName' value='{$record['MiddleName']}'></td>";
You can use variables inside double quotes in PHP. You can access array inside if you surround with curly braces, you can also access objects. I feel it is more readable but some like to concatinate.
For second par, you can use GET variables in url, such as index.php?page=1&per_page=10
For searching
$query = "SELECT * FROM clients WHERE FirstName = '$firstName'";
// or
$query = "SELECT * FROM clients WHERE FirstName LIKE '%$firstName%'";
Also, the mysql driver is being removed in the next version of PHP, as it has been deprecated for a while, mysqli should be used instead.
As Xeridea wrote check your html. And if you need to display 10 results change your sql request to
$sql = "SELECT * FROM clients LIMIT 10";
or if you need clienst 10 - 20
$sql = "SELECT * FROM clients LIMIT 10,10";
first 10 - from,
second how many
if you need select clients the name is John
$sql = "SELECT * FROM clients WHERE name = 'John';
Create dinamicly links depends on pages(you can set it in url $_GET request) and use LIMIT to flip pages. Good luck.
You just have to add below code before select query and use my select query.
$SearchString = ''; if(isset($_POST['searchtext']) &&
$_POST['searchtext']!=''){ $searchtext = $_POST['searchtext'];
$SearchString = " WHERE FirstName LIKE "'.$searchtext.' ";
mysql_query($AddQuery, $con); };
$sql = "SELECT * FROM clients".$SearchString;

how can i Select data from database using input type box and print on same page

THIS IS MY CODE HERE I AM GETTING PROBLEM THIS IS A INPUT TYPE TAG AND NOT SELECTED DATA FROM DATABASE USING PHP.
here is first part of this code is html formatted ad second part is php
i want select data from database to data slect to same page as we see on the sopping cart sites
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>phpSelect</title>
</head>
<body>
Insert Age for search
<form action="#" method="post" >
<input type="text" id="val" name="resValue" />
<input type="submit" value="submit" /></form>
<?php
if(isset($_POST['submit']))
{
$res=$_POST['resValue'];
echo $res;
}
//echo $res;
$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons where Age=25");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
Try changing the SQL to this
SELECT * FROM Persons where Age='".mysql_escape_string($formValue['val'])."'
First issue I found on your code is here:
<input type="submit" value="submit" />
it should be:
<input type="submit" value="submit" name="submit" />
To be able to get the results. Below are the codes:
<?php
$query = "";
if(isset($_POST['submit']))
{
$res=$_POST['resValue'];
$query = " where Age='$res'"
}
//echo $res;
$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons $query");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Change your select query to this one.
SELECT * FROM Persons where Age='".mysql_escape_string($_POST['val'])."'
In your problem the all value of form get by the name of all fields of form.\
so here should be
<input type="submit" name="submit" value="submit"/>
Because in $_POST['submit'] submit is same as button's name.
$result = mysqli_query($con,"SELECT * FROM Persons where Age="25");

Updating mysql database using While loop php

This has been bugging me for 3 days now.. I'm new to this and trying to get my head round something. I have a form which involves 3 fields. Firstname, Surname, Marks. I have used a while loop to generate the table from a mysql table. I have used a text box and used the loop to call the text box after the 'ID' so each text box is named uniquely. I am then using a post method to send values to a second page which will update the 'marks' column with the value the user has just put in.. this is where I am finding my problem!
This is the initial page.
<html>
<head><title>Please Enter Your Surname</title></head>
<body>
<center>
<h2><font color=blue>Please Enter Your Surname</font></h2><p>
<form action="insert.php" method="POST">
<?php
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("session6",$db)or do_error("Could not connect to the database");
$result = mysql_query("SELECT * FROM members ORDER BY id",$db);
$rows=mysql_num_rows($result);
if(!$rows)
{
do_error("No results found");
}
else
{
echo "<table border=3 cellspacing=1 cellpadding=1
align=center bgcolor=lightblue>\n";
echo "<caption><h2><font color=blue> Members Details
</font></h2></caption>\n";
echo "<tr><th>Member Id</th><th>Firstname</th><th>Mark</th></tr>\n";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td strong>" . $row['Id'] . "</td>";
echo "<td strong>" . $row['Firstname'] . "</td>";?>
<td strong><input type="text" name="<?php echo $row['Id']; ?>" size="20"></td>
<tr>
<?php
}
?><input type="hidden" name="no_of_rows" value="<?php echo $rows; ?>">
<?php
echo "</table>\n";
}
mysql_close($db) or do_error("Could not close connection");
function do_error($error)
{
echo $error;
die();
}
?>
<input type="submit" value="Search">
<input type="reset" value="Reset">
</form>
</body></html>
`
Then the update is done here which is where I seem to be having a problem:
<html>
<body>
<?php
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("marks",$db)or do_error("Could not connect to the database");
$i=1;
while ($i <= $_POST["no_of_rows"])// or $_POST["No_of_Rows"] from form
{
$insertsql = "UPDATE members SET mark = " . $_POST[$i] . " WHERE Id = " . $row['Id'] . ";";
echo $_POST['$i'];
$i++;
}
?>
</body></html>
When I echo $_POST[$i'] it shows the correct values but does not update the DB, and I'm not about ready to throw my laptop in the bin! ha! I know it is prob going to be something stupid I just can't see what, so any help would be appreciated.
You're missing the single quotes in your update query. This would help:
$insertsql = "UPDATE `members` SET `mark` = '" . $_POST[$i] . "' WHERE `Id` = '" . $row['Id'] . "' ;";
you are also not running the mysql_query query command for the update
lastly you are using the mysql php commands which are deprecated. Use mysqli or pdo instead. and don't forget to escape data in your queries to prevent sql injections
Problem is the single quotes here, forcing to literal '$i' which probably isnt a key in $_POST
echo $_POST["$i"];
No need to use quotes when variable is used:
$_POST[$id];

Session array keeps overwriting rather than adding to itself

Ran into an issue today that I have not been able to resolve. I am trying to set up a very basic shopping cart for a project. I have a searchable form on the page searchFilm.php that will retrieve a list of 10 films based on your search criteria. This works without issue. I also have an "Add" button beside each film in the list, that also works well.
When I click "Add" it redirects to another page, as intended, called addToCart.php. This page will then display the information for the film added, which is Title and Rental Rate.
This also has worked without issue. Both pages use a central page call dbConnect.php to connect to and select from the database.
The issue I have run into is trying to create a session array that will hold the film_id of each film that I add, and add them to a table. It keeps overwriting the last value that was held in the array. I have commented out almost everything on the addToCart page to try and simplify my debugging. At this point it seems like I am perhaps starting a new session every time I click add.
I will provide the code for each page. I have been trying to figure this out for 4-5 hours without success. Hoping that another pair of eyes might see something I am missing.
Thanks.
dbConnect.php:
<?php
function connect($db)
{
if(!$db)
{
die('Could not connect to the Sakila Database: ' . mysqli_error($db));
}
return $db;
}
function select($db, $table, $id)
{
$result = mysqli_query($db, "SELECT * from " . $table . " where film_id = '" . $id . "'");
if(!$result)
{
die('Could not retrieve records from the Sakila Database: ' . mysqli_error($db));
}
return $result;
}
function searchResult($db, $table, $term)
{
$result = mysqli_query($db, "SELECT * from " . $table . " where description LIKE ('%" . $term . "%') LIMIT 0,10");
if(!$result)
{
die('Could not retrieve records from the Sakila Database: ' . mysqli_error($db));
}
return $result;
}
?>
searchFilm.php:
<html>
<head>
<title>TITLE!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
include'dbConnect.php';
session_start();
if(isset($_POST['search']))
{
$term = $_POST['search'];
//connect to the database
$db = connect(mysqli_connect("localhost","root","","sakila"));
//retrieve results from the database
$result = searchResult(mysqli_connect("localhost","root","","sakila"),'film', $term);
//echo the title and description of each row
echo "<table border=1 bordercolor=red>";
echo "<tr>";
echo "<th>Title</th>";
echo "<th>Description</th>";
echo "<th>Add To Cart</th>";
echo "</tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td> <td>" . $row['description'] . "</td>";
?>
<td>
<form name="addToCart" action="addToCart.php" method="POST">
<input type="hidden" name="filmID" value="<?php echo $row['film_id']; ?>" />
<input type="submit" name="addToCart" value="Add" />
</form>
</td>
<?php
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
}
?>
<form method="post" action="searchFilm.php" name="">
<p>Search:
<input name="search" type="text" value="" />
</p>
<p>
<input name="" type="submit">
</p>
</form>
</body>
</html>
addToCart.php:
<?php
include('dbConnect.php');
if(isset($_POST['filmID']))
{
$id = $_POST['filmID']; //the item selected
$_session['cart'][] = $id;
foreach ($_session['cart'] as $item)
{ //display contents of array
echo "$item<br />";
}
/*$filmid = $_POST['filmID'];
$_SESSION['cart'][$filmid];
$db = connect(mysqli_connect("localhost","root","","sakila"));
$select = select(mysqli_connect("localhost","root","","sakila"),'film', $filmid);
echo "<table border=1 bordercolor=red>";
echo "<tr>";
echo "<th>Film</th>";
echo "<th>Rental Rate</th>";
echo "</tr>";
while($row = mysqli_fetch_assoc($select))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td> <td>" . $row['rental_rate'] . "</td>";
echo "</tr>";
}
echo "</table>";*/
}
?>
<html>
<head>
<title>TITLE!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
click to go back
</body>
</html>
Sorry for the length. Just wanted to make sure that all information was there.
Any insight would be appreciated.
Thanks!
PS. I know my database is very insecure. It's just full of dummy data and run every once in a while on a VM, so I don't really care. :P
1) Try starting the session in addToCart.php
2) As far as I know, $_session won't work, it should be $_SESSION
addToCart.php should call session_start(); and it doesn't as far as I can see.
I believe the issue is that there doesn't appear to be a call to session_start() in the addToCart.php file.
Since you aren't starting a session, none of the previous data is available. Essentially you are creating an array called $_SESSION and adding your cart array to it.
This results in using an array with the same name as PHP's session array, but it is not based off of an existing session.

Deleting multiple rows from mysql with checkbox?

I would like to apologize if the duplicate of this question exist. i tried to find and could find anything here that could solve my problem..
I am using a form to get the input and update it in the mysql database, and then retrieve the records in the html form, and have defined the code for deleting the records individually through hyperlinks. however i want to do more, i want to use the checkboxes to delete the multiple records.
my code goes like this.
<?php
//include connection string
include('connection.php');
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post"/>
Username : <input type="text" name="user"/><br />
Password : <input type="password" name="pass"/><br />
<input type="submit" name="submit" value="Send"/>
</form>
<?php
// query to insert into database
if(isset($_POST['user']) && isset($_POST['pass'])) {
$user = empty($_POST['user']) ? die(mysql_error()) : mysql_escape_string($_POST['user']);
$pass = empty($_POST['pass']) ? die(mysql_error()) : sha1(mysql_escape_string($_POST['pass']));
$query = "INSERT INTO users(name, pass) VALUES ('$user', '$pass')";
$result = mysql_query($query) or die(mysql_error());
}
if(isset($_GET['id'])) {
//query to delete the records
$query = "DELETE FROM users WHERE id = " . intval($_GET['id']);
$result = mysql_query($query);
}
//query to retrieve records
$query = "SELECT * FROM users";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
echo "<table cellpadding=10 border=1>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>delete";
echo "</tr>";
}
echo "</table>";
}
?>
i would like you to know that i am a newbie to programming world and i am not so sure of how exactly html checkbox work and how do i use it to delete the multiple records. i want to know what extra code do i have to write for it, and i would appreciate a lot if someone explains me that extra code in brief..
thank you..
This is probably a good time for another form:
<?php
// query to insert into database ...
// ... etc...
if(isset($_POST["formDeleteSelected"])) {
//query to delete the records
$query = "DELETE FROM users WHERE id IN (" . implode(", ",$_POST["rowid"]) . ")";
$result = mysql_query($query);
header("Location: mycode.php"); // just so 'refresh' doesn't try to run delete again
exit();
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<?php
//query to retrieve records
$query = "SELECT * FROM users";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
echo "<table cellpadding=10 border=1>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td><input type="checkbox" name="rowid[]" value=\"" . $row[0] . "\" /></td>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
<input type="submit" name="formDeleteSelected" text="Delete Selected" />
</form>
Or something like that (I haven't actually tried that code so there may be a typo). Also note that you should make sure to sanitize any form/get inputs for SQL Injection (plenty of information on that in other Stack Overflow questions).
First of all you need a checkbox and the id you want to delete:
<input id="delete" type="checkbox" name="delete" /><label for="delete">Delete user</label>
<input type="hidden" name="user_id" value="12345" />
You can then test if the checkbox has been set and then manually set the GET parameter to reuse your existing code:
if(isset($_POST['delete'])){
$_GET['id'] = $_POST['user_id'];
}
That's not the most elegant solution but a really simple one that should work with your code.
try an SQL query with a list of IDs
... WHERE id=$sentIds[0] OR id=$sentIds[1] OR ...
or use a set operation
... WHERE id IN ($i1,$i2 ... );
You sure have to send ids in the form for this to work, but You know that ;)

Categories