the problem is..i try to parsing json from php..here is jquery code:
$.post( "confirmsignup.php", $("#signupform").serialize()).always(function( data ) {
alert(data.msg);
}, "json");
PHP code:
if (isset($_POST['gender'])&&isset($_POST['fname'])&&isset($_POST['sname'])&&isset($_POST['username'])&&isset($_POST['dob'])) {
$gender=secureing($_POST['gender']);
$fname=secureing($_POST['fname']);
$sname=secureing($_POST['sname']);
$username=secureing($_POST['username']);
$email=secureing($_POST['email']);
$dob=secureing($_POST['dob']);
if (isset($_POST['agree'])&&isset($_POST['pass'])&&isset($_POST['repass'])) {
$pass=secureing($_POST['pass']);
if ($_POST['pass']==secureing($_POST['repass'])) {
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '".md5($pass)."', '$dob')";
if(!($query_run = mysql_query($query))){
$msg = "error";
}else{
$msg = "complete";
}
}
}
}
header('Content-Type: application/json');
?>
{
"msg": "<?php echo $msg ." - ". $query; ?>"
}
secureing() is for returning string after escape_string..
$msg suppose to return string "complete"... but it returning "error"..
however in phpmyadmin, query is successfully executed..
i think there is no mistake..what is my mistake?please help..
Can you please change the following code with your code, I have used mysql_insert_id to check record is inserted or not.
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '".md5($pass)."', '$dob')";
$query_run = mysql_query($query);
$id = mysql_insert_id();
if($id > 0)
{
$msg = "complete";
}
else
{
$msg = "error";
}
It may help you.
I have same issue long time ago!
it's because you haven't any AI primary key in the table!
add a field like this to the table: id INT Primary Key Auto Increment.
this will works!
and migrate to mysqli or pdo for better security and support! ;)
try my code is seem you have put wrong condition
if (isset($_POST['gender'])&&isset($_POST['fname'])&&isset($_POST['sname'])&&isset($_POST['username'])&&isset($_POST['dob'])) {
$gender=secureing($_POST['gender']);
$fname=secureing($_POST['fname']);
$sname=secureing($_POST['sname']);
$username=secureing($_POST['username']);
$email=secureing($_POST['email']);
$dob=secureing($_POST['dob']);
if (isset($_POST['agree'])&&isset($_POST['pass'])&&isset($_POST['repass'])) {
$pass=secureing($_POST['pass']);
if ($_POST['pass']==secureing($_POST['repass'])) {
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '".md5($pass)."', '$dob')";
if(!(mysql_query($query))){
$msg = "error";
}else{
$msg = "complete";
}
}
}
}
i just found the solution, after change my php API to connecting to database.
from:
if(!#mysql_connect('localhost', 'root', '')||!#mysql_select_db('knewit')){
die("something not right");
}
to:
$mysqli = new mysqli("localhost", "root", "", "knewit");
after that, i change my executing method from mysql_query to $mysqli->query.
i also change my jquery post method from always to done.
and the final code be like this.
jQuery script:
$.post( "confirmsignup.php", $("#signupform").serialize()).done(function( data ) {
alert(data.msg);
}, "json");
PHP script:
if (isset($_POST['agree'])&&isset($_POST['pass'])&&isset($_POST['repass'])) {
$passs=secureing($_POST['pass']);
if ($_POST['pass']==secureing($_POST['repass'])) {
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '$passs', '$dob')";
if(!($query_run = $mysqli->query($query))){
$msg = "error";
}
else
{
$msg = "complete";
}
}
}
}
header('Content-Type: application/json');
$arrayName = array('msg' => $msg );
echo json_encode($arrayName);
thank you for answer my question. i really appreciate it.
Related
I'm making a simple CURD operation using PHP and MYSQL. However I'm not able to insert/add data in the created table.
I think it might be a syntax error itself, but I can't figure out which one. The rest of the code works fine.
operation.php:
require_once("../CRUD/php/db.php");
$conn = createDB();
if(isset($_POST['create']))
{
createData();
}
function createData()
{
$name = textboxValue("name_type");
$age = textboxValue("age_type");
$gender = textboxValue("gender_type");
$email = textboxValue("email_type");
$contact = textboxValue("contact_type");
$dept = textboxValue("dept_type");
$sql = "INSERT INTO details(name,age,gender,email,contact,department)
VALUES('$name', '$age', '$gender', $email', '$contact', '$dept');";
if(mysqli_query($GLOBALS['conn'],$sql))
{
echo "Data added";
}
else
{
echo "Error adding data";
}
}
function textboxValue($value)
{
$textbox = mysqli_real_escape_string($GLOBALS['conn'], trim($_POST[$value]));
if(empty($textbox))
{
return false;
}
else
{
return $textbox;
}
}
"Error adding data" gets echoed. I can share the html code as well if needed.
$sql = "INSERT INTO details(name,age,gender,email,contact,department)
VALUES(\"$name\", \"$age\", \"$gender\", \"$email\", \"$contact\", \"$dept\");";
and so? By the way one quote you forgot near $email
So Ive been debugging this for a couple of hours and can't seem to work it out. Ive got a form that takes info into a session then from sessions it goes into a class.
form->session->class->database
Inside the class theres a function that looks like this:
function lagre($kunde)
{
$navn = $kunde->GetNavn();
$telefon = $kunde->GetTelefon();
$epost = $kunde->GetEpost();
$antall = $kunde->GetAntall();
$db = mysqli_connect("localhost","root","","Billett");
if($db->connect_error)
{
die("Couldn't connect");
}
else {
echo "Connected";
}
$sql = "INSERT INTO `Billett`.`Billett` (`BillettID`, `Navn`, `Telefon`, `Epost`, `Antall`) VALUES (NULL, '$navn', '$telefon', '$epost', '$antall')";
$resultat = mysqli_query($db,$sql);
if(!$resultat)
{
echo "<br> Values not inserted";
}
else {
echo "<br> Values inserted";
}
}
The problem is that the values doesn't insert into the database. I cant work out why. Any ideas?
You try to write in different way
$sql = "INSERT INTO `Billett`.`Billett` (`BillettID`, `Navn`, `Telefon`, `Epost`, `Antall`) VALUES (NULL, '".$navn."', '".$telefon."', '".$epost."', '".$antall."')";
Are you using Autocommit? If not then you need to commit your data to the DB, otherwise your INSERT doesn't stick:
/* commit transaction */
if (!$mysqli->commit()) {
print("Transaction commit failed\n");
exit();
}
Example from PHP documentation
I am wondering how can I insert the values retrieved from a HTML form into 2 tables, loginDetails and memberDetails.
loginDetails (table_1 shown in the code)
loginID (PK) <-- auto increment
username
password
memberDetails (table_2 shown in the code)
memberID (PK) <-- auto increment
loginID (FK)
These are the codes I have so far, however the loginID in memberDetails table are always 0,:
PHP codes
$Query = "INSERT INTO $table_1 VALUES (NULL,
'".$formValue['username']."',
'".$formValue['password']."')";
if (mysqli_query($Link, $Query)) {
$lastID = mysql_insert_id();
$Query2 = "INSERT INTO $table_2 VALUES (NULL,
'".$lastID."')";
if (mysqli_query($Link, $Query2)) {
$message = "You've sucessfully created the account!";
echo json_encode(array('success'=>'true', 'action'=>'login','html'=>$message, 'console.log'=>$Query));
}
else {
$message = "Error occur in query2";
echo json_encode(array('action'=>'error','html'=>$message, 'console.log'=>$Query));
}
}
else {
$message = "Error in query1";
echo json_encode(array('action'=>'error','html'=>$message, 'console.log'=>$Query));
}
It would be great if this question can be solved, as i have been struggling in this for 3 nights already. Cheers.
You can place your queries in an array. Loop through the array. If an error occurs, exit the script.
$myQueries = array(`"INSERT INTO $table_1 VALUES (NULL,
'".$formValue['username'].",
'".$formValue['password']."')",
"INSERT INTO $table_2 VALUES (NULL,
'".$lastID."')"
)`;
for($i = 0; $i < count($myQueries); $i++){
if (mysqli_query($Link, $myQueries[$i])) {
$lastID = mysql_insert_id();
$message = "You've sucessfully created the account!";
echo json_encode(array('success'=>'true',
'action'=>'login',
'html'=>$message,
'console.log'=>$Query));
}
else {
$message = "Error occur in query[$i]";
echo json_encode(array('action'=>'error',
'html'=>$message,
'console.log'=>$Query));
exit; // stops the next query
}
}
}
Here I have a code which inserts data into db. It's working fine now, but I want the title to have a minimum of 4 characters and the body a minimum of 500.
Here is my code:
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if ($title && $body && $category) {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}
else {
echo "error";
}
}else {
echo "data missing";
}
}
?>
I tried the code below to put minimum requirements for the title and body, but it echoes the title error message whenever you submit data even when the title contains more than 5 characters.
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if (strlen($title<5)) {
echo "Title must be of minimum 5 characters";
}
else {
if (strlen($body<500)) {
echo "Title must be of minimum 500 characters";
}
else {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}
else {
echo "error";
}
}
}
}
?>
A question as such deserves an explanation for future readers to the question.
The reason why your code is failing, is that:
if (strlen($title<5))
evaluates to:
function($string conditional)
when the syntax is:
function($string) conditional
The manual states:
int strlen ( string $string )
http://php.net/manual/en/function.strlen.php
Example pulled from the manual:
if (strlen($foo) === 0) echo 'Null length is Zero <br>';
Plus, as stated in comments. Your query is subject to an SQL injection. It's best to use a prepared statement.
Consult the following links:
How can I prevent SQL injection in PHP?
https://en.wikipedia.org/wiki/Prepared_statement
I think the issue lies with the conditions you used.
if (strlen($title<5))
should be
if (strlen($title)<5)
similarly
if (strlen($body<500))
to be
if (strlen($body)<500)
Try this:
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if (strlen($title) < 5) {
echo "Title must be of minimum 5 characters";
}else {
if (strlen($body) <500 ) {
echo "Body must be of minimum 500 characters";
}else {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}else {
echo "error";
}
}
}
}
?>
I created a form using php, mysql and xampp server. The problem is that whatever I write in this form it shows that the "message failed to send" and even when I check my db using http://localhost/phpmyadmin/ the message is not there. Here is the code.
P.S I followed a video tutorial and it is exactly the same that made me totally lost. Please help.
The Connection code is:
<?php
$db_host = 'localhost';
$db_user= 'root';
$db_pass= 'the password';
$db_name= 'chat';
if ($connection= mysql_connect($db_host, $db_user, $db_pass)) {
echo "Connected to Database Server...<br />";
if ($database= mysql_select_db($db_name, $connection)) {
echo "Database has been selected... <br />";
} else {
echo "Database was not found. <br />";
}
} else {
echo "Unable to connect to MYSQL server.<br />";
}
?>
And the function code is:
<?php
function get_msg() {
$query = "SELECT 'Sender', 'Message' FROM 'chat' . 'chat'";
$run = mysql_query($query);
$messages= array();
while($message = mysql_fetch_assoc($run)) {
$messages[]= array ('sender' =>$message['Sender'],
'message'=>$message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)){
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO 'chat'.'chat' VALUES (null, '{$sender}', '$message')";
if($run = mysql_query($query)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
?>
I have found the problem in your SQL query:
$query = "INSERT INTO 'chat'.'chat' VALUES (null, '{$sender}', '$message')";
You have to specify the fields there, the SQL query is invalid. Also you have used the wrong escape characters. This works:
$query = "INSERT INTO `chat`.`chat` (`ID`, `sender`, `message`) VALUES (null, '{$sender}', '$message')";
You do not have to specify a null value if you use AUTO_INCREMENT:
$query = "INSERT INTO `chat`.`chat` (`sender`, `message`) VALUES ('{$sender}', '$message')";
And please use MySQLi instead of MySQL because it is deprecated. Furthermore, the database should not be specified twice, simple use:
$query = "INSERT INTO `chat` (`sender`, `message`) VALUES ('{$sender}', '$message')";
$query = "INSERT INTO `chat`.`chat` VALUES (null, '{$sender}', '$message')";
Note the ` and it's not '
I am a novice in PHP and MySQL so I tend to always explicitly exit or die on MySQL on errors.
<?php
$db = new mysqli('host', 'username', 'password', 'db');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
// no reason to continue, no db connection
}
$statement="SELECT * from `bufferlines` WHERE `beloeb` >'-400' AND `tekst` LIKE 'Dankort-nota SuperB%'";
if(!$res=$db->query($statement)){
printf("Error: %s\n", $db->error); //show MySQL error
echo "<br />".$statement; // show the statement that caused that error
exit("Error 4");//no reason to continue, show where in code
}
?>
This way I get it thrown in my face and cannot get any further until I have pinned down and corrected the error.
The number in exit("Error 4") is only to find the place in the code where it went wrong and thus is unique.
I know this is counter productive when you know your stuff, but for me it's an invaluable learning tool together with php.net dev.mysql.com and stackoverflow.com