PHP Mysql Insert Into not working, no error given no data posted to DB, earlier the same page was working [closed] - javascript

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 have problem regarding noted above. My code in php is as under:
$con = mysql_connect(xxxx,xxx,xxx) or die(mysql_error());
mysql_select_db(xxx) or die(mysql_error());
if (count($_POST) > 0) echo "form submitted";
if(isset($submit))
{
$name = $_POST['std_name'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$user_type = "student";
if(mysql_query("insert into login (user_id, user_pass, User_type) values ('$email','$pass','$user_type'", $con))
{
echo "<p class='success_msg'>Congrats! your registration has successfully been done.</p>";
echo mysql_error();
}
else
{
echo mysql_error();
}
Earlier this code was working well and the values were being entered into database. but suddenly it is not working and not even giving any error. any help in the regard will be highly appreciated, please.

$submit is not set in the code sample
You are missing a closing bracket at the end of your query
Read about 'SQL injection', your code is vulnerable

Here's what might help...
Connect to your MySQL database via PHPMyAdmin or via SSH.
Once connected, type the query manually (so, INSERT INTO login() etc) — if it works, then it's a bug further up your code. If this is the case, you need to show us more.
OK, so I've applied a nice PDO version down below.
$host = "localhost";
$port = 3306;
$dbname = "myDatabase";
$user = "myUser";
$pass = "myPass";
$db = new PDO("mysql:host=" . $host . ";port=" . $port . ";dbname=" . $dbname, $user, $pass);
echo (count($_POST) > 0) ? echo "form submitted" : "";
if(isset($submit))
{
$name = $_POST['std_name'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$user_type = "student";
$query = $db->prepare("INSERT INTO login(`user_id`, `user_pass`, `User_type`) VALUES (:email, :pass, :utype");
$binds = array(
":email" => $email,
":pass" => $pass,
":utype" => $user_type
);
if($query->execute($binds))
{
echo "<p class='success_msg'>Congrats! your registration has successfully been done.</p>";
}else{
echo "\nPDO::errorInfo():\n";
print_r($db->errorInfo());
}
}
Read the PDO documentation here.

Related

i can't put the input data into the database

this is my code. i've done this before in other computer and it's okay, but now when try it in my laptop,it can't be done. idk what is the problem, it will show blank in phpmyadmin. i'm using xampp v3.2.2, is that will be the problem?
<html><head><title>Your Data</title></head>
<body>
<?php
$n = $_POST["n"];
$c = $_POST["contact"];
$e = $_POST["email"];
$cm = $_POST["campus"];
$m1 = $_POST["member1"];
$m2 = $_POST["member2"];
$m3 = $_POST["member3"];
$connect = mysqli_connect("localhost","root","") or die("Unable to connect MySQL".mysqli_error());
$db = mysqli_select_db($connect,"multimedia_db") or die("Unable to select database");
$query1 = "INSERT INTO teams(advisor_name,advisor_contact,advisor_email,advisor_campus,member1,member2,member3) VALUES ('$n','$c','$e','$cm','$m1','$m2','$m3')";
$data1 = mysqli_query($connect,$query1) or die("SQL statement failed"); //records are assigned to variable data
echo "You've succesfully register";
?>
</body>
</html>
I don't use MySQLi very often. So I'll explain how to use PDO. Just so you know PDO means PHP Data Objects. The reason I'm explaining, PDO is because, if done properly, it makes SQL injection almost impossible.
Connection
connecting to your database is generally done in a separate file. Here is an example:
con.php
<?php
$hostname = '';
$username = '';
$password = '';
$dbname = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
This is just connecting to the database, so we don't have to keep connecting to other pages, we just refer to this page with an include, like this:
<?php include 'con.php'; ?>
We can put this on any page and it'll include the connection to the database. For example, if you want to select from a database:
<?php
include 'con.php';
$load_data = $dbh->prepare("SELECT * FROM user_table");
if ($load_data->execute()) {
$load_data->setFetchMode(PDO::FETCH_ASSOC);
}
while ($row = $load_data->fetch()) {
$name = $row['name'];
echo $name;
}
?>
This would simply SELECT everything from the user_table from the column name and would display all the matching records.
If you're trying to do an INSERT instead:
<?php
include 'con.php';
$post_name = $_POST['post_name'];
$stmt = $dbh->prepare("INSERT INTO user_table (name) VALUES (:user_name)");
$stmt->bindParam(':user_name', $post_name, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "Success";
} else {
echo "Failed";
}
?>
So the $post_name would be the name you give your input on a form in this case name="post_name" that would be inserted into the user_table.
Hope this helps and FYI here is a very good tutorial on how to do INSERT, UPDATE and DELETE using PDO.
i've found the solution for my question. It's just that i forgot to put localhost in front of the 'url'. no wonder it showed blank.
like 'localhost/sem5/saveRegistration.php'.
i'm sorry for the inconvenience. still a beginner using this hehe

forget password code in php not working [closed]

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 6 years ago.
Improve this question
I have the code for forget password written in php. But it is not working. whenever I execute it it shows that the mail has been sent to particular email. But no mail is sent.
Here's the code
<?php
include('./connect1.php');
$username = $_GET['user'];
$password = $_GET['pass'];
$email = "";
$sql = "SELECT email FROM users WHERE username='$username'";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_assoc($result);
$email = $row['email'];
}
else{
echo "no such user exists";
}
$to = $email;
$from = "gopal#gmail.com";
$message = "
<html>
<head>
<title>Password Reset</title>
</head>
<body>
<p>Please click on this link to reset your passowrd</p>
<a href='www.someone.com/login/reset.php?user=".$username."'>Reset Password</a>
</body>
</html>
";
$subject = "Password Reset";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: <gopal#gmail.com>' . "\r\n";
mail($to,$subject,$message,$headers);
echo '<script>alert("Password reset mail has been sent to'.$email.'");</script>';
?>
Please help me out.
This is probably a configuration error. if you insist on using PHP mail function, you will have to edit php.ini.
if you are looking for an easier and more versatile option (in my opinion), you should use PHPMailer

Search to MySQL table using jQuery, Ajax and PHP not working [closed]

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 7 years ago.
Improve this question
I am trying to create a search engine for a MySQL table with jQuery, Ajax and PHP. I have a database on my external server in order to get data from. Here is a pic of the MySQL database table.
I have these two scripts for the search engine:
index.html
<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<input id="searchdb"/>
<div id="resultdb"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#searchdb').change(function() {
$.ajax({
type: 'GET',
url: 'getdb.php',
data: 'ip=' + $('#searchdb').val(),
success: function(msg) {
$('#resultdb').html(msg);
}
});
});
});
</script>
</body>
</html>
getdb.php
<?php
if ($_GET['insert']) :
$insert = preg_replace('#[^0-9]#', '', $_GET['insert']);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM test WHERE id='.$insert.'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc()
echo $row["name"];
}
endif;
?>
What I want is to type the id, hit enter and get back the name or "0 results". There seems to be something wrong with the code I wrote. Could you please help me? Thanks in advance.
The period characters in your SQL text string are being interpreted as literal dot characters, not PHP concatenation.
e.g.
$sql = "SELECT id, name FROM test WHERE id='.$insert.'";
echo "SQL=" . $sql;
should return:
SQL=SELECT id, name FROM test WHERE id='.123.'
That would be easy enough to fix. But why include the value as part of the SQL text in the first place.
Using prepared statements and bind placeholders is really not that hard.
Use a static string as a SQL statement, use a question mark as a bind place holder, and call the mysqli_stmt_bind_param function. And check the prepare and execute calls for errors. (Those return FALSE if an error occurs.) And the call to num_rows isn't necessary. Just do a fetch. If it returns a row, you've got a row. If it returns FALSE, there wasn't a row to return.
Something like this:
$sql = "SELECT id, name FROM test WHERE id = ? ";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("i",$insert);
if ($stmt->execute()) {
if ($row = $stmt->fetch_assoc()) {
echo $row['name'];
} else {
echo "0 results";
}
} else {
// handle error
die $conn->error;
}
} else {
// handle error
die $conn->error;
}
You could handle the error conditions differently, depending on your requirements.

How to add validation(javascript) in php?

let say that, i want to my change password in php code then it will validate by the use of javascript. before it return to my index page or it will popup on index page. how can i do it? any trick that you can suggest? :)
<?php
include('config2.php');
error_reporting(E_ERROR | E_PARSE);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$val = $_GET['val1'];
session_start();
$ak = $_SESSION['autokey'];
$sql = "UPDATE tbl_user SET password = '". md5($val) ."' WHERE autokey = '$ak'";
mysql_query($sql);
header("location:index");
?>
thanks in advance :)
You could change your code block like this..
$sql = "UPDATE tbl_user SET password = '". md5($val) ."' WHERE autokey = '$ak'";
mysql_query($sql);
if(mysql_affected_rows())
{
echo "<script>alert('Password was successfully changed !');</script>";
echo "<script>window.location='index.php'</script>";
} else
{
echo "<script>alert('Password was not changed');</script>";
echo "<script>window.location='index.php'</script>";
}
As the comment says.. You are mixing up mysql_* and mysqli_*. Change that first.
Sidenote: Switching to PreparedStatements is even more better to ward off SQL Injection attacks !

Registration Form (HTML, PHP & MySQL) redirect after error or missing values

I am new to development with HTML, PHP, CSS etc.
I need to do this small Registration and Login Form. I haven't gone into detail in Object-Oriented PHP and I'm working in the simplest manner as this task needs to be done in a short time and I've only been coding and experimenting with these languages these past two days.
What I already have is a working Registration and Login forms that when they are submitted the information is posted to another php file. Than it verifies that the data has been entered and that the e-mail isn't already used. What i need is that when either the e-mail is already used and when a field is left empty that it automatically goes back to Registration/Login forms and displays a message with their respective errors.
I know this might have been done in a different way but the deadline is really close and so i need a solution that works with what I already have.
I'm sorry if a similar question is already available, but i might be using incorrect keywords to search for the solution.
Keywords currently that I'm using are Redirection, "Going back to previous page".
If JavaScript is more suitable for this kind of operation it is also excepted and would like this to be pointed out, although a php solution would be appreciated a bit more as i currently obtain more knowledge on PHP than on JavaScript.
Thanks, any help or directions to suitable solutions would be mostly appreciated.
You can use
A) PHP header() function
B) echo a META HTTP - EQUIV=" refresh "
CONTENT=" seconds; URL = \the-other-url">
C) Use JS like this but you
will need to set a timeout
Example:
if (empty ($_POST ['username']) || empty ($_POST ['password']))
{
echo "Please enter a username, or password";
header ("refresh:5; url=back.php");
exit;
}
There are many different ways to do this. If when the form is submitted your executing the code on a different php file then you could have an IF statement there which redirects the headers back to the form page if there are errors with the users input such as:
if($username == "")
{
header("Location: YOUR_FORM_PAGE.php");
}
Hope this helps.
To add the execution to the same page you can do this.
add these buttons;
<input type="hidden" id="submitted" name="submitted" value="1">
<span class="label"></span><input type="submit" class="submit" value="Submit"><input type="reset" class="submit" value="Clear">
set the form action to the form page. Add this to the top of the page and add any PHP you want to it;
if(isset($_POST["submitted"]) && $_POST["submitted"] == 1)
{
for example;
if($from_fullname == "")
{
$submission_status = '<div class="vpb_info" align="left">Please enter your fullname in the required field to proceed. Thanks.</div>';
}
and add this to the page where you want the error displayed;
<p> <?php echo $submission_status; ?></p>
Sounds like http-redirect (http://php.net/manual/en/function.http-redirect.php) should help you out. You can redirect on your error conditions with that.
Update
With redirect you can attatch QueryString Parameters so you could redirect back to the login.php page with an errror code and/or message as a query string perameter.
These will get you started, a registration or signup php file and a login php file I made once
(personal info is faked).
SignUp.php
<?php
session_start();
$name = $_REQUEST['name'] ;
$userpassword = hash('sha512',$_REQUEST['password'] );
$signature = $_REQUEST['signature'] ;
$image = $_REQUEST['image'];
$email = $_REQUEST['email'] ;
$emailreplies = $_REQUEST['emailreplies'] ;
if (!isset($_REQUEST['name'])) {
header( "Location: MotesBlog.php" );
}else{
$username="root";
$password="root";
$database="MotesBlog";
mysql_connect("localhost",$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query=sprintf("SELECT Name FROM users WHERE Name LIKE '%s';",
mysql_real_escape_string($name));
$query=mysql_query($query);
if(mysql_num_rows($query)){
$query = sprintf("SELECT Email FROM users WHERE Name='%s';",
mysql_real_escape_string($name));
$query=mysql_query($query);
$_SESSION['NameTaken'] = true;
$_SESSION['UsedName'] = $name;
$_SESSION['UsedEmail'] = mysql_result($query,0);
header("Location: SignUp.html");
}else{
$query=sprintf("SELECT Email FROM users WHERE Email LIKE '%s';",
mysql_real_escape_string($email));
$query=mysql_query($query);
if(mysql_num_rows($query)){
$_SESSION['EmailTaken'] = true;
$_SESSION['UsedEmail'] = $email;
header("Location: SignUp.html");
}else{
$query = sprintf(" INSERT INTO users VALUES (
NULL , '%s', '%s' , '%s', '%s', '%s', CURRENT_TIMESTAMP , 0, $emailreplies);",
mysql_real_escape_string($name),
$userpassword,
mysql_real_escape_string($signature),
mysql_real_escape_string($image),
mysql_real_escape_string($email));
mysql_query($query);
$query = sprintf("SELECT JoinDate FROM users WHERE Name='%s';",
mysql_real_escape_string($name));
$vcode=md5(mysql_result(mysql_query($query),0));
mysql_close();
require_once "Mail.php";
$from = "PocketWoods Hunting Hall<pwoods#email.com>";
$to = $email;
$subject = "Welcome to Motes Blog";
$body = "<html>
<body>Thank you for your time. <br/>
To ensure a human made this account and not an
automated process please click the link below:<br>
<a href=\"http://site.com/MotesBlog/verifyaccount.php?vcode=".$vcode."&name=".$name."\">
Activate Account
</a>
</body>
</html>";
$host = "mail.root.com";
$username = "root#root.com";
$password = "root";
$headers = array ( 'From' => $from,
'To' => $to,
'Subject' => $subject,
'MIME-Version' => "1.0",
'Content-type' => "text/html; charset=iso-8859-1");
$smtp = Mail::factory('smtp',
array ( 'host' => $host,
'auth' => false,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
header("Location: success.html");
}
}
}
?>
Login.php
<?php
session_start();
$username="root";
$password="root";
$database="MotesBlog";
mysql_connect("localhost",$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$user_name = $_REQUEST['name'];
$user_password = $_REQUEST['password'];
if (!isset($_REQUEST['name'])) {
header( "Location: MotesBlog.php" );
}else{
if(isset($_SESSION['User'])){
if( ($_SESSION['CreatedTime'] + 3600) < time() ){
$_SESSION['Expired'] = true;
}
unset($_SESSION['User']);
}
$query = sprintf("SELECT Password FROM users WHERE Name='%s';",
mysql_real_escape_string($user_name));
$query=mysql_query($query);
if(mysql_num_rows($query)){
$real_password=mysql_result($query,0);
$query = sprintf("SELECT Email FROM users WHERE Name='%s';",
mysql_real_escape_string($user_name));
$query=mysql_query($query);
$email = mysql_result($query,0);
if($real_password == hash('sha512',$user_password)){
$query = sprintf("SELECT Validated FROM users WHERE Name='%s';",
mysql_real_escape_string($user_name));
$query=mysql_query($query);
mysql_close();
if(mysql_result($query,0)){
$_SESSION['User'] = $user_name;
$_SESSION['CreatedTime'] = time();
setcookie("User", $_REQUEST['name'], time() + 60*60*24*365);
header( "Location: MotesBlog.php" );
}else{
$_SESSION['resend_name'] = $user_name;
$_SESSION['resend_email'] = $email;
$_SESSION['NotValidated'] = true;
header( "Location: MotesBlog.php" );
}
}else{
$_SESSION['WrongPW'] = true;
$_SESSION['UsedEmail'] = $email;
header( "Location: MotesBlog.php" );
}
}else{
$_SESSION['WrongName'] = true;
header( "Location: MotesBlog.php" );
}
}
?>

Categories

Resources