Why won't mysql query with my php script? - php

I'm trying to make this information insert into my table in mysql database with this script I wrote.
<?php
require("../includes/db.php");
$nme = $_POST["nme"];
$email = $_POST["email"];
$address = $_POST["address"];
$city = $_POST["city"];
$state = $_POST["state"];
$zip = $_POST["zip"];
$phone = $_POST["phone"];
$options = implode($_POST["options"],", ");
$query = mysql_query("insert into peeps (name, email, address, city, zip, phone, type) values ('$nme','$email','$address','$city','$state','$zip','$phone','$options')");
if($query)
print "yes";
else
print "no";
?>
The output of this code is no.

If mysql_query() returns false, it means the query failed.
Try this:
if (false === $query) // make sure it's actually boolean false
print mysql_error(); // print a nice plain-english description of the problem.
else
print "Yes";
This should give you a good idea of where the problem is.

If you modify this part of your code you can see the exact error you get.
if($query)
{
print "yes";
}
else
{
print mysql_error(); ;
}
However the way you have written may generate errors if you do not have enabled Magic Quotes. If you have that kind of error you better use mysql_escape_string

Related

Error adding data in mysql table using PHP

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

Inserting data by PHP and MySQL

It's working, but when I add the data in to my database, the data will be twice. I don't know if my syntax is wrong or my code is wrong.
Here's the structure:
//if submit is clicked
$checkin = $_POST['text_checkin'];
while ($row = mysqli_fetch_array($reservation)) {
if (isset($_POST['submitBtn'])) {
if ($row['reservefrom'] == $checkin) {
echo "Same Date";
return;
}
else
{
$lastname = $_POST['text_lastname'];
$firstname = $_POST['text_firstname'];
$address = $_POST['text_address'];
$tnumber = $_POST['text_tnumber'];
$cnumber = $_POST['text_cnumber'];
$email = $_POST['text_email'];
$checkin = $_POST['text_checkin'];
$checkout = $_POST['text_checkout'];
$room = $_POST['text_room'];
$tour = $_POST['text_tour'];
$guest = $_POST['text_guest'];
$query = "INSERT INTO reservation
(lastname, firstname, homeaddress,
telephonenumber, cellphonenumber, email,
reservefrom, reserveto, room, tour,
guestnumber)
values ('$lastname', '$firstname', '$address',
'$tnumber', '$cnumber', '$email', '$checkin',
'$checkout', '$room', '$tour', '$guest')";
mysqli_query($db, $query);
echo "Data Submitted!";
}
}
}
You're getting multiple inserts because you are looping for each record in $reservations. You should first look into why you are getting multiple records if you expected just a single record reservation.
That aside, alter your code by replacing your while loop with:
if(isset($_POST['submitBtn']) && $row = mysqli_fetch_array($reservation)){
if($row['reservefrom'] == $checkin) die("Same Date");
$lastname = $_POST['text_lastname'];
$firstname = $_POST['text_firstname'];
// ... other values, then execute your query
}else{
// either submitBtn was not posted or no result were found in $reservation
}
I noticed also that you use return in your code, but the code doesn't seem to be within a function so that's confusing. If it is within a function, it's probably a bad idea to echo from within unless the function is specifically meant to send data directly to the browser.

Guestbook adding entry without checking fields

I got the code for this guestbook from a tutorial, but I decided to add some security and ip checking to it. I am learning php while doing this. The problem I'm having is with the "If else" statements not checking anything and just adding it to the database. Here's the code:
if ($_POST['postbtn']) {
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$message = strip_tags($_POST['message']);
$answer = 'abcdefg';
$response = strtolower(strip_tags($_POST['answer']));
// Check if all fields were filled out
if ($name && $email && $message && $response) {
$time = date("h:i A");
$date = date("m/d/Y");
$ip = $_SERVER['REMOTE_ADDR'];
}
else {
echo "<p style='color:red;'>You didn't fill out all of the fields.</p>";
}
// Check if security answer was correct
if ($response === $answer) {
echo "<p style='color:red;'>Security answer was incorrect.</p>";
} else {
// Check ip address
$checkIP = mysql_query("SELECT ip FROM guestbook WHERE ip = '$ip'");
}
if (mysql_num_rows($checkIP) > 0) {
echo "<p style='color:red;'>You already signed.</p>";
} else {
// add to the database
mysql_query("INSERT INTO guestbook VALUES (
'', '$name', '$email', '$message', '$time', '$date', '$ip'
)");
// refresh page
header('Location: http://www.example.com/guestbook');
}
}
if (isset($_POST['postbtn'])) {
// define variables after the check if the postbtn is pressed
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$message = strip_tags($_POST['message']);
$answer = 'abcdefg';
$response = strtolower(strip_tags($_POST['answer']));
// Check if all fields were filled out, I turned it arround for you, it checks now if it's empty, if so, process an error, else continue
if (empty($name) || empty($email) || empty($message) || empty($response)) {
echo "<p style='color:red;'>You didn't fill out all of the fields.</p>";
// Check if security answer was correct, you check here if its correct and state incorrect answer.
}else if ($response != $answer) {
echo "<p style='color:red;'>Security answer was incorrect.</p>";
// so now we have all errors out of the way, lets go deeper
}else{
$time = date("h:i A");
$date = date("m/d/Y");
$ip = $_SERVER['REMOTE_ADDR'];
$checkIP = mysql_query("SELECT ip FROM guestbook WHERE ip = '$ip'");
// check if we get anything back from the query
if (mysql_num_rows($checkIP) > 0) {
echo "<p style='color:red;'>You already signed.</p>";
} else {
mysql_query("INSERT INTO guestbook VALUES ('', '$name', '$email', '$message', '$time', '$date', '$ip')");
// refresh page
header('Location: http://www.example.com/guestbook');
}
}
}
I do this out of my head, so dont shoot me down on it. I tried to point out where your flaws where. For example, you had a flaw in the checking of your variables, you had a flaw for your security (you actually would give an error message when you typed in the right security answer)
So to explain it all, in if statements, you need to go deep into the rabbit hole as they say it nicely. Sometimes you need the else statement to continue and go deeper in. This way you can catch better your errors. For example. Your code would input anyway in the database, because even if you had a error it would just get to the point of entering it into the database. (your answers would be ignored, because variabels set inside an if else statement, cant be used outside of that loop. See it as a localized variable)
But if you keep digging deeper in if else statements, you can take them with you.
edit
Also, I indent the code for you, so you see how deep we go and how many if-else statements there actually are. If you have any questions, please dont hesitate ;)
edit2
I actually replaced the response and answer check 1 if else statement down and made an else if to keep all errors near each other. You could also do this with the variable to check the num_rows, but I havent done it. You could also toss that in an else if statement after the security check. This should also work, but to make it prettier, you can go the way i described.
In theory, this should work fine.
It checks everything, but execution is not blocked by errors.
Wrap your code into try-catch block and throws exception on every error.
try {
if ($_POST['postbtn']) {
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$message = strip_tags($_POST['message']);
$answer = 'abcdefg';
$response = strtolower($_POST['answer']);
// Check if all fields were filled out
// Invert condition
if (!$name || !$email || !$message || $response) {
throw new Exception("You didn't fill out all of the fields.");
}
$time = date("h:i A");
$date = date("m/d/Y");
$ip = $_SERVER['REMOTE_ADDR'];
// And so on...
}
}
catch (Exception $e) {
echo "<p style='color:red;'>" . $e->getMessage() . "</p>";
}

Array objects not being printed in input fields and sql query not receiving the id value

I am getting the id from another page but i am not being able to pass it to the sql query. If i define any value to $id instead of 0 then the query works but otherwise it fails.
Secondly, i would like to display the values of the array in respective input fields. I tried using
<?php
echo $result_array['institutename'][0];
?>
in the body part but it didnt work out.
My rest code is as follows:
(I know the mysql functions are deprecated but i would move on to mysqli as soon as i have solved this problem)
<?php
include 'connect.php';
$id=0;
$result_array=array();
if(isset($_REQUEST['id'])){
$id=(int)$_REQUEST['id'];
//$uid=$id;
if(!empty($id)){
$sql = "SELECT * FROM institute WHERE id =$id";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$result_array[]=$row;
}
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['form_institutedetails'] == 'saveinstitutedetails')
{
$mysql_table='institute';
$institutename = $_POST['institutename'];
$established = $_POST['established'];
$regno = $_POST['reg_no'];
$branch = $_POST['branch'];
$initials = $_POST['initials'];
$address=$_POST['address'];
$pin=$_POST['pin'];
$contact1=$_POST['contact1'];
$contact2=$_POST['contact2'];
$contact3=$_POST['contact3'];
$fax1=$_POST['fax1'];
$fax2=$_POST['fax2'];
$email=$_POST['email'];
$website=$_POST['website'];
if(isset($_POST['head_office'])){
$head_office=$_POST['head_office'];
}
else{
$head_office="Branch";
}
if (!preg_match("/^.+#.+\..+$/", $email))
{
$error_message = 'Email is not a valid email address. Please check and try again.';
}
if (empty($error_message))
{
$newinstitutename = mysql_real_escape_string($institutename);
$newestablished = mysql_real_escape_string($established);
$newregno = mysql_real_escape_string($regno);
$newbranch = mysql_real_escape_string($branch);
$newaddress = mysql_real_escape_string($address);
$newpin = mysql_real_escape_string($pin);
$newemail = mysql_real_escape_string($email);
$newwebsite = mysql_real_escape_string($website);
$ho = mysql_real_escape_string($head_office);
include 'connect.php';
$sql = "UPDATE `".$mysql_table."` SET `institutename`='$newinstitutename', `established`='$newestablished', `regno`='$newregno', `branch`='$newbranch', `initials`='$initials', `address`='$newaddress', `pin`='$newpin', `contact1`='$contact1', `contact2`='$contact2', `contact3`='$contact3', `fax1`='$fax1', `fax2`='$fax2', `email`='$newemail', `website`='$newwebsite', `head_office`='$ho' WHERE `id`=$id";
$result = mysql_query($sql, $db);
mysql_close($db);
$error_message='Updated Successfully!.';
}
}
?>
When you are unsure about the structure of an array, you can always do a print_r during development.
print_r($result_array);
In this case, it is an index array of associative arrays.
To access the first record's institutename (and probably the only record since it looks like you used an unique key in your query), you can use
echo $result_array[0]['institutename'];

Cannot execute sql INSERT query (mysql_query) in php script. PHP/MySQL -- Time Sensitive

UPDATE: NOW RESOLVED - Thanks everyone!
Fix: I had a column named "referred_by" and in my code it's called "referred_by_id" - so it was trying to INSERT to a column that didn't exist -- once I fixed this, it decided to work!
I have limited time left to work on this project. The clock is ticking.
I'm trying to INSERT $php_variables into a TABLE called "clients".
I've been trying for hours to get this script to work, and I got it to work once, but then I realized I forgot a field, so I had to add another column to the TABLE and when I updated the script it stopped working. I reverted by but now it's still not working and I'm just frustrating myself too much.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if (!isset($_COOKIE["user"]))
{
header ("Location: ./login.php");
}
else
{
include ("./source.php");
echo $doctype;
}
$birthday = $birth_year . "-" . $birth_month . "-" . $birth_day;
$join_date = date("Y-m-d");
$error_type = 0;
$link = mysql_connect("SERVER", "USERNAME", "PASSWORD");
if (!$link)
{
$error = "Cannot connect to MySQL.";
$error_type = 1;
}
$select_db = mysql_select_db("DATABASE", $link);
if (!$select_db)
{
$error = "Cannot connect to Database.";
$error_type = 2;
}
if ($referred_by != "")
{
$result = mysql_query("
SELECT id FROM clients WHERE referral_code = $referred_by
");
if (!$result)
{
$error = "Cannot find referral.";
$error_type = 3;
}
while ($row = mysql_fetch_array($result))
{
$referred_by_id = $row['id'];
}
}
else
{
$referred_by_id = 0;
}
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$birth_month = mysql_real_escape_string($_POST['birth_month']);
$birth_day = mysql_real_escape_string($_POST['birth_day']);
$birth_year = mysql_real_escape_string($_POST['birth_year']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
$zip_code = mysql_real_escape_string($_POST['zip_code']);
$phone_home = mysql_real_escape_string($_POST['phone_home']);
$phone_cell = mysql_real_escape_string($_POST['phone_cell']);
$referral_code = mysql_real_escape_string($_POST['referral_code']);
$referred_by = mysql_real_escape_string($_POST['referred_by']);
$organization = mysql_real_escape_string($_POST['organization']);
$gov_type = mysql_real_escape_string($_POST['gov_type']);
$gov_code = mysql_real_escape_string($_POST['gov_code']);
$test_query = mysql_query
("
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."')
");
if (!$test_query)
{
die(mysql_error($link));
}
if ($error_type > 0)
{
$title_name = "Error";
}
if ($error_type == 0)
{
$title_name = "Success";
}
?>
<html>
<head>
<title><?php echo $title . " - " . $title_name; ?></title>
<?php echo $meta; ?>
<?php echo $style; ?>
</head>
<body>
<?php echo $logo; ?>
<?php echo $sublogo; ?>
<?php echo $nav; ?>
<div id="content">
<div id="main">
<span class="event_title"><?php echo $title_name; ?></span><br><br>
<?php
if ($error_type == 0)
{
echo "Client was added to the database successfully.";
}
else
{
echo $error;
}
?>
</div>
<?php echo $copyright ?>
</div>
</body>
</html>
Definitely not working as is. Looks you have a 500 error, since you have an else with a missing if:
else
{
$referred_by_id = 0;
}
Otherwise, you'll need to post your DB schema.
Also, note that you're really taking the long way around with this code, which makes it difficult to read & maintain. You're also missing any sort of checks for SQL injection... you really need to pass things through mysql_real_escape_string (and really, you should use mysqli, since the mysql interface was basically deprecated years ago).
$keys = array('first_name',
'last_name',
'birthday',
'join_date',
'email',
'address',
'city',
'state',
'zip_code',
'phone_home',
'phone_cell',
'referral_code',
'referred_by_id',
'organization',
'gov_type',
'gov_code');
$_REQUEST['birthdate'] = $_REQUEST['birth_year'].'-'.$_REQUEST['birth_month'].'-'.$_REQUEST['birth_day'];
$_REQUEST['join_date'] = date('Y-m-d',time());
$params = array();
foreach ($keys as $key)
{
$params[] = mysql_real_escape_string($request[$key]);
}
$sql = 'INSERT INTO clients ('.implode(',', $keys).') ';
$sql .= ' VALUES (\''.implode('\',\'', $params).'\') ';
You've an error on line 81:
else
{
$referred_by_id = 0;
}
I don't see an IF construct before that, make the appropriate correction and run the script again.
Without looking at the table structure to make sure all the fields are there, I'm going to assume it's something with the data.
Any quotes in the data will lead to problems (including SQL injection security holes). You should wrap each $_POST[] with mysql_real_escape_string(), such as:
$first_name = mysql_real_escape_string($_POST['first_name']);
EDIT: Further debugging...
As someone suggested (sorry, can't find the comment), try:
$sql = "
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."'
)";
// Debug:
print "<pre>". $sql ."</pre>";
mysql_query($sql);
The SQL statement should be printed out when submitting the form. Take that SQL statement and try to execute it directly in MySQL to see if it works, or if it generates an error.

Categories