Mysql query not inserting into database? - mysql

I am trying to insert data posted from a form into my database using the following MySQL statement but it is producing my error 'Oooops! *** **** ***'
I know there is a connection because before I insert anything I test the users email address to see if it already exists and if it does it redirects the user to login. and this works so if the email doesn't exist in the database then it is suppose to be inserting the form data but it isn't.
* can someone please show me where I am going wrong? I have made sure I am spelling the table names correct and everything and am 100% sure I have posted all my form data correctly.
<?php
session_start();
include("config.php");
include("verify.php");
//retrieve our data from POST
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$contactnum = $_POST['contactnum'];
$mobnum = $_POST['mobnum'];
$postcode = $_POST['postcode'];
$addres1 = $_POST['address1'];
$addres2 = $_POST['address2'];
$town = $_POST['town'];
$compname = $_POST['compname'];
$compreg = $_POST['compreg'];
$verify = $_POST['verify'];
$verification = $_POST['verification'];
$firstname = stripslashes($firstname);
$firstname = mysql_real_escape_string($firstname);
$lastname = stripslashes($lastname);
$lastname = mysql_real_escape_string($lastname);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$email2 = stripslashes($email2);
$email2 = mysql_real_escape_string($email2);
$contactnum = stripslashes($contactnum);
$contactnum = mysql_real_escape_string($contactnum);
$mobnum = stripslashes($mobnum);
$mobnum = mysql_real_escape_string($mobnum);
$postcode = stripslashes($postcode);
$postcode = mysql_real_escape_string($postcode);
$addres1 = stripslashes($addres1);
$addres1 = mysql_real_escape_string($addres1);
$addres2 = stripslashes($addres2);
$addres2 = mysql_real_escape_string($addres2);
$town = stripslashes($town);
$town = mysql_real_escape_string($town);
$compname = stripslashes($compname);
$compname = mysql_real_escape_string($compname);
$compreg = stripslashes($compreg);
$compreg = mysql_real_escape_string($compreg);
$verify = stripslashes($verify);
$verify = mysql_real_escape_string($verify);
$verification = stripslashes($verification);
$verification = mysql_real_escape_string($verification);
$query = sprintf("SELECT * FROM supplier_registration WHERE supplier_email='%s'", mysql_real_escape_string($email2));
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
$_SESSION['message2'] = '<div id="message_box3"><div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"></div><h23>Found You!</h23><p>It appears that a user with that email address is already registered. Please Login below or click on our support section.</p> </div>';
header('Location: ../login.php');
} else {
$sql = "INSERT INTO supplier_registration (id, first_name, last_name, supplier_email, contact_number, mobile_number, postcode, address1, address2, town, company_name, company_reg, date) VALUES (NULL, '$firstname','$lastname','$email2', '$contactnum', '$mobnum', '$postcode', NULL, NULL, NULL, '$compname', '$compreg', now())";
$result2 = mysql_query($sql);
if(mysql_num_rows($result2) > 0) {
$_SESSION['message2'] = '<div id="message_box3"><div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"></div><h23>Thanks for Registering!</h23><p>You have successfully registered. We have sent you a verification email.</p> </div>';
header('Location: ../index.php');
}else{
$_SESSION['message2'] = '<div id="message_box3"><div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"></div><h23>Oooops!</h23><p>It appears there was an error whilst attempting to register your details. Please try again later.</p> </div>';
header('Location: ' . $_SERVER['HTTP_REFERER']);
} }
?>

The error may relate to the datatypes of the fields in your table.
In your code there is no conversion of strings to numbers.
If you add the table definition and the exact SQL error to your question more help can be given.

try this..
$sql = "INSERT INTO supplier_registration (id, first_name, last_name, supplier_email, contact_number, mobile_number, postcode, address1, address2, town, company_name, company_reg, date) VALUES ('', '$firstname','$lastname','$email2', '$contactnum', '$mobnum', '$postcode', '', '', '', '$compname', '$compreg', now())";
$result2 = mysql_query($sql);

It's because date in your query is a Reserved Keyword. so you'll have to put in [] like this [date]

Related

how to add multiple JSON data links to Mysql

I have a lot of links which has JSON data inside and i need the data from links to mysql, what could be fastest way for that ?
Is it possible to modify this code below to make it able to read from multiple urls ?
<?php
//connect to mysql db
$con = mysql_connect("username","password","") or die('Could not connect: ' . mysql_error());
//connect to the employee database
mysql_select_db("employee", $con);
//read the json file contents
$jsondata = file_get_contents('empdetails.json');
//convert json object to php associative array
$data = json_decode($jsondata, true);
//get the employee details
$id = $data['empid'];
$name = $data['personal']['name'];
$gender = $data['personal']['gender'];
$age = $data['personal']['age'];
$streetaddress = $data['personal']['address']['streetaddress'];
$city = $data['personal']['address']['city'];
$state = $data['personal']['address']['state'];
$postalcode = $data['personal']['address']['postalcode'];
$designation = $data['profile']['designation'];
$department = $data['profile']['department'];
//insert into mysql table
$sql = "INSERT INTO tbl_emp(empid, empname, gender, age, streetaddress, city, state, postalcode, designation, department)
VALUES('$id', '$name', '$gender', '$age', '$streetaddress', '$city', '$state', '$postalcode', '$designation', '$department')";
if(!mysql_query($sql,$con))
{
die('Error : ' . mysql_error());
}
?>
Here is an example of reading url's from a excel file.
I am using http://code.google.com/p/php-excel-reader/.
File - urls.xls.
It assumes this excel contains url's in the first column.
<?php
//connect to mysql db
$con = mysql_connect("username","password","") or die('Could not connect: ' . mysql_error());
//connect to the employee database
mysql_select_db("employee", $con);
$data = new Spreadsheet_Excel_Reader("urls.xls",false);
$rows = $data->rowcount(0);
for( $i=0;$i<$rows;$i++ ) {
//read the json file contents
$jsondata = file_get_contents($data->val($i,0));
//convert json object to php associative array
$data = json_decode($jsondata, true);
//get the employee details
$id = $data['empid'];
$name = $data['personal']['name'];
$gender = $data['personal']['gender'];
$age = $data['personal']['age'];
$streetaddress = $data['personal']['address']['streetaddress'];
$city = $data['personal']['address']['city'];
$state = $data['personal']['address']['state'];
$postalcode = $data['personal']['address']['postalcode'];
$designation = $data['profile']['designation'];
$department = $data['profile']['department'];
//insert into mysql table
$sql = "INSERT INTO tbl_emp(empid, empname, gender, age, streetaddress, city, state, postalcode, designation, department)
VALUES('$id', '$name', '$gender', '$age', '$streetaddress', '$city', '$state', '$postalcode', '$designation', '$department')";
if(!mysql_query($sql,$con))
{
die('Error : ' . mysql_error());
}
}
?>
Hope this helps.

adding a condition to a WHERE clause based on a passed variable value mysql

I am a relative novice and could use some help with this problem.
This will be used in a search filter situation.
Users need to search by a value and 1 or more other values passed by the search form.
$name = $_POST['name'];
$sdate = $_POST['sdate'];
$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
$vehicle = $_POST['vehicle'];
$triptype = $_POST['triptype'];
If any of these values are '' I do not want them in the query, If they contain a value I do want them in the query.
SELECT * FROM form_data WHERE `resp_person` = '$name',
IF $sdate != '' then `sdate` = '$sdate',
IF $startdate != '' then `sdate` = *all values between $startdate and $enddate*,
IF $triptype != '' then `triptype` = '$vehicle',
IF $vehicle != '' then `vehicle` = '$vehicle', `sdate`
ORDER BY `sdate` DESC, `stime` DESC")
I know the code is wrong but it should give you a good idea of what I am trying to accomplish. Any guidance would be greatly appreciated.
A better way is to not use string concatenation to build the entire query, but rather use an sql library that supports prepared statements, such as PDO.
$pdo = new PDO('... connection string ...', username, password);
$where = '';
$possible_values = array('name', 'sdate', 'startdate', 'enddate', 'vehicle', 'triptype' );
$params = array();
foreach($possible_values as $val)
{
if(isset($_POST[$val]))
{
$params[] = $_POST[$val];
if($where == '')
{
$where = "WHERE $val = ?";
}
else
{
$where .= " AND $val = ?";
}
}
}
$stmt = $pdo->prepare("SELECT * FROM form_data " . $where);
$stmt->execute($params);
In cases like this, I prefer to build the query in pieces...
$wheres = array(); // Collect things to AND together
if ($searchterm != 'All') $wheres[] = "subject LIKE '%searchterm'";
if (...) $wheres[] = "...'";
...
if (count($wheres) > 0)
$where_str = "WHERE " . implode(' AND ', $wheres);
else
$where_str = '';
$order_str = (...) ? "ORDER BY ..." : '';
$limit_str = $limit ? "LIMIT $limit" : '';
$query = "SELECT ... FROM foo $where_str $order_str $limit_str";
Oh, and don't forget to use escape the strings on any data coming in from a form -- else a user can do nasty things to the SQL statement!

Why is my UPDATE Query not working?

I have the following update query but for some reason it's not working. I think it's something to do with the "id = '".$id."' but I've tried about three different ways and I cannot seem to get it to work. I've written update queries before with no problems but for some reason this one is being a pain. Thanks in advance.
$id = $_GET['id'];
$speaker = mysql_real_escape_string($_POST['speaker']);
$message = $_POST['message'];
$title = mysql_real_escape_string($_POST['title']);
$date = $_POST['date'];
$day = $_POST['day'];
$password = mysql_real_escape_string($_POST['password']);
$complete = $_POST['complete'];
$title = ucwords(strtolower($title));
if ($complete && ($password == "*****"))
{
$db = mysql_connect($hostname, $username, $password) or die(mysql_error());
mysql_select_db($dbname,$db) or die(mysql_error());
mysql_query("UPDATE sermons SET speaker = '$speaker', message = '$message', title = '$title', date = '$date', day = '$day' WHERE id = '$id'");
$num_rows = mysql_num_rows(mysql_query("SELECT speaker, message, title, date, day FROM sermons WHERE speaker = '$speaker' AND message = '$message' AND title = '$title' AND date = '$date' AND day = '$day'", $db));
if ($num_rows == 1)
echo "<script type='text/javascript'> alert('Sermon Information Entered Successfully!'); </script>";
else
echo "<script type='text/javascript'> alert('Error! Please Try Again.'); </script>";
}
else if ($complete && ($password != "*****"))
{
echo "<script type='text/javascript'> alert('Incorrect Password! Please Try Again.'); </script>";
}
Because of id is Integer so this is correct code try thus :
mysql_query("UPDATE sermons SET speaker = '$speaker', message = '$message', title = '$title', date = '$date', day = '$day' WHERE id =".$id);
I expected it will be works.
Writing this as an answer as providing code in comments is difficult to read
Try changing
mysql_query("UPDATE sermons SET speaker = '$speaker', message = '$message', title = '$title', date = '$date', day = '$day' WHERE id = '$id'");
To
mysql_query("UPDATE sermons SET speaker = '$speaker', message = '$message', title = '$title', date = '$date', day = '$day' WHERE id = '$id'") or die(mysql_error());
Then add the error message to your question please.

INSERT in a WHILE LOOP Not Inserting into Database

I have a SELECT statement, WHILE statement and an INSERT:
$result = mysqli_query($con,"SELECT winner, time, course, market, twitter_pubstatus
FROM combo
WHERE twitter_pubstatus = 0 AND market = '$win' GROUP BY winner");
while($row = mysqli_fetch_array($result))
{
$winner = $row['winner'];
$time = $row['time'];
$course = $row['course'];
$message = "$winner won the $time at $course. You are a winner! #GetIn";
$query = "INSERT INTO messageTable (MESSAGE) VALUES($message)or die(mysql_error())";
}
It runs through with no errors. There should be 12 rows that get inserted into the database. What am I doing wrong?
Try changing $query = "INSERT INTO messageTable (MESSAGE) VALUES($message)or die(mysql_error())";
to
$query = "INSERT INTO messageTable (MESSAGE) VALUES('$message')or die(mysql_error())";
Notice the single quotes in '$message'
And $query is just a string so execute the query
$result=mysqli_query($query)
And then check if query executed by doing this
if(!$result) die(mysqli_error());

How to prevent null values to updating MySQL database

My update query is
"UPDATE registration SET `dob` = '".$theDate."' , pwd='".$_REQUEST['n_password']."', name='".$_REQUEST['n_name']."' where id='".$_SESSION['id']."' "
Problem is that it is not necessary that user update all fields so if it happens there are null values coming from form and it will replace earlier value in database.
I can update it one by one after checking if field value is not null but if there is any other way r tutorial please help me
I can update it one by one after checking if field value is not null
but if there is any other way r tutorial please help me
Don't issue an UPDATE query after you check each value, instead add that column to the query you're building, then execute just one UPDATE with only the columns that had values.
$dbh = new PDO('mysql:host=localhost;dbname=whatever', 'user', 'password');
$params = array();
$sql = "UPDATE REGISTRATION SET `dob` = ?";
$params[] = $theDate;
if (!empty($_REQUEST['n_password'])) {
$sql .= ", `pwd` = ?";
$params[] = $_REQUEST['n_password'];
}
if (!empty($_REQUEST['n_name'])) {
$sql .= ", `name` = ?";
$params[] = $_REQUEST['n_name'];
}
$sql .= " WHERE `id` = ?";
$params[] = $_SESSION['id'];
$stmt = $dbh->prepare($sql);
$stmt->execute($params);