PHP code executes but no output - php

I am trying to learn "searching elements from mysql database using php".
For this I created a database named randomdata. In randomdata database there is a table named randomtable. In this table there are four columns: Name, Surname, Email and Gender.
I want to search people by there Gender. For this I tried following query.
$query="SELECT * FROM randomtable WHERE Gender =' ".$gender . " ' ";
I tried both, GET and POST functions. But still I am not able to take output. I am using these.
Windows 8
Wampserver
Notepad++
I restarted server and PC, but nothing changed. Below is my complete code.
Find Entries:
Male
Female
<?php
if(isset($_POST['submit']))
{
echo $gender=$_POST['$gender'];
$connect=mysql_connect("127.0.0.1","root","", "randomdata");
if($connect)
{
//echo 'I am connected';
$query="SELECT * FROM randomtable WHERE Gender =' ".$gender . " ' ";
echo $query;
$results=mysqli_query( $connect,$query);
while($row = mysqli_fetch_array($results))
{
echo $row['Name'] . "<br/>" . $row['Surname'] . "<br/>" . $row['Email'] . "<br/>" ;
}
}
else
{
die(mysql_error());
}
}
?>

It looks like the issue is with assigning the POST variable to $gender
Currently you are using
echo $gender=$_POST['$gender'];
Please try changing this to
$gender=$_POST['gender'];
UPDATE
After testing your code it seems the isset is the issue. There is never a POST['Submit'].
To fix this you need the name attribute in the submit input ie
<input type="submit" Value="Search" name="Submit"/>
Also in the query you have spaces either side of the $gender variable. I now have the code working, try with this.
<html>
<body>
Find Entries: <br>
<form action="" method="POST">
<input type="radio" name="gender" Value="Male"> Male </input>
<br>
<input type="radio" name="gender" Value="Female"> Female </input>
<br>
<input type="submit" Value="Search"/>
</form>
<?php
if(isset($_POST['gender']))
{
//print_r($_POST);
$gender=$_POST['gender'];
$connect=mysqli_connect("127.0.0.1","root","password", "randomdata");
if($connect)
{
//echo 'I am connected';
$query="SELECT * FROM randomtable WHERE Gender = '".$gender . "' ";
//echo $query;
$results=mysqli_query( $connect,$query);
while($row = mysqli_fetch_array($results))
{
echo $row['Name'] . "<br/>" . $row['Surname'] . "<br/>" . $row['Email'] . "<br/>" ;
}
}
else
{
die(mysql_error());
}
}
?>

mysql_connect should be mysqli_connect

Try this...
$query="SELECT * FROM randomtable WHERE Gender ='".$gender . "'";
Removed extra spaces in query

Is there no output at all? Very odd indeed.
What are you posting?
Are you sure that you're including 'submit' in your test post?
If this doesn't help, perhaps there's a more severe error that's not allowing the script to run? Are you able to see the php or apache error logs?

I guess you were intending to assign the "submit" index to the $gender variable instead of the "gender" index?
Try the code below:
<?php
if(isset($_POST['submit']))
{
$gender = $_POST['submit'];
$connect = mysql_connect("127.0.0.1", "root", "", "randomdata");
if($connect)
{
$query = 'SELECT * FROM randomtable WHERE Gender = "' .$gender .'"';
$results = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($results))
{
echo $row['Name'] . "<br/>" . $row['Surname'] . "<br/>" . $row['Email'] . "<br/>" ;
}
}
else
{
die(mysql_error());
}
}
?>

Related

SQL, PHP: when submit plus 1 in table_field specified from dropdown

UPDATED (*the code is working and I updated the full code :) *)
UPDATED (**edit the suggestions still dont work :) **)
Hi guys I have been looking around in many of the post in here regarding using php to plus 1 in a table_field specifed by a dropdown on the php page. I am very new to this so I just tried some things out to see if I could get it to work but for me this is not easy :)
So here we go.
as you can see in the code there is a drow down that fetch data from a member table. In this table there is a field "isMcount" when a person have chosen a member from the drop down and then press submit I need it to +1 in the "isMcount" column for that specified member which is active in the drop down
Hope you will help.
this is the table setup:
isMcount Type=int(100) Null=No Default=(as defiend)=1
<?php
require('includes/config.php'); ?>
<?php
if(isset($_POST['submit'])){
$row1 = $_POST['username'];
$row1 = mysql_real_escape_string($row1);
mysql_query("UPDATE members SET isMcount = isMcount + 1 WHERE username = '".$row1."' ") or die(mysql_error());
$_SESSION['success'] = 'Page Updated';
header('Location: '.DIRADMIN);
exit();
}
?>
<form method="post">
<select name="username">
<?php
$sql = mysql_query("SELECT username FROM members");
while ($row1 = mysql_fetch_array($sql)){
echo "<option value=\"" . $row1['username'] . "\">" . $row1['username'] . "</option>";
}
?>
</select>
<input type="submit" name="submit" value="Submit" class="button" />
</form>
You have wrong HTML part. Try option below. "username" is field name for select and will be available on $_POST['username'] with a value of username for your user.
<form method="post">
<select name="username">
<?php
$sql = mysql_query("SELECT username FROM members");
while ($row1 = mysql_fetch_array($sql)){
echo "<option value=\"" . $row1['username'] . "\">" . $row1['username'] . "</option>";
}
?>
</select>
<input type="submit" name="owner" value="submit"/>
</form>
And you can remove isMCount from $_POST in PHP as you don't need it.
And then you update query would be:
mysql_query("UPDATE members SET isMcount = isMcount + 1 WHERE username = '" . $row1 . "'");
Please check the statements within if condition:
$row1 = $row['username']; // It should be $_POST['owner']
$mc = $row['isMcount']; // You don't even need this
mysql_query("UPDATE members SET isMcount = isMcount + 1 WHERE $row1 = username");
You simply need to get the username from the POST data submitted through the form.
So, you query should be something like this:
mysql_query("UPDATE members SET isMcount = isMcount + 1 WHERE username = '".$row1."' ") or die(mysql_error());
Also, you should change your HTML to this:
echo "<option value=\"" . $row1['username'] . "\">" . $row1['username'] . "</option>";
Hope this helps.
Peace! xD
Some suspected areas are in your code
<form action="#" method="POST">
<?php
if(isset($_POST['submit'])){
$username = $row['username'];
$mc = $row['isMcount'];
$row1 = mysql_real_escape_string($row1);
$mc = mysql_real_escape_string($mc);
mysql_query("UPDATE members SET isMcount = isMcount + 1 WHERE username = '$username'");
$_SESSION['success'] = 'Page Updated';
header('Location: '.DIRADMIN);
exit();
}
?>
<select name="username">
<?php
$sql = mysql_query("SELECT username FROM members");
while ($row1 = mysql_fetch_array($sql)){
echo "<option value='".$row1['username']."'>".$row1['username']."</option>";
}
?>
</select>
<input type="submit" name="submit" value="submit"/>
</form>
Suggestion : Use mysqli or pdo instead of mysql

Form values from dropdown list not passing

I created a drop down list that has been populated by the database and now I'm having trouble retrieving the data. Normally, I would know how to retrieve the value of the drop down list if I had to manually name the data, but in this case, I'm not quite sure how I would name it.
Here is my current code:
<h1>Generate Reports</h1>
<form enctype="multipart/form-data" action="http://localhost/yiiFolder/index.php/create" method="post">
<table>
<tr>
<td><strong>Materials</strong></td>
<?php
mysql_connect('host', 'root', 'password');
mysql_select_db ("db");
$sql = "SELECT material_name FROM materials";
$result = mysql_query($sql);
echo "<td><select name='materials'>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['material_name'] . "'>" .
$row['material_name'] . "</option>";
}
echo "</select></td></tr> ";
$sql2 = "SELECT location_name From locations";
$result2 = mysql_query($sql2);
?>
<td><strong>Locations</strong></td>
<?php
echo "<td><select name='locations'>";
while ($row2 = mysql_fetch_array($result2))
{
echo "<option value='" . $row2['location_name'] . "'>" .
$row2['location_name'] . "</option>";
}
echo "</select></td></tr>";
?>
<tr>
<td><button name="submit" type=submit>Generate</button></td>
</tr>
</table>
</form>
<?php
$material = $row['material_name'];
$locations = $row2['location_name'];
$generate = $_POST['submit'];
if(isset($generate))
{
echo $material;
echo $locations;
}
?>
You're trying to capture value before the submit button is hit. Also, as Hanky pointed out you're using the wrong names while referring to select data. You should do this instead
if(isset($_POST['submit'])) // this code will run after the button is clicked
{
$material = $_POST['materials']; // and not material_name
$locations = $_POST['locations']; // and not location_name
echo $material;
echo $locations;
}
PS: You're following a very unsecure way of developing a web application. At the very least you need to switch to PDO and always escape the data.

PHP deleting from database not working

I'm trying to let the user check off which item to be deleted. When the user check off one or many items and click the Delete button, those data will be erased from the database. I've also added a search box to search for the dvd. The search box works, but the deleting doesn't. This is what it looks like in the browser.
My PHP looks like this (I took out the searching code):
<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
<?php
$link = mysqli_connect( $host, $user, $password, $dbname);
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
//searching code goes here
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']);
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)";
$resultTwo = mysqli_query($link, $queryTwo);
}
echo "<table border=\"1\"><tr><th>DvdTitle</th><th>RunningTime</th><th>Delete</th></tr>";
if (mysqli_num_rows($result) == 0)
echo "<tr><td colspan='2'>No records found.</td></tr>";
else {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row['DvdTitle'] . "</td>";
echo "<td>" . $row['RunningTime'] . "</td>";
echo "<td>" . "<form>" . "<input type='checkbox' name='deleteThese[]' value='" . $row['DvdID'] . "' >" . "</form>" . "</td></tr>\n";
}
}
echo "</table>";
mysqli_free_result($result);
mysqli_close($link);
?>
Each DvdTitle has an unique Dvd ID, hence the value of each row is the dvd's ID $row['DvdID'].
Adding the parentheses will allow for those ID's to be selected for deletion.
IN($deleteThese)
EDIT
Do not close the form after the submit button. Put that at the end of the code. This will allow the form to include the checkbox values.
<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<!-- YOUR PHP CODE -->
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
2nd Edit [requested to improve code]
Move the isset on top of the form.
<?php
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']);
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)";
$resultTwo = mysqli_query($link, $queryTwo);
}
?>
<form>....
$deletethese might need to have quotes around it.

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];

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