Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to post data to a table in my database, but there is no error messages as to why the data is not posted. I have inserted data into the table in phpmyadmin and this data is printed with the result while loop, but data will not post to the table.
<!-- form to take input-->
<form name='form1' method='post'>
Name:
<input type='text' name='Name' id='name' /> <br />
Comment:
<input type='text' name='Comment' id='comment' /> <br />
<input type="submit" name='submit' value="Submit" id='submit'>
</form>
<!-- start php-->
<?php
if(isset($_POST['submit']))
{
$name = $_POST['Name'];
$comment = $_POST['Comment'];
}
$con = mysqli_connect("localhost", "kodie", "hill1124", "comments");
if(mysqli_connect_errno())
{
echo "Failed to connect to MySql: ". mysqli_connect_error();
}
mysqli_query($con, "INSERT INTO commenttable VALUES ('$name','$comment',NOW()");
$query = "SELECT * FROM commenttable";
$result = mysqli_query($con, $query);
$hash = $result;
echo "<table>";
if($hash = NULL)
{
echo "null";
}
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['Name'] . "</td><td>" . $row['comment'] . "</td><td>" . $row['timestamp'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>";
mysqli_close($con);
?>
I am unsure why it won't post, I don't think it is permissions but I am new to using mysql and don't understand why the statement compiles without errors but doesn't actually put the data on the table.
Any help is appreciated.
In order to INSERT data in your database you need to adjust the insert query.
What you have now:
mysqli_query($con, "INSERT INTO commenttable VALUES ('$name','$comment',NOW()");
Should be
mysqli_query($con, "INSERT INTO commenttable VALUES ('$name', '$comment', NOW())");
You should also consider using mysqli_real_escape_string to prevent SQL-injection
So:
$name = $_POST['Name'];
$comment = $_POST['Comment'];
Becomes:
$name = mysqli_real_escape_string($con, $_POST['Name']);
$comment = mysqli_real_escape_string($con, $_POST['Comment']);
You can also take a look at the following:
http://php.net/manual/en/mysqli.real-escape-string.php;
http://nl3.php.net/manual/en/function.trim.php (removes left over spaces);
http://nl3.php.net/manual/en/function.strip-tags.php (Optional removes html tags from string)
UPDATE
<!-- form to take input-->
<form action="" name="form1" method="post">
Name:
<input type="text" name="Name" id="name"> <br>
Comment:
<input type="text" name="Comment" id="comment"> <br>
<input type="submit" name='submit' value="Submit" id="submit">
</form>
<!-- start php-->
<?php
if($_POST) {
$con = mysqli_connect("localhost", "kodie", "hill1124", "comments");
$name = mysqli_real_escape_string($con, trim($_POST['Name']));
$comment = mysqli_real_escape_string($con, trim($_POST['Comment']));
if (mysqli_connect_errno()) {
echo "Failed to connect to MySql: " . mysqli_connect_error();
}
if (!empty($name) && !empty($comment)) {
$query = mysqli_query($con, "INSERT INTO commenttable VALUES ('$name','$comment',NOW())");
// Check if the query succeeded
if (mysqli_affected_rows($con)) {
$query = "SELECT * FROM commenttable";
$result = mysqli_query($con, $query);
$hash = $result;
echo "<table>";
}
} else {
echo 'Something went wrong: '. mysqli_error($con); // Echo the error (You could replace echo with die())
}
}
if ($hash = NULL) {
echo "null";
}
while ($row = mysqli_fetch_array($result)) {
echo "<tr><td>" . $row['Name'] . "</td><td>" . $row['comment'] . "</td><td>" . $row['timestamp'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>";
mysqli_close($con); // this is not necessary
}
?>
You are missing a closing ) at the end of your insert statement:
mysqli_query
($con,
"INSERT INTO commenttable VALUES ('$name','$comment',NOW())");
// This one ^
See the line mysqli_query($con, "INSERT INTO commenttable VALUES ('$name','$comment',NOW()");
You havnt Closed the mysqli_query().
It must be mysqli_query($con, "INSERT INTO commenttable VALUES ('$name','$comment',NOW()"));
Make sure User "kodie" have privileges to do INSERT
Missing parenthesis in
mysqli_query($con, "INSERT INTO commenttable VALUES ('$name','$comment',NOW()");
should be
mysqli_query($con, "INSERT INTO commenttable VALUES ('$name','$comment',NOW()")); // missing )
Related
MySql query returns with blank page using 2 submit button form.
get a blank page with no errors when i run this. i am able to display the whole db but have trouble searching through and displaying matches.
index.html page:
<form action="subjsearch.php" method="post">
<label>First Name:</label><input type="text" name ="firstname"><br><br>
<label>Last Name:</label><input type="text" name ="lastname"><br><br>
<label>Age:</label><input type="text" name="age" size = "2"><br><br>
<label>Tattoo:</label><input type="text" name ="tattoo"><br><br>
<label>Moniker:</label><input type="text" name ="moniker"><br><br>
<input type="submit" name="submitBTN" value="Submit">
<input type="submit" name="searchBTN" value="Search">
<input type="reset" name="resetBTN" value="Reset">
</form>
action page:
<?php
include 'db.php';
if(isset($_POST['submitBTN'])){
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];
$tattoo = $_POST['tattoo'];
$moniker = $_POST['moniker'];
$query = "INSERT INTO subjects (firstName,lastName,age,tats,moniker)VALUES(
'$firstname',
'$lastname',
'$age',
'$tattoo',
'$moniker')";
if ($conn->query($query) === TRUE) {
echo "New record created successfully";
} elseif(isset($_POST['searchBTN'])){
$query = "SELECT * FROM subjects WHERE firstName = '$firstname' OR lastName = '$lastname' OR age = '$age' OR tats = '$tattoo' OR moniker = '$moniker' ";
$result = $conn->query($query);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th><th>AGE</th><th>Tattoo</th><th>Moniker</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstName"]." ".$row["lastName"]."</td><td>".$row["age"]."</td><td>".$row["tats"]."</td><td>".$row["moniker"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
$conn->close();
}
?>
Search won't work as it's inside the if(isset($_POST['submitBTN'])) {..} block. Moved the if(isset($_POST['searchBTN'])) {..} block outside of if(isset($_POST['submitBTN'])) {..} block.
Also did escape of input values to avert SQL injections. Preferred way is prepared statement tho.
Updated Code:
<?php
include 'db.php';
$firstname = $conn->real_escape_string(isset($_POST['firstname']) ? $_POST['firstname'] : '');
$lastname = $conn->real_escape_string(isset($_POST['lastname']) ? $_POST['lastname'] : '');
$age = $conn->real_escape_string(isset($_POST['age']) ? $_POST['age'] : '');
$tattoo = $conn->real_escape_string(isset($_POST['tattoo']) ? $_POST['tattoo'] : '');
$moniker = $conn->real_escape_string(isset($_POST['moniker']) ? $_POST['moniker'] : '');
if (isset($_POST['submitBTN'])) {
$query = "INSERT INTO subjects (firstName,lastName,age,tats,moniker)VALUES(
'$firstname',
'$lastname',
'$age',
'$tattoo',
'$moniker')";
if ($conn->query($query) === true) {
echo "New record created successfully";
}
$conn->close();
}
if (isset($_POST['searchBTN'])) {
$query = "SELECT * FROM subjects WHERE firstName = '$firstname' OR lastName = '$lastname' OR age = '$age' OR tats = '$tattoo' OR moniker = '$moniker' ";
$result = $conn->query($query);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th><th>AGE</th><th>Tattoo</th><th>Moniker</th></tr>";
// output data of each row
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"] . "</td><td>" . $row["firstName"] . " " . $row["lastName"] . "</td><td>" . $row["age"] . "</td><td>" . $row["tats"] . "</td><td>" . $row["moniker"] . "</td></tr>";
}
echo "</table>";
}
else {
echo "0 results";
}
}
?>
This is my code which shows current events and lets the user change the date, name or venue of the event.
I keep getting a 500 error for some reason. I think it is due to the information being passed to and from the database.
database set up is :userid ,eventname, venue, date, name ,eventid... respectivley
<div class="current events">
<h1>Your Current Events:</h1>
<?php
$sql = "SELECT * FROM events WHERE userid='{$_SESSION['u_id']}';";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<b>Event name: </b>";
echo " ";
echo $row['eventname'];
echo " ";
echo "<b>Event Venue: </b>";
echo " ";
echo $row['venue'];
echo " ";
echo "<b>Event Date: </b>";
echo " ";
echo $row['date'];
echo "
<form method='POST' action='editevent.php'>
<input type='hidden' name='eventname' value='" .$row['eventname']. "'>
<input type='hidden' name='venue' value='" .$row['venue']. "'>
<input type='hidden' name='date' value='" .$row['date']. "'>
<input type='hidden' name='name' value='" .$row['name']. "'>
<button>Edit</button>
</form>
";
}
}else{
echo "No Upcoming Events";
}
?>
</div>
I then have another file in my includes directory which allows changes to the information.
<?php
session_start();
if (isset($_POST['eventsubmit'])) {
$eventname = $_POST['eventname'];
$venue = $_POST['venue'];
$date = $_POST['date'];
$name = $_POST['name'];
$eventname = mysqli_real_escape_string($conn, $_POST['eventname']);
$venue = mysqli_real_escape_string($conn, $_POST['venue']);
$date = mysqli_real_escape_string($conn, $_POST['date']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
$sql = "UPDATE events SET eventname='$eventname' WHERE userid='2' ";
mysqli_query($conn, $sql);
header("Location: ../members.php?event=success");
exit();
} else {
header("Location: ../signup.php");
exit();
}
}
I check your code in second php file you put one extra this } please remove it.
please use mysqli_error instruction to get exactly which error you get
mysqli_query($conn, $sql)or die( mysqli_error($conn));
or you can use to show php error if there any error in php syntax in start of page
error_reporting(E_ALL);
ini_set('display_errors', 1);
I wonder if anyone could help me with my problem? I want to send value (input text) to mysql database but it is always blank text. I am the beginner and I think I've made stupid mistake... Code:
<form name="form" method="get">
<input type="text" name="nick">
<input type="text" name="message" height="300px">
</form>
<?php
$servername = "localhost";
$username = "root";
$password = "xxx";
$dbname = "xxxxx";
if (isset($_POST['button1']))
{
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$nickval = $_POST['nick'];
$messageval = $_REQUEST['message'];
$sql = "INSERT INTO Messages (nick, message)
VALUES ('$_GET[nick]', '$_GET[message]')";
if ($conn->query($sql) === TRUE) {
echo "OK";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$result = mysqli_query($conn,"SELECT * FROM Messages");
echo "<table border='1'>
<tr>
<th>Nick</th>
<th>Message</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['nick'] . "</td>";
echo "<td>" . $row['message'] . "</td>";
echo "</tr>";
}
echo "</table>";
$conn->close();
}
?>
<form method="POST" action=''>
<input type="submit" name="button1" value="Send">
</form>
This:
<input type="submit" name="button1" value="Send">
needs to go inside your first form, where your other inputs are.
<form name="form" method="post">
<input type="text" name="nick">
<input type="text" name="message" height="300px">
<input type="submit" name="button1" value="Send">
</form>
And also #Joe T's answer. Many problems wrong with this question it seems
Your SQL should look more like this, the other answer is also right (about moving your submit button inside the same form with your inputs)
$nickval = mysqli_real_escape_string ( $conn , $_POST['nick']);
$messageval = mysqli_real_escape_string ( $conn , $_POST['message']);
$sql = "INSERT INTO Messages (nick, message)
VALUES ( '$nickval', '$messageval')";
As the commenter wrote, don't use $_REQUEST and $_GET, only $_POST is used here.
And if you don't escape your inputs, (as i've done here with mysqli_real_escape_string) you are asking for a world of hurt.
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());
}
}
?>
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 ;)