I have a pair of radio buttons and I want to insert its value into my database in the form of bit. Following is the HTML code for the same.
<form id="Form" method="post" class="overlay" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<input type="hidden" id="Keyy" name="key" value="">
<label for="JRadioYes">Active? Yes</label> <input type="radio" id="JRadioYes" name="activeradio"<?php if (isset($ActiveValue) && $ActiveValue == "yes") echo "checked='checked' "; ?>value="yes">
<label for="JRadioNo">No</label> <input type="radio" id="JRadioNo" name="activeradio"<?php if (isset($ActiveValue) && $ActiveValue == "no") echo "checked='checked' "; ?>value="no">
<input type="submit" id="submitter" name="sub" value="Submit!" onclick="decider(this)">
</form>
The following is the PHP code for inserting into the database
// Check if radio is submitted
if (isset ( $_POST ["activeradio"]))
{
//Extract values from $_POST and store in variables
$select_radio = $_POST ["activeradio"];
if ($select_radio == "yes") {
$active_status = true;
//I also tried assigning 1 instead of true
}
if ($select_radio == "no") {
$active_status = false;
//I also tried assigning 0 instead of false
}
if($_POST["key"] == "update")
{
try
{
echo "<script type='text/javascript'>
alert('$active_status');
</script>";
$JobInt = intval($JobTypeID);
$stmt = sqlsrv_query ( $conn, 'EXEC spEditThisJobType #Active = ?', array (
$active_status
) );
}
catch(Exception $e)
{
echo "Error :". $e;
}
if($stmt != null)
{
echo "<script type='text/javascript'>alert('Successfully Updated!$stmt');
</script>";
}
}
}
I am able to get the alert which says Successfully Updated, but I am also getting Resource #6 error along with it. Also the database does not get updated.
What is the mistake I have done here? Please guide me. Thank you in advance.
Have a look at the documentation for sqlsrv_query - it returns a resource object, not the result of the query.
Therefore when you echo "Successfully Updated!$stmt", the resource $stmt is converted to its string representation - Resource #6.
So you either need to remove $stmt from your echo, or do something with the resource such as reading the data using sqlsrv_fetch_array.
Related
I have never worked with $_COOKIES, and now I've been given the task to make it work.
I have been following a couple of tutorials online.
Found here: http://www.phpnerds.com/article/using-cookies-in-php/2
And then here:https://www.youtube.com/watch?v=Dsem42810H4
Neither of which worked for me.
Here is how my code ended up. I shortened it as much as I could.
Starting with the index.php page, which contains the initial login form:
<form role="form" action="index.php" method="post" id="loginForm" name="loginForm">
<input type="text" class="form-control" id="username" name="username"
value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" />
<input type="password" class="form-control" id="password" name="password"
value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>"/>
<button type="button" id="loginSubmit" name="loginSubmit" class="btn btn-primary btn-block btn-flat">Sign In</button>
<input type="checkbox" id="rememberme"
<?php if(isset($_COOKIE['username'])){echo "checked='checked'";} ?> value="1" />
</form>
Here is the JavaScript used to send the form values:
$('#loginSubmit').on('click', function()
{
var username = $('#username').val();
var password = $('#password').val();
var rememberme = $('#rememberme').val();
// skipping the form validation
$.post('api/checkLogin.php', {username: username, password: password, rememberme:rememberme}, function(data)
{
// the data returned from the processing script
// determines which page the user is sent to
if(data == '0')
{
console.log('Username/Password does not match any records.');
}
if(data == 'reg-user")
{
window.location.href = "Home.php";
}
else
{
window.location.href = "adminHome.php";
}
});
});
Here is the processing script, called checkLogin.php. This is where I attempt to set the $_COOKIE:
<?php
include ("../include/sessions.php");
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['password'])));
$rememberme = $_POST['rememberme'];
$select = "SELECT username, fullname, password FROM users WHERE username = '".$username."'";
$query = mysqli_query($dbc, $select);
$row = mysqli_fetch_array($query);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfullname = htmlentities(stripslashes($row['fullname']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword))
{
// setting sessions here
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $dbfullname;
// here is where I attempt to set the $_COOKIE
if(isset($remember))
{
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', $_POST['password'], time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false);
setcookie('password', $_POST['password'], false);
}
echo $username; // this gets sent back to the JavaScript
mysqli_free_result($query);
}
else
{
// username/password does not match any records
$out = 0;
echo $out;
}
}
?>
So now that I have attempted to set the $_COOKIE, I can try to print it to the home page, like so:
<?php echo 'cookie ' . $_COOKIE["username"]; ?>
To which does not work, because all I see is the word 'cookie'.
Besides that, when I log out, I am hoping to see the login form already filled out, which is the overall task I have been trying to complete, but have been unsuccessful at doing so.
Code
<?php
mysql_connect('localhost','root','123456') or die(mysql_error());
mysql_select_db('email') or die(mysql_error());
?>
<?php
if(isset($_POST['submit']))
{
extract($_POST);
$sql=mysql_query("insert into user(name,email)value('$name','$email')");
if($sql)
{
echo '<script>alert("successfull");</script>';
}
else
{
echo '<script>alert("error");</script>';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="" name="form">
<input type="text" name="name" id="name" placeholder="name">
<input type="text" name="email" id="email" placeholder="email">
<input type="submit" name="submit" id="submit">
</form>
</body>
how can we insert data into database without duplicate email id after submit it show alert msg that email id already exist?
thank you
<?php
if(isset($_POST['submit']))
{
extract($_POST);
$query = mysql_query("select * from user where email = '$email'");
$result = mysqli_fetch_assoc($query);
if($result > 0 )
{
echo 'Email already exits';
}
else
{
// code here for insert or what ever you wants
}
}
?>
Firstly the mysql_* functions has been deprecated as of PHP version 5.5.0 and above. So its greatly advised to use mysqli_* functions.
To answer your question, a simple select query along with if statements would do:
$sql="SELECT * FROM users WHERE email = '$email'";
$result = $conn->query($sql);
if($result->num_rows>0){
//Email Already Exists
}
else
{
//Perform Insertion
}
Lastly, its highly recommended to use prepared statements.
First make a select query to check whether on this email and name entry already exist or not.
$SelectSqlQry=mysql_query("select COUNT(email) from user where email = '.$email.'");
$LengthRecords = mysqli_fetch_assoc($SelectSqlQry);
if($LengthRecords > 0) {
//do your alert or anything.
//alert email already exists.
echo '<script>alert("Email Already Exists");</script>';
}
else {
//Insert email..
}
then check your condition on this variable. SelectSqlQry
I am using ajax and php and i would like to append my array each an everytime i make an ajax call. But it is not working.
These are my codes:
$('#multiple_upload_form' +count).ajaxForm({
target:'#images_preview'+count,
beforeSubmit:function(e){
console.log("gud to go");
},
success:function(data){
console.log(data);
console.log("succeded");
},
error:function(data){
console.log("failde");
}
}).submit();
PHP this is the pHP side of it.Plase help
<?php
$questionArr = array();
if($_POST['image_form_submit']){
array_push($questionArr,$questionNum );
if(is_array($questionArr)){
foreach($questionArr as $val) {
if ($val == $questionNum){
$response['response']= "exist";
echo json_encode($questionArr);
}else{
$response['response']= "question does not exist";
echo json_encode($response);
}
}
}else{
$response['response']= "not array";
echo json_encode($response);
}
}
?>
And this is my HTML
<form method="post"name="multiple_upload_form"id="multiple_upload_form" enctype="multipart/form-data" action="php_work/test.php">
<input type="hidden" name="image_form_submit" value=""/>
<input type="file" name="images[]" id="images" multiple >
</form>
It may help you:
<?php
$questionNum = 1; // Or from anywhere you are getting data into it
$questionArr = array();
$response['response']= "not array"; // Giving Default value
if($_POST['image_form_submit']){
$questionArr[] = $questionNum;
if(!empty($questionArr)){
foreach($questionArr as $val) {
if ($val == $questionNum){
$response['response'] = "exist";
}else{
$response['response']= "question does not exist";
}
}
}
}
echo json_encode($response);
exit;
?>
First: There is one if statement in the PHP which won't return a value, since there's no else. So if $_POST['image_form_submit'] is false, nothing is echoed.
Second: array_push($questionArr, $questionNum); Where do you defined $questionNum in your PHP script?
Third: in your JS: $('#multiple_upload_form' +count) there you try to refer to an element with an id with a number I guess? I don't see such an element in your HTML. I also don't see in the JS code where you define count.
Long answer short: check both PHP and JS codes for errors.
I have a login script that should return 'success' or 'failure' respectively, but it adds many spaces before the result, in the console it shows tha value as "<tons of space> success". This is the PHP for the login script:
public function login() {
global $dbc, $layout;
if(!isset($_SESSION['uid'])){
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if(!empty($username) && !empty($password)){
$query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
$data = mysqli_query($dbc, $query);
if((mysqli_num_rows($data) === 1)){
$row = mysqli_fetch_array($data);
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
$ip = $_SERVER['REMOTE_ADDR'];
$user = $row['uid'];
$query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
mysqli_query($dbc, $query);
setcookie("ID", $row['uid'], time()+3600*24);
setcookie("IP", $ip, time()+3600*24);
setcookie("HASH", $row['hash'], time()+3600*24);
echo 'success';
exit();
} else {
//$error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
//return $error;
$err = 'failure';
echo($err);
exit();
}
} else {
//$error = '<div class="shadowbar">You must enter both your username AND password.</div>';
//return $error;
$err = "{\"result\":\"failure\"}";
echo json_encode($err);
exit();
}
}
} else {
echo '{"result":"success"}';
exit();
}
return $error;
}
and the form and JS
<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success : function(result) {
console.log(result);
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
});
but the result always has a lot of spaces for some reason. I'm new to JS, so if this is common, I don't already know.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define("CCore", true);
session_start();
//Load files...
require_once('include/scripts/settings.php');
require_once('include/scripts/version.php');
require('include/scripts/core.class.php');
require('include/scripts/nbbc_main.php');
$parser = new BBCode;
$core = new core;
$admin = new admin;
require_once('include/scripts/layout.php');
require_once('include/scripts/page.php');
//Set Variables...
global $dbc, $parser, $layout, $main, $settings, $core;
$page = new pageGeneration;
$page->Generate();
?>
this is my index, and anything before the page is generated and login() is called, is in there.
I suppose you are using Ajax calls. I had the same problem, but it my case the result hadn't contain spaces, it was returned in new line. The problem was that my script which was requested by Ajax, contained "new line" character before the PHP script. Search your script file for spaces before PHP script starting with <?php //code... If you had included some scripts in the script which returns success note, search them as well.
I dont know if it matters but your
if(result == " success"){ // <<<<<< Here is a Problem maybe
window.location = "/index.php";
}else if(result == " failure"){ // <<<<<< Here is a Problem maybe
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
compares your result from the server which is i.e. "success" with " success". There is space too much.
EDIT:: I dont get ether why you jumps between the response format. Sometimes you echo "success" which is plain and good with your if condition but sometimes you return json encodes strings.
These Responses you can't just compare with plain text. These Responses you have to Parse into a JSON Object. Then you could compare with:
if (parsedJSONobject.result == "success"){}
The comments on the question are most probably correct: the spaces are being (again, probably, nobody can know for sure without reading the whole source) echoed by PHP included before this. For example, if you do:
<?php
// there's a space before the previous line
you'd get that space in the output.
What you can do is a bit of a hack, you include a header, for example:
header('Content-Type: text/html');
just before your success output, this will (yet again, probably) output something like:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
(note the "output started" part) and now you know where to start looking.
HTH.
I'm new to ajax concept. Here i'm trying to insert the user details(signup form) into the database. it inserted the datas into the db succesfully. But, ajax is my problem.
1) i didn't get any error message if form fields are empty. you can see my below codes i've done validation on post.php page. but, it doesn't return the error values. 2) it stores the empty values into database. 3) if datas stored successfully i want to get the success message & if datas failed to store in db i want to get the error message. How should i do these all things?
Ajax.js
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'POST',
url: 'post.php',
data: $('form').serialize(),
success: function(msg) {
if(msg=='error_n')
{
$("#e_name").html('Name required');
}
if(msg=='error_m')
{
$("#e_mobile").html('Mobile required');
}
//success and error alert
if(data="inserted")
{
alert("insertion success");
}
else
{
alert("falid to insert into database");
}
}
});
e.preventDefault();
});
});
Post.php
<?php
include_once('config.php');
$name = trim($_POST["name"]);
$mobile = trim($_POST["mobile"]);
if($name == "")
{
echo 'error_n';
}
if($mobile == "")
{
echo 'error_m';
}
try
{
$stmt = $conn->prepare("INSERT INTO sample ( Name, Mobile ) VALUES ( ?, ? )");
$conn->errorInfo();
$stmt->bindParam('1', $name, PDO::PARAM_STR);
$stmt->bindParam('2', $mobile, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database' .$e->getMEssage();
}
?>
Homepage.php
<p>register here</p>
<div id="light" class="white_content">
Close
<form>
<input type="hidden" name="form" value="values" />
name : <input name="name" id="name" type="text" /><span id="e_name"></span> <br />
mobile : <input name="mobile" id="mobile" type="text" /><span id="e_mobile"></span> <br />
<input type="submit" value="submit" />
</form>
</div>
<div id="fade" class="black_overlay"></div>
After your error messages are returned, you need to stop the script execution. Your current code still tries to add the values and hence overrides your custom error messages. Most probably then your PHP returns your exception message and which is not what your JavaScript is expecting.
if($name == "")
{
echo 'error_n';
die(); // Stop here
}
if($mobile == "")
{
echo 'error_m';
die(); // Stop here
}
Also add echo 'inserted'; when your database insert is successful.