This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 6 years ago.
This is script for sending messages to other users. Everything is OK but it doesnt save the input field values into the database. I am looking the code from 1 hour and I can't find the problem. 'to', 'subj', 'msg' come from the form.
<?php
include 'php/db_connect.php';
$name = $_SESSION['name'];
$to = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'to'))));
$sender = $name;
$subj = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'subj'))));
$msg = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'msg'))));
$errorTo = '';
$errorSubj = '';
$errorMsg = '';
$errorMain = false;
if (filter_input_array(INPUT_POST)) {
if ($to === $name) {
$errorTo = 'Не може да пращаш съобщение на себе си';
$errorMain = true;
}
$checkTo = "SELECT user_name FROM users WHERE user_name='$to'";
$resultCheck = mysqli_query($conn, $checkTo);
$row = mysqli_fetch_array($resultCheck, MYSQLI_ASSOC);
if (mysqli_num_rows($resultCheck) == 0) {
$errorTo = 'Не съществува такъв потребител';
$errorMain = true;
}
if (str_word_count($subj) > 20) {
$errorSubj = 'Прекалено дълга тема за съобщение';
$errorMain = true;
}
if (str_word_count($msg) > 300) {
$errorSubj = 'Прекалено дълго съобщение';
$errorMain = true;
}
if (!$errorMain) {
$insertInDb = 'INSERT INTO msg (to, sender, subject, msg) VALUES ("$to", "$sender", "$subj", "$msg")';
mysqli_query($conn, $insertInDb);
}
}
?>
You use php variables into single quotes. Change string:
$insertInDb = 'INSERT INTO msg (to, sender, subject, msg)
VALUES ("$to", "$sender", "$subj", "$msg")';
to
$insertInDb = "INSERT INTO msg (to, sender, subject, msg)
VALUES ('$to', '$sender', '$subj', '$msg')";
Related
This question already has answers here:
How can I do 'insert if not exists' in MySQL?
(11 answers)
Closed 2 years ago.
I have a database that contains more than 640,000 records that I update every week with data from a JSON file. What I want to do is only load records into the database that do not currently exists. My script below works on small amounts of data but when I try to load a large file it times out (I get a 500 Internal Server Error). Is there a better way to do this?
<?php
set_time_limit(0);
ini_set('memory_limit','2000M');
$url = 'json/OERrecordstest.json';
$contents = file_get_contents($url);
$records = json_decode($contents, true);
include("../config.php");
echo "<div class='card card-body'>";
foreach($records as $record) {
$type = $record['type'];
$name = $record['title'];
$title = addslashes($name);
$creator = $record['author'];
$author = addslashes($creator);
$link = addslashes($record['link']);
$origin = $record['source'];
$source = addslashes($origin);
$description = addslashes($record['description']);
$base_url = $record['base_url'];
$isbn_number = $record['isbn_number'];
$e_isbn_number = $record['e_isbn_number'];
$publication_date = $record['publication_date'];
$license = $record['license'];
$subject = addslashes($record['subject']);
$image_url = $record['image_url'];
$review = $record['review'];
$language = $record['language'];
$license_url = $record['license_url'];
$publisher = addslashes($record['publisher']);
$publisher_url = $record['publisher_url'];
$query = $conn->prepare("SELECT * FROM oer_search WHERE title=:title AND author=:author AND source=:source");
$query->bindParam(":title", $name);
$query->bindParam(":author", $creator);
$query->bindParam(":source", $origin);
$query->execute();
if ($query->rowCount() == 0) {
$insert = $conn->prepare("INSERT INTO oer_search (type, title, author, link, source, description, base_url, isbn_number, e_isbn_number, publication_date, license, subject, image_url, review, language, license_url, publisher, publisher_url) VALUES ('$type', '$title', '$author', '$link', '$source', '$description', '$base_url', '$isbn_number', '$e_isbn_number', '$publication_date', '$license', '$subject', '$image_url', '$review', '$language', '$license_url', '$publisher', '$publisher_url')");
$insert->execute();
}
}
if($insert){
echo "<p><span class='recordInserted'><em>$name was successfully inserted into SOAR.</em></span></p>";
}
else {
echo "<p><span class='recordInserted'><em>Record(s) already exist in SOAR.</em></span></p>";
}
echo "</div>";
?>
I could not comment, I wrote as an answer because my score was not enough. can you change it like this and try it?
$query = $conn->prepare("SELECT id FROM oer_search WHERE title=:title AND author=:author AND source=:source limit 1");
or
<?php
if(!session_id()) session_start();
ini_set('memory_limit', '2000M');
$url = 'json/OERrecordstest.json';
$contents = file_get_contents($url);
$records = json_decode($contents, true);
include("../config.php");
echo "<div class='card card-body'>";
if (!$_SESSION["records"]) {
foreach ($records as $record) {
$_SESSION["records"][$record["id"]] = $records;
}
}
$i = 0;
foreach ($_SESSION["records"] as $record) {
$i++;
if ($i > 1000) break;
$type = $record['type'];
$name = $record['title'];
$title = addslashes($name);
$creator = $record['author'];
$author = addslashes($creator);
$link = addslashes($record['link']);
$origin = $record['source'];
$source = addslashes($origin);
$description = addslashes($record['description']);
$base_url = $record['base_url'];
$isbn_number = $record['isbn_number'];
$e_isbn_number = $record['e_isbn_number'];
$publication_date = $record['publication_date'];
$license = $record['license'];
$subject = addslashes($record['subject']);
$image_url = $record['image_url'];
$review = $record['review'];
$language = $record['language'];
$license_url = $record['license_url'];
$publisher = addslashes($record['publisher']);
$publisher_url = $record['publisher_url'];
$query = $conn->prepare("SELECT id FROM oer_search WHERE title=:title AND author=:author AND source=:source limit 1");
$query->bindParam(":title", $name);
$query->bindParam(":author", $creator);
$query->bindParam(":source", $origin);
$query->execute();
if ($query->rowCount() == 0) {
$insert = $conn->prepare("INSERT INTO oer_search (type, title, author, link, source, description, base_url, isbn_number, e_isbn_number, publication_date, license, subject, image_url, review, language, license_url, publisher, publisher_url) VALUES ('$type', '$title', '$author', '$link', '$source', '$description', '$base_url', '$isbn_number', '$e_isbn_number', '$publication_date', '$license', '$subject', '$image_url', '$review', '$language', '$license_url', '$publisher', '$publisher_url')");
$insert->execute();
unset($_SESSION["records"][$record["id"]]);
}
}
print "remaining data :". count($_SESSION["records"]);
?>
Tipps to speed up mass-imports:
Move your SQL prepare outside of the loop (you only have to do it once)
Collect data to insert into batches of 1000 (for example.. usually alot more possible)
Use transactions / disable Index calculation during insert
Find duplicates with a lookup array from existing data (don't query the database for each row of your import)
In general: Avoid SQL queries in Loops
hope that helps a bit
This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 5 years ago.
I am using the code below i need to check the description must not be same so i have to check the description column for duplicate entry how to do this ?
<?php
session_start();
require 'Admin/includes/connection.php';
$emp_id = $_SESSION['id'];
$task_name = $_POST['task_name'];
$desc = $_POST['desc'];
$hours = $_POST['hours'];
$t = "random";
$a = date('Y-m-d');
$sql = "INSERT INTO project_task (emp_id, task_type, task, description, hours, submit_date) VALUES ('$emp_id', '$t', '$task_name', '$desc', '$hours', '$a')";
if($conn->query($sql) === TRUE){
$data["abc"] = "true";
}
else{
$data["abc"] = "false";
}
header("Content-type: application/json");
echo json_encode($data);
?>
This Will Help You
<?php
session_start();
require 'Admin/includes/connection.php';
$emp_id = $_SESSION['id'];
$task_name = $conn->real_escape_string($_POST['task_name']);
$desc = $conn->real_escape_string($_POST['desc']);
$hours = $_POST['hours'];
$t = "random";
$a = date('Y-m-d');
$q = "SELECT description from project_task where description = '$desc' ";
$result = $conn->query($q);
if($result->num_rows > 0 ){
$data["result"] = "false";
}else{
$sql = "INSERT INTO project_task (emp_id, task_type, task, description, hours, submit_date) VALUES ('$emp_id', '$t', '$task_name', '$desc', '$hours', '$a')";
if($conn->query($sql) === TRUE){
$data["result"] = "true";
}
else{
$data["result"] = "false";
}
}
header("Content-type: application/json");
echo json_encode($data);
?>
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 7 years ago.
<?php
require_once('config.php');
//print_r($_POST);
if(isset($_POST["btnsubmit"]))
{
$flagvalidate = "yes";
//print_r($_POST);
/*foreach($_POST as $key=>$value)
{
if($value=="" && $flagvalidate=="yes")
{
//$flagvalidate = "no";
}
}*/
if($flagvalidate=="yes")
{
$db_fields = "empimage, postapplied, surname, firstname, fathername, dob, age, gender, nationality, religion,mothertongue, caste, subcaste, category, bloodgroup,rhfactor, maritalstatus, name, address, city, state, pincode, telephone, mobile, email, areaofinterest, specialachievements, fitforpost, createdate";
$postvalues = array();
$postvalues[0] = $_POST['hidempimage'];
$postvalues[1] = $_POST['txtpostapplied'];
$postvalues[2] = $_POST['txtsurname'];
$postvalues[3] = $_POST['txtfirstname'];
$postvalues[4] = $_POST['txtfathername'];
$postvalues[5] = $_POST['txtdob'];
$postvalues[6] = $_POST['txtage'];
$postvalues[7] = $_POST['txtgender'];
$postvalues[8] = $_POST['txtnationality'];
$postvalues[9] = $_POST['txtreligion'];
$postvalues[10] = $_POST['txtmothertongue'];
$postvalues[11] = $_POST['txtcaste'];
$postvalues[12] = $_POST['txtsubcaste'];
$postvalues[13] = $_POST['txtcategory'];
$postvalues[14] = $_POST['txtbloodgroup'];
$postvalues[15] = $_POST['txtrhfactor'];
$postvalues[16] = $_POST['txtmaritalstatus'];
$postvalues[17] = $_POST['txtname'];
$postvalues[18] = $_POST['txtaddress'];
$postvalues[19] = $_POST['txtcity'];
$postvalues[20] = $_POST['txtstate'];
$postvalues[21] = $_POST['txtzipcode'];
$postvalues[22] = $_POST['txttelephone'];
$postvalues[23] = $_POST['txtmobile'];
$postvalues[24] = $_POST['txtemail'];
$postvalues[25] = $_POST['txtareaofinterest'];
$postvalues[26] = $_POST['txtspecialachievements'];
$postvalues[27] = $_POST['txtfitforpost'];
$postvalues[28] = time();
$db_values="";
foreach($postvalues as $key=>$value)
{
if($db_values=="")
$db_values.="'".mysql_real_escape_string($value)."'";
else
$db_values.=", '".mysql_real_escape_string($value)."'";
}
$sqlquery = "insert into tbl_employee (".$db_fields.") values (".$db_values.")";
mysql_query($sqlquery);
$currentempid = mysql_insert_id();
$education_db_fields = "empid, exampassed, degree, subjects, university, year, percentagemarks";
for($i=1;$i<=$_POST['hideducationcount'];$i++)
{
$education_postvalues = array();
$education_postvalues[0] = $currentempid;
$education_postvalues[1] = $_POST['txtexampassed'.$i];
$education_postvalues[2] = $_POST['txtdegree'.$i];
$education_postvalues[3] = $_POST['txtedusubjects'.$i];
$education_postvalues[4] = $_POST['txtuniversity'.$i];
$education_postvalues[5] = $_POST['txtyear'.$i];
$education_postvalues[6] = $_POST['txtpercentagemarks'.$i];
$education_db_values="";
foreach($education_postvalues as $key=>$value)
{
if($education_db_values=="")
$education_db_values.="'".mysql_real_escape_string($value)."'";
else
$education_db_values.=", '".mysql_real_escape_string($value)."'";
}
$sqlquery = "insert into tbl_empeducationdetails (".$education_db_fields.") values (".$education_db_values.")";
mysql_query($sqlquery);
}
$experience_db_fields = "empid, level, name, address, post, fromdate, todate";
for($i=1;$i<=$_POST['hidexperiencecount'];$i++)
{
$experience_postvalues = array();
$experience_postvalues[0] = $currentempid;
$experience_postvalues[1] = $_POST['txtexlevel'.$i];
$experience_postvalues[2] = $_POST['txtexname'.$i];
$experience_postvalues[3] = $_POST['txtexadd'.$i];
$experience_postvalues[4] = $_POST['txtexpostheld'.$i];
$experience_postvalues[5] = $_POST['txtexfromdate'.$i];
$experience_postvalues[6] = $_POST['txtextodate'.$i];
$experience_db_values="";
foreach($experience_postvalues as $key=>$value)
{
if($experience_db_values=="")
$experience_db_values.="'".mysql_real_escape_string($value)."'";
else
$experience_db_values.=", '".mysql_real_escape_string($value)."'";
}
$sqlquery = "insert into tbl_empexperience (".$experience_db_fields.") values (".$experience_db_values.")";
mysql_query($sqlquery);
}
$reference_db_fields = "empid, name, position, cell, email, address ";
for($i=1;$i<=2;$i++)
{
if ( $_POST['txtrefname'.$i]!='')
{
$reference_postvalues = array();
$reference_postvalues[0] = $currentempid;
$reference_postvalues[1] = $_POST['txtrefname'.$i];
$reference_postvalues[2] = $_POST['txtrefpos'.$i];
$reference_postvalues[3] = $_POST['txtrefcell'.$i];
$reference_postvalues[4] = $_POST['txtrefemail'.$i];
$reference_postvalues[5] = $_POST['txtrefpost'.$i];
$reference_db_values="";
foreach($reference_postvalues as $key=>$value)
{
if($reference_db_values=="")
$reference_db_values.="'".mysql_real_escape_string($value)."'";
else
$reference_db_values.=", '".mysql_real_escape_string($value)."'";
}
$sqlquery = "insert into tbl_empreference (".$reference_db_fields.") values (".$reference_db_values.")";
mysql_query($sqlquery);
}
}
header("Location: registercomplete.php");
}
else
{
exit;
}
//echo "<script>alert('Please fill all the fields in the Application Form!');window.location.href='register.php';</script>";
}
?>
i am getting Warning: Cannot modify header information - headers already sent by (output started at /home/zealouse/public_html/skillhr/config.php:11) in /home/zealouse/public_html/skillhr/registerprocess.php on line 150
can any one help me?
Thanks in advance....
Check if there is any outputs in your config.php file.
I have the code below and i can't figure why it's not working. The problem it's that i can insert a post with it, but when i try to update a post it's create a new page instead to update.
I have tried to remove isset from if(isset($_POST['id']) != 'null') and the update work, but then the insert doesn't work anymore.
Any idea what it's wrong with my code? Thanks.
<?php
if(isset($_POST['submitted']) == 1)
{
$title = mysqli_real_escape_string($dbc, $_POST['title']);
$header = mysqli_real_escape_string($dbc, $_POST['header']);
$body = mysqli_real_escape_string($dbc, $_POST['body']);
if(isset($_POST['id']) != 'null')
{
$q = "UPDATE pages SET user = $_POST[user], title = '$title', header = '$header', body = '$body' WHERE id = $_GET[id]";
}
else
{
$q = "INSERT INTO pages (user, title, header, body) VALUES ($_POST[user], '$title', '$header', '$body')";
}
$r = mysqli_query($dbc, $q);
if($r)
{
$message = '<p>Page was added!</p>';
}
else
{
$message = '<p>Page could not be added because:</p>'.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
?>
You are using post and get at the same time. first check whethet it is post or get. then just simply do isset() check
<?php
if(isset($_POST['submitted']) == 1)
{
$title = mysqli_real_escape_string($dbc, $_POST['title']);
$header = mysqli_real_escape_string($dbc, $_POST['header']);
$body = mysqli_real_escape_string($dbc, $_POST['body']);
if(isset($_GET['id']) && $_GET['id']!="")
{
$q = "UPDATE pages SET user = $_POST[user], title = '$title', header = '$header', body = '$body' WHERE id = $_GET[id]";
}
else
{
$q = "INSERT INTO pages (user, title, header, body) VALUES ($_POST[user], '$title', '$header', '$body')";
}
$r = mysqli_query($dbc, $q);
if($r)
{
$message = '<p>Page was added!</p>';
}
else
{
$message = '<p>Page could not be added because:</p>'.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
?>
Try this :
if(isset($_POST['id']) AND $_POST['id'] != 'null')
use this code: if(isset($_POST['id'] && $_POST['id']!= '')
I'm currently making a simple script that takes a user input named comments and putting it in a database. Every time I use the same email, I want it to overwrite their last entry. However, it keeps putting a new entry every time. Here is my code:
if($comments){
try{
echo "<img width=\"245\" height=\"130\" src=\"logo.png\"/><br/>";
echo "<h1>Thank you. You should receive your order on xx-xx-xx</h1>";
$TF = "TRUE";
if($numrows == 0){
$postquery = "INSERT INTO TTT25 (email,card,changes,comments) VALUES ('$email','$businesscard','$TF','$comments')";
$querythepost = sqlsrv_query($conn, $postquery);
}
else{
$postquery = "UPDATE TTT25 SET changes = '$TF', comments = '$comments' WHERE email = '$email'";
$querythepost = sqlsrv_query($conn, $postquery);
}
}
catch(Exception $e){}
}
elseif($optout=="false"){
echo "<img width=\"245\" height=\"130\" src=\"logo.png\"/><br/>";
echo "<h1>Thank you. You should receive your order on xx-xx-xx</h1>";
$TF = "FALSE";
$comments = "";
if($numrows == 0){
$postquery = "INSERT INTO TTT25 (email,card,changes,comments) VALUES ('$email','$businesscard','$TF','$comments')";
$querythepost = sqlsrv_query($conn, $postquery);
}
else{
$postquery = "UPDATE TTT25 SET changes = '$TF', comments = '$comments' WHERE email = '$email'";
$querythepost = sqlsrv_query($conn, $postquery);
}
}
Sorry it must have cut off:
my num rows and other variables defined before the conditional statements:
$optout = $_GET['opt'];
$encodedemail = $_GET['email'];
$email = base64_decode($encodedemail);
$originalcard = base64_decode($_GET['card']);
$businesscard = $originalcard;
$comments = $_POST['comments'];
//$primary = md5(uniqid(rand (), true)); no longer needed
$postquery;
$TF;
$sqlmatch = sqlsrv_query("SELECT * FROM TTT25 WHERE email = '".$email."'");
$numrows = sqlsrv_num_rows($sqlmatch);
echo $numrows;