I'm making a very simple groups(like vb forum groups). I've coded all of it, after getting some errors and fixing it now it's showing the page without errors.
The problem now is the data ISN'T being inserted to mysql. When putting the input into forms and then pressing create it goes to "?update=update" and echo's the success message, but doesn't submit to mysql.
Code:
<? if(!$update) { ?>
<form action="make_group.php?update=update" method="post">
Group name: <br />
<input name="title" type="text" size="30" />
<br />
Group picture: <br />
<input name="picture" type="text" size="30" />
<br />
Group desc: <br />
<textarea name="desc" cols=30 rows=10 wrap=physical></textarea>
<br />
<input type="submit" value="Create" />
<? }
elseif($update==update)
{
$username = $_SESSION[usr_name];
$action = "made a group";
$title = clean($_POST[title]);
$desc = clean($_POST[desc]);
$pictures = clean($_POST[pictures]);
$updateemail = mysql_query("insert into usr_groups(username, title, desc, picture) values('$username', '$title', '$desc', '$picture')");
$result = #mysql_query($qry2);
echo("Your group has been created");
} ?>
Above page code
<?
session_start();
include("config.php");
$ip = $_SERVER['REMOTE_ADDR'];
$sqlcontent = mysql_query("select * from usr_config");
$content = mysql_fetch_array($sqlcontent);
if(!isset($_SESSION[usr_name]) || empty($_SESSION[usr_name]) || !isset($_SESSION[usr_level]) || empty($_SESSION[usr_level]))
{
session_destroy();
session_unset();
die('
<tr>
<td><meta http-equiv="REFRESH" content="0;url=/index.php"></HEAD></td>
</tr>
<tr>
<td></td>
</tr>
</table>
</div>
</body>');
}
include("func.php");
$update = clean($_GET[update]);
$getprof = mysql_query("select * from usr_users where username = '$_SESSION[usr_name]'");
$prof = mysql_fetch_array($getprof);
?>
Set off the desc with ` - amending my answer to include my comment from below - desc is a reserved word in MySQL, to declare it as a field name instead of a sort order, it must have the back ticks:)
I would suggest putting adding an OR die(mysql_error()) to the end of your mysql_query(call)
mysql_query('your query') OR die(mysql_error())
I would only do this while your debugging and not leave it on anything the public would see. This will give you information on why the INSERT query isn't working. I don't where you are connecting, but I'm assuming you left that out for security reasons :)
I do see that your statement
elseif($update==update){
doesn't have quotes around it - so it would seem like that conditional block is never being called...I see your comment, but I would consider at least for debugging purposes, throwing some quotes around it. Can't hurt right :) the die statement will tell you if you have syntax issues. Maybe consider printing something in that block as well to make sure that conditional is interpreted the way you are expecting...
FWIW your SQL appear to be fine to me - you may run into issues with the name if you ever get a ' in the name...
change $picture to $pictures
$updateemail = mysql_query("insert into usr_groups(username, title, desc, picture) values('$username', '$title', '$desc', '$pictures')");
Unable to insert if column named is keyword, such as DESC
Try to echo $updateemail and then add this code to check if there are any errors.
if (!mysql_query($updateemail,$con)) {
die('Error: ' . mysql_error());
}
echo "1 record added";
Also,change the insert query to :
$updateemail = mysql_query("insert into usr_groups(username, title, description, picture) values('$username', '$title', '$desc', '$pictures')");
change the desc column name to something.
Related
Hi every one please help me I have problem with my code . I want to store my form data into database but can not instead i got success message ( thank you for your comment)
Please help me
My form code is this
com_form.php
<form method='post'>
Name: <input type='text' name='name' id='name' /><br />
Email: <input type='text' name='email' id='email' /><br />
Comment:<br />
<textarea name='comment' id='comment'></textarea><br />
<input type='hidden' name='articleid' id='articleid' value='<? echo $_GET["id"]; ?>' />
<input type='submit' value='Submit' />
</form>
</form>
and PHP code is this
manage_com.php
<?
if( $_POST )
{
$con=mysqli_connect("localhost","root","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT name,email,comment FROM comments ";
$retval=mysqli_query($con,$sql);
$users_name = $_POST['name'];
$users_email = $_POST['email'];
$users_comment = $_POST['comment'];
$users_name = mysqli_real_escape_string($con, $_POST['$users_name']);
$users_email = mysqli_real_escape_string($con, $_POST['$users_email']);
$users_comment = mysqli_real_escape_string($con, $_POST['$users_comment']);
$articleid = $_GET['id'];
if( ! is_numeric($articleid) )
die('invalid article id');
$query = "
INSERT INTO `pricemom_comment`.`comments` (`id`, `name`, `email`,
`comment`, `post_date`, `articleid`) VALUES (NULL, '$users_name',
'$users_email', '$users_comment',
CURRENT_TIMESTAMP, '$articleid');";
mysqli_query($con,$query);
echo "<h2>Thank you for your Comment!</h2>";
mysqli_close($con);
}
?>
page where i want to show form
page1.php
<? include("manage_com.php"); ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>page1 created by Afzal</title>
</head>
<body>
<img src="nature.jpg" alt="beautifull nature image" style="width:700px; align:center;height:200px;">
<h2>page1 created by Afzal</h2>
<p style="width:700px;">order to display comments on a page, we first need to know what comments to show. When we setup our site we created two pages, and each page was assigned a unique id number. This ID number will be used to gather comments for that specific page. For example, when the user is on page 1, we'll select all of the comments in the database assigned to page "1".</p>
<p style="width:700px;"> Now that we have our sample SQL query, we can use it to create the php code that will print all comments on a page. Below is the example code that we created. If you're not familiar with php, any line that begins with a // is a comment, and comments are used by developers to document their code. In our example, we have quite a few comments to help explain what the code is doing, but keep in mind that most scripts do not have as many comments.</p>
<?php
include("com_form.php");
?>
</body>
</html>
please fix my problem . where i make mistakes
NOTE: I got success message ( thank you for you comment) but comment not store in my database
Your echo statement display success no matter what happend.
Perform a query and check for error:
if (!mysqli_query($con,$query))
{
echo("Error description: " . mysqli_error($con)); die;
}
I think that the problem is connected with wrong sql request. You try to insert NUll value for id field.
It is not inserting the session variables like name, id ,email, number like which is stored in $a,$b,$c,$d in pseller.php
This is my login page where i am checking username and password
login.php
<?php
error_reporting(E_ALL); // to see if there is error in code
include "connect_to_mysql.php";
if(isset($_POST['log']))
{
$user= $_POST['user'];
$pass= md5($_POST['pass']);
$sql=mysql_query( "select * from reg where username= '$user' AND password='$pass' AND category='product seller' LIMIT 1 ") or die( mysql_error());
$data=mysql_num_rows($sql);
if ($data == 1) {
$_SESSION['name']=$name;
$_SESSION['id']=$id;
$_SESSION['phone_no']=$number;
$_SESSION['email_id']=$email;
header("location:pseller.php");
}
else {
header("location:login.php?error");
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Log In </title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>
<div id="mainWrapper">
<div id="pageContent"><br /><br /><br />
<div align="right" style="margin-right:24px; color:#FF0000">
<br /><br />
<form id="form" name="form" method="post" action="login.php">
<h2 style="padding-right:200px;">User Name:</h2>
<input name="user" type="text" id="user" size="40" style="height:30px;" required placeholder="Enter Email"/>
<br /><br />
<h2 style="padding-right:210px;">Password:</h2>
<input name="pass" type="password" id="pass" size="40" style="height:30px;" required/>
<br />
<br />
<br />
<img style="padding-right:190px;" src="generate.php"><br /><br />
<input type="text" name="secure" size="10" required placeholder="Enter The Value" style="padding-right:210px; height:30px;">
<br />
<br />
<br />
<input type="submit" name="log" id="log" value="Log In" style="padding-right:40px;" />
</form>
<p> </p>
</div>
<br />
<br />
<br />
</div>
</div>
</body>
</html>
This is pseller page where I am trying to store session values in variables then inserting in database. but session variables are not inserting data in database and showing the value of v_id v_number as 0.
pseller.php
<?php
// Parse the form data and add inventory item to the system
include_once('connect_to_mysql.php');
session_start();
if (isset($_POST['p_name'])) {
$target_dir = "pics/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file) ;
$img_name = $_FILES["fileToUpload"]["name"];
$a=$_SESSION['name'];
$b=$_SESSION['id'];
$c=$_SESSION['phone_no'];
$d=$_SESSION['email_id'];
$product_name = mysql_real_escape_string( $_POST['p_name']);
$price = mysql_real_escape_string($_POST['price']);
$category = mysql_real_escape_string($_POST['category']);
$subcategory = mysql_real_escape_string($_POST['subcategory']);
$category2 = mysql_real_escape_string($_POST['category2']);
$details = mysql_real_escape_string($_POST['details']);
// See if that product name is an identical match to another product in the system
// Add this product into the database now
$sql = mysql_query("INSERT INTO product (p_name, price, details, category, sub_category, category2, img_name, v_id, v_name, v_number, v_email, date) VALUES('$product_name','$price','$details','$category','$subcategory','$category2','$img_name','$b','$a','$c','$d',now())") or die (mysql_error());
}
?>
Please help me to come out from here.
Ok so judging from the question and discussion in the comments, you're lacking proper handling of the user data in login.php.
There are also a couple of other points that are a bit off in your code:
You should not the mysql library as it's deprecated. You should either use mysqli, which is a rather easy switch if you're already used to mysql, or use PDO
Your code is vulnerable to SQL injection. You should use prepared statements when using user input in SQL queries. More info here for example
MD5 is not a very secure option for passwords. You can read more here
Below is a simple example of the PHP part for login.php I threw together based on what information I could gather from your question. It isn't complete for your specific database structure and needs, but should help you forward with your problem:
<?php
// Define database connection using mysqli
$mysqli = new mysqli("localhost", "username", "password", "dbname");
if(isset($_POST['log']))
{
$user= $_POST['user'];
$pass= md5($_POST['pass']); // Should be replaced by secure alternatives
// Define the SQL query string
$sql = "SELECT id, name, phone_no, email FROM reg WHERE email = ? AND password = ? LIMIT 1";
$stmt = $mysqli->prepare($sql); // Prepare the query string
$stmt->bind_param("ss", $user, $pass); // Define prepared statement parameters
// Execute the prepared stament
if ($stmt->execute())
{
$result = $stmt->get_result(); // Get the result
$data = $result->num_rows; // Get number of rows
if ($data == 1)
{
$userdata = $result->fetch_array(MYSQLI_ASSOC); // Get an associative array from the result
$_SESSION['name'] = $userdata['name'];
$_SESSION['id'] = $userdata['id'];
$_SESSION['phone_no'] = $userdata['phone_no'];
$_SESSION['email_id'] = $userdata['email'];
header("location:pseller.php");
}
}
else
{
header("location:login.php?error");
}
}
?>
$_SESSION['id']=$id;
$_SESSION['phone_no']=$number;
only get updated if select with username and password has rowcount 1
Those become variables $b and $c in pseller.php
So if $user and $pass do not get you a row on select from db, you get junk in SESSION.
mysql_num_rows returns number of rows. You are doing LIMIT 3. So if you are 0, 2, or 3, session is in trouble. Why, because your if statement says =1.
Also, you are using a deprecated mysql_* function library and acting directly upon user-supplied values that can render sql injection attacks. Use mysqli or pdo, and see this.
Include session_start(); in yourlogin.php
$sql=mysql_query("select * from reg where username= '$user'
AND password='$pass' AND category='product seller'") or die( mysql_error());
Inside the above query, Please make the changes.
Avoid making column names with spaces category='product seller'
Now echo the values under the SELECT * FROM query and the $a, $b, $c, $d to know if you REALLY are taking the values through to the next page. I am pretty much sure that you were not and also #Drew suggested, shift to msqli/PDO.
EDIT:
In your second page pseller.php try to echo and see what you're getting.
echo $_SESSION['name'];
echo $_SESSION['id'];
echo $_SESSION['phone_no'];
echo $_SESSION['email_id'];
No luck? Okay let's just try it this way and see what happens;
$sql=mysql_query("select * from reg where username= '$user' AND password='$pass'") or die( mysql_error());
if ($sql) {
while($row=mysql_fetch_array($sql))
{
echo $row['name'];
echo $row['id'];
echo $row['phone_no'];
echo $row['email_id'];
}
// header("location:pseller.php");
}
Now put the correct username and password (present in the database) and if you can see the echoed values, use sessions to store and use them later on also uncomment the header(); line and you are good to go.
Trying to get this form to add new data into my database yet for some reason it doesn't seem to work? Instead of staying on the same page "admin.php?page=3" it redirects to just "admin.php" and no echos or signs that it is even doing anything? Could someone help me out here? Cheers!
Form:
<form>
<form name="postnewstory" action="admin.php?page=3" method="POST">
<strong>News Title: </strong><input type="text" name="news_title"><br><br />
<strong>News Story:</strong><br>
<textarea name="news_body" rows="4" cols="60"></textarea><br><br />
<input type="file" name="news_photo"><br>
<strong>Story Link: </strong><br />
<input name="button" type="radio" value="0" checked="checked">No Link<br>
<input type="radio" name="button" value="1">Link<br><br />
<strong>Link Address: </strong><input type="text" name="news_link"><br>
<strong>News Story Tags: </strong><input type="text" name="news_tags">
<input type="submit" value="Post" name="postnewstory" class="btn btn-success"><br />
</form>
PHP:
I know its very basic, just trying to get it to work before I add error checks or anything.
<?php
if (isset($_POST['postnewstory'])){
$username = $user_data['username'];
$email_address = $user_data['email_address'];
$news_title = $_POST['news_title'];
$news_photo = $_POST['news_photo'];
$button = $_POST['button'];
$news_link = $_POST['news_link'];
$news_tags = $_POST['news_tags'];
$exists = mysql_query ("SELECT * FROM users WHERE username='$username'") or die ("not found");
if (mysql_num_rows($exists) != 0){
//update the info in database
mysql_query ("INSERT INTO news (`news_id` ,`news_title` ,`news_body` ,`news_photo` ,`news_date` ,`username` ,`news_tags` ,`button ,`news_link`)
VALUES (NULL , '$news_title', '$news_body', '$news_photo', now(), '$username', '$news_tags', '$button', '$news_link');") or die ("update didn't work");
echo "<div class='alert alert-success'><strong>This post was sent!</strong></span></div> ";
echo '<meta http-equiv="refresh" content="2;url=admin.php?page=3">';
} else echo "<strong><font color=red>Update did not work, please try again.</font></strong>";
}
?>
You have a missing backtick in:
,`button
change to:
,`button`
Rewrite:
("INSERT INTO news (`news_id` ,`news_title` ,`news_body` ,`news_photo` ,`news_date` ,`username` ,`news_tags` ,`button`,`news_link`)
Footnotes:
I quote Shankar:
"Replace die ("update didn't work"); with die (mysql_error()); to know the exact error why your query ain't working."
I think this should work;
Change the line
echo '<meta http-equiv="refresh" content="2;url=admin.php?page=3">';
to
echo "<script>window.location = 'admin.php?page=3';</script>";
So here I am trying to create a logbook with some simple php.
The problem is that nothing is being added to the database I created. Whenever I check the database I just keep getting an empty dataset after adding and submitting text on the guestbook form.
Can anybody see any problems with my code?
<?php
$sql = mysql_connect("localhost" , "root") or die(mysql_error);
mysql_select_db("guestbook" , $sql);
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$query = mysql_query("INSERT INTO message (name , email) VALUES ('$name' , '$email')");
echo ("Message succesfully added.");
}
?>
<html>
<head>
<title>Guestbook</title>
</head>
<form action="index.php" method="post">
Name: <input type="text" name="name"/><br>
Email: <input type="text" name="email"/><br>
<input type="submit" value="Post!"/>
</form>
</html>
<?php
$result = mysql_query("SELECT * FROM message ORDER BY id DESC");
while($row = mysql_fetch_array($result))
{
?>
<table>
<tr>
<td>Name:</td>
<td><?php echo $row['name'] ?></td>
</tr>
<tr>
<td>Message:</td>
<td><?php echo $row['email'] ?></td>
</tr>
</table>
<?php
}
?>
Replace
mysql_query("INSERT INTO message (name , email) VALUES ('$name' , '$email'");
With
mysql_query("INSERT INTO message (name , email) VALUES ('$name' , '$email')");
I think that name is a reserved word in mysql isn't it?
you might have to modify your inset script as follows:
$query = mysql_query("INSERT INTO message (`name` , email) VALUES ('$name', '$email')");
Having said that, your script is WIDE open to an injection attack. You should be using PDO and also verifying data before you go sticking it into an SQL statement. What do you do when your user enters bob;drop table users; as his name and your query runs?
Edit: Also, you had a bracket missing.
Edit 2: If you are still getting an error run this and let us know what you see:
$sql = "INSERT INTO message (`name` , email) VALUES ('$name', '$email')";
echo $sql;
There is a good chance you see that one of the variables is empty.
Edit 3:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
if(!empty($name) && !empty($email))
{
$query = mysql_query("INSERT INTO message (name , email) VALUES ('$name' , '$email')");
echo ("Message succesfully added.");
}
else
{
echo "It seems that either name or email was empty, so not inserting data.<br>";
}
}
?>
Edit 4 - aka Goodness me!
I also noticed that I failed to add the extra bracket to the code that I copied from your question. I have edited it to include it from now on.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$username = mysql_real_escape_string($_POST['username']);
$username = mysql_real_escape_string($_POST['useremail']);
if(!empty($name) && !empty($email))
{
$query = mysql_query("INSERT INTO message (name , email) VALUES ('$username', '$useremail')");
echo ("Message succesfully added.");
}
else
{
echo "It seems that either name or email was empty, so not inserting data.<br>";
}
}
<html>
<head>
<title>Guestbook</title>
</head>
<form action="index.php" method="post">
Name: <input type="text" name="username"/><br>
Email: <input type="text" name="useremail"/><br>
<input type="submit" value="Post!"/>
</form>
?>
// Make sure you stick this </html> at the BOTTOM of you php file.
</html>
I am trying to submit the page to itself but some reason the following code is not working. Also How can I get the table1 primary key ID back after inserting the data successfully? I have a child table which needs this ID. Thanks for any suggestions.
<?php
include('db_login.php');
$connection = mysql_connect( $db_host, $db_username, $db_password );
if (!$connection){
die ("Could not connect to the database: <br />". mysql_error());
}
// Select the database
$db_select=mysql_select_db($db_database);
if (!$db_select){
die ("Could not select the database: <br />". mysql_error());
if ($_POST['Submit'])
{
$first = $_POST["first"];
$first = mysql_real_escape_string(get_magic_quotes_gpc() ? stripslashes($first): $first);
$last = $_POST["last"];
$last = mysql_real_escape_string(get_magic_quotes_gpc() ? stripslashes($last): $last);
$insertsql = "INSERT INTO table1(FirstName,LastName) VALUES ('".$first."', '" .$last. "')";
$result1 = mysql_query($insertsql) or die(mysql_error());
}
?>
<form name="hotlineForm" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"
method="post">
<input id="first" type="text">
<input id="last" type="text">
<input type="submit" value="Submit"></form></body>
What part isn't working on the post back? Are you not entering your if statement?
To get the ID of the last insert use the following after your $result1 = mysql_query(...):
$primary_id = mysql_insert_id()
http://php.net/manual/en/function.mysql-insert-id.php
Change your form inputs to include name attributes. Without them, your $_POST will be empty.
<input name='first' id="first" type="text">
<input name='last' id="last" type="text">
<input name='Submit' type="submit" value="Submit">
As mentioned in the comments, get_magic_quotes should not be used. You've correctly called mysql_real_escape_string() on your inputs already.
Following your insert, get the id from mysql_insert_id():
$result1 = mysql_query($insertsql) or die(mysql_error());
$new_id = myqsl_insert_id();
if ($_POST['Submit'])
I don't see a form element with this name.
try:
if (isset($_POST['first']) && isset($_POST['last']))
For getting inserted ID you can use:
mysql_insert_id();
You are missing a closing } here:
if (!$db_select){
die ("Could not select the database: <br />". mysql_error());
} <<---- Close your if statement here.
if ($_POST['Submit'])
Currently the code that does the actual work only gets called if the DB cannot be selected.
Not very useful.
This is why proper indentation is important.
If you are religious about your indentation, you will spot these kind of errors instantly.
Use a name for the input field and check if it was sents not the submit