I'm fairly new to mysql and I was wondering if the following code should be working. I've been checking with my database after submission of this form and nothing is getting inputted into the database. Please let me know what I'm doing wrong, Thank you!
<?php
$username = $_SESSION['username'];
$email = $_POST['email'];
$desc = $_POST['desc'];
$url = $_POST['url'];
$priority = $_POST['priority'];
if( strlen($username) > 0 && strlen($email) > 0 && strlen($desc) > 0)
{
$sql = "INSERT INTO feature_request_table (username, desc, email, url, priority, status)
VALUES( '$username' , '$desc' , '$email' , '$url' , '$priority' , '0' )";
echo "The sql statement is: " . $sql . "</br>";
mysql_query($sql);
//echo "The result is: " . $results . "</br>";
echo "Your request have been sent. Please allow a brief period of time for your webmaster implement your request. Thank you!";
}
mysql_close($con);
?>
Use the return value of mysql_query() and check if it is NULL to find out if the query was successful:
$result = mysql_query($sql);
// A NULL value of $result indicates failure
if (!$result) {
// something went wrong!
// See the error...
echo mysql_error();
}
Also, we don't see in the posted code that mysql_connect() was called. Also check that the connection was successfully made:
$conn = mysql_connect(all the connection details...);
if (!$conn) {
// connection failed
}
One thing I haven't seen mentioned yet is that you may not have auto-commit turned on, in which case your insert will return TRUE, but you will not see any change in the DB until you commit the insert.
You should really use the isset() function instead of strlen. Also, it does look like your never actually connecting to a mysql server according to the given code. Try posting the sql statement that is echoed into phpMyAdmin directly.
Following are the changes you need to do.
Use the column name desc with some other name of enclose in 'desc'.
Always print the error message or even terminate the output.
Check whether the POST Items are received correctly or not.
Here is the modified code.
if( isset($username) && isset($email) && isset($desc) )
{
$sql = "INSERT INTO feature_request_table (username, 'desc', email, url, priority, status)
VALUES( '$username' , '$desc' , '$email' , '$url' , '$priority' , '0' )";
echo "The sql statement is: " . $sql . "</br>";
mysql_query($sql) or die (mysql_error());
//echo "The result is: " . $results . "</br>";
echo "Your request have been sent. Please allow a brief period of time for your webmaster implement your request. Thank you!";
}
This sould do it :
$data = mysql_query($sql);
if($data === false) { // TODO: better error handling
// Do something...
echo mysql_error();
// Or see the errors...
}
Note : if you want to have valid HTML pages in all situations handle your errors don't use OR DIE().
Related
I am trying to use the INSERT INTO SQL statement in php. It will input everything correctly up until the last value ($bands_bio). Instead of putting in the correct information, it leaves the value blank. I have looked over everything and can't seem to find any sort of syntax errors.
$page_title = "Create a new band";
require ('includes/database.php');
require_once 'includes/bandsHeader.php';
$band_name = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_name', FILTER_SANITIZE_STRING)));
$band_photo = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_photo', FILTER_SANITIZE_STRING)));
$genre = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'genre', FILTER_SANITIZE_STRING)));
$band_bio = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_bio', FILTER_SANITIZE_STRING)));
echo $band_bio;
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = "")) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/searchFooter.php';
exit;
}
$albums = 0;
$sql = "INSERT INTO bands VALUES (NULL, '$band_name', '$genre', '$albums', '$band_bio')";
$query = #$conn->query($sql);
if (!$query) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/footer.php';
exit;
}
As you can see, I echoed out $band_bio in order to see if it was getting the right value from my form that uses the GET method, which it is so that's not the issue. It has no problem inserting everything correctly up until the last value, which is supposed to be the last column called band_bio in my bands table in my database. It will not output any errors or anything, either. It's almost as if it's taking the string data from the variable and removing all of the text before it inserts the information.
I have been working on this website for a few weeks now and have used the INSERT INTO statement the exact same way on other pages and it works just fine. This is the first thing that has really stumped me and I can't figure it out. Any help is appreciated.
When inserting, ensure that your pk (id) field is set to auto-increment.
This way, you can exert more control over your queries. You should be more successful with:
$sql = "INSERT INTO bands "
. "(`band_name`,`genre`,`numof_albums`,`band_bio`) "
. "VALUES ('$band_name', '$genre', '$albums', '$band_bio')";
By not specifying the pk field, INNODB will automatically increment and insert it for you.
The idea is that you want to specify which columns are being inserted into. Relying on column ordering by mysql is fine, but there may be something at play in your case.
There should be no reason why band_bio would be "left off". You would get a column-mismatch error.
Totally found the answer myself! It, in fact, was a syntax error.
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = ""))
The variable $band_bio was being assigned to a blank string in the if statement since I accidentally used an assignment operator rather than a comparison operator. So the correct code would need to be $band_bio === "" rather than $band_bio = "".
I swear, the problem is always something so much simpler than you think it's going to be.
here's the php script tht gets the string and insert it in the db .
<?php
include 'connect.php';
$name = $_POST['name'];
$message = $_POST['message'];
$message = nl2br($message);
if(isset($name) && isset($message)){
$sql = "INSERT INTO messages VALUES('','".$name."', '".$message."')";
if($sqlrun = mysqli_query($connection , $sql)){
header('Location:../write.php');
}else{
echo "query doesnt work";
}
}
?>
what can be the reason it works only with small strings?
in the database the field is a text that contain 1000 bits maximum .
Why don't you check if there were any errors? any information is better than no information.
$sql = "INSERT INTO messages VALUES('','".$name."', '".$message."')";
if($sqlrun = mysqli_query($connection , $sql)){
header('Location:../write.php');
exit();
}else{
echo "query doesnt work: " . mysqli_error(); // jaaaj information!
}
I don't know why , but after i cheked the sql query time after time i realized that for the first argument in the values ( the '' which is dedicated for an auto-increment field) , i have to put NULL in there so that the query should be like this :
$sql = "INSERT INTO messages VALUES(NULL,'".$name."', '".$message."')";
again , i don't know exactly why now it works .
anyway thanks everyone !
I'm try to get cookies on to a browser. It's giving me parameter 1 error and parameter 3. This code works elsewhere on my site but not here. Can someone help me?
if ((!isset($_POST["uname"])) || (!isset($_POST["password"])))
{
header ("Location: wddnt/clients/'. $tattoo_extern_acct . '/index.html");
exit;
}
$userpass = md5($_POST['password']);
#$db = mysqli_connect("$dbc_ser", "$dbc_usr", "$dbc_pwd", "$dbc_db");
$sql = "SELECT id, name, company, job_title, cell_num, office_num, office_email,
login_right, first_run, attempts, locked_out FROM login
WHERE email = '".$_POST["email"]."'
AND password = PASSWORD('$userpass')";
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
else
{
$result = mysqli_query($db, $sql);
while ($info = mysqli_fetch_array($result))
{
$id = stripslashes($info['id_files']);
$u_acct = stripslashes($info['uname']);
$name = stripslashes($info['name']);
$job_title = stripslashes($info['job_title']);
$location = stripslashes($info['company']);
$cell_num = stripslashes($info['cell_num']);
$office_num = stripslashes($info['office_num']);
$office_email = stripslashes($info['office_email']);
$login_right = stripslashes($info['login_right']);
$first_run = stripslashes($info['first_run']);
$attempts = stripslashes($info['attempts']);
$locked_out = stripslashes($info['locked_out']);
$land_page = stripslashes($info['land_page']);
}
}
Try debugging some of the individual variables. What is in $sql, for example? Is it correct?
Is the "Cannot connect" clause executed, or does it get to the query and fail there? (I am not sure what "parameter 1 error and parameter 3" means).
Don't forget to escape the 'email' value by the way - this code has an SQL injection hole.
header ("Location: wddnt/clients/'. $tattoo_extern_acct . '/index.html");
This is not going to work the way you expect.
$sql = "SELECT id, name, company, job_title, cell_num, office_num, office_email,
login_right, first_run, attempts, locked_out FROM login
WHERE email = '".$_POST["email"]."'
You need to read up on SQL injection.
while ($info = mysqli_fetch_array($result))
You allow multiple accounts with the same email address / password?????
It's giving me parameter 1 error and parameter 3
Couldn't you post the actual error message you get?
$id = stripslashes($info['id_files']);
WTF? Smartquotes?
I'm not sure i understand your question but the last time i checked anyone who wants to use cookies uses the $_COOKIE global variable, either for setting them or accessing them. $_POST is made to get stuffs from forms, not cookies.
Please check the manual for more details about $_COOKIE
Regards
I created this account registration activation script of my own, I have checked it over again and again to find errors, I don't see a particular error...
The domain would be like this:
http://domain.com/include/register.php?key=true&p=AfRWDCOWF0BO6KSb6UmNMf7d333gaBOB
Which comes from an email, when a user clicks it, they get redirected to this script:
if($_GET['key'] == true)
{
$key = $_GET['p'];
$sql = "SELECT * FROM users
WHERE user_key = '" . $key . "'";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_affected_rows($result) > 0)
{
$sql = "UPDATE users
SET user_key = '', user_active = '1'
WHERE user_key = '" . $key . "'";
$result = mysql_query(sql) or die(mysql_error());
if($result)
{
$_SESSION['PROCESS'] = $lang['Account_activated'];
header("Location: ../index.php");
}
else
{
$_SESSION['ERROR'] = $lang['Key_error'];
header("Location: ../index.php");
}
}
else
{
$_SESSION['ERROR'] = $lang['Invalid_key'];
header("Location: ../index.php");
}
}
It doesn't even work at all, I looked in the database with the user with that key, it matches but it keeps coming up as an error which is extremely annoying me. The database is right, the table and column is right, nothing wrong with the database, it's the script that isn't working.
Help me out, guys.
Thanks :)
Change $_GET['key'] == true to $_GET['key'] == "true"
You do before this if, a successful mysql_connect(...) or mysql_pconnect(...) ?
Change mysql_affected_rows($result); to mysql_num_rows($result);. Affected you can use for DELETE or UPDATE SQL statements.
Before you second if was opened, add before you second mysql_result(...), mysql_free_result($result); to free memory allocated to previous result.
if($result) change to if(mysql_affected_rows($result));. You can do that here.
After the header(...); function call's add a return 0; or exit(0); depends on your complete code logic.
You are using $key variable in SQL statements, to get your code more secure on SQL Injection attacks get change $key = $_GET['p']; to $key = mysql_real_escape_string($_GET['p']);
I think your location in header() functions fails. In header() url address should be full like: http://www.example.com/somewhere/index.php
And check your $_GET['p'] variable exists!! If this not exist and if $_GET['key'] exists, you find all activated users. Then i think the setting user_key to '' is nessesary if you have user_activated marker.
you shouldnt be using:
if(mysql_affected_rows($result) > 0)
You should be using mysql_num_rows()
Your problem is:
$result = mysql_query($sql) or die(mysql_error());
"or" makes your statement boolean so $result gets a True instead of value returned by mysql_query()
echo 'Hello' or die('bye'); // outputs nothing, because result is True not 'Hello'
3 or die() == True; // true
3 or die() != 3; // true
OR is the same as || and it is operator of logical statement.
This will work:
$result = mysql_query($sql);
if(!$result) die(mysql_error());
The same mistake was made a few hours ago: link
Cases where OR can be used:
defined('FOO') or
define('FOO', 'BAR');
mysql_connect(...) or die(...);
mysql_select_db( .... ) or die(...);
mysql_query('UPDATE ...') or die(...);
if(FOO or BAR) { ... }
<?php
include"include/connection.php";
$checkusername=mysql_query("SELECT * FROM employer WHERE eusername='$username'");
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = "insert into employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry) values ('".$_POST['first_name']."','".$_POST['last_name']."','".$_POST['gender']."','".$_POST['email']."','".$_POST['username']."','".$_POST['password']."','".$_POST['address']."','".$_POST['phone']."','".$_POST['city']."','".$_POST['country']."')";
$result = mysql_query($query) or die (mysql_error());
echo " Thanks for registration";
}
?>
This is my code for inserting registration form data into a database. This code adds the data but also gives a parse error, but does not give the error if the username already exists.
Notice: Undefined variable: username in C:\Program Files\EasyPHP5.3.0\www\register_hirer2.php on line 6
Thanks for registration
line 6 is:
$checkusername=mysql_query("SELECT * FROM employer WHERE eusername='$username'");
Well, your $username is undefined indeed.
Most probably you want to use $_POST['username'].
And of course this obligatory XKCD comic:
If the "data source" is an html form (supposedly using method="post") you have to use $_POST['username'] when register_globals is set to off (which is the default since ...ages). see http://docs.php.net/security.globals
Also have a read of http://php.net/manual/en/security.database.sql-injection.php
<?php
include"include/connection.php";
$query = "SELECT
*
FROM
employer
WHERE
eusername='". mysql_real_escape_string($username). "'
";
$checkusername=mysql_query($query) or die(mysql_error());
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = "INSERT INTO employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry) values (". same mysql_real_escape_string() thing here for each parameter .")";
$result = mysql_query($query) or die (mysql_error());
echo " Thanks for registration";
}
?>
You can also use prepared statements. This way you don't need/can't forget using an escaping function.
edit and btw: you don't need the SELECT before the INSERT in order to make the username unique. Actually it will make things even harder since now you have to deal with race conditions. You'd have to lock the table between those two queries.
If you add an unique index for the username in your table MySQL will not allow the insertion of a doublet but instead return a specific error code which your script can fetch and handle without the need of dealing with race conditions.
define('ER_DUP_ENTRY', 1062);
$mysql = mysql_connect('..', '..', '..');
mysql_select_db('..', $mysql) or die(mysql_error($mysql));
$fields = array(
'efname'=>'first_name',
'elname'=>'last_name',
'egender'=>'gender',
'eemail'=>'email',
'eusername'=>'username',
'epwd'=>'password',
'eadd'=>'address',
'ephone'=>'phone',
'ecity'=>'city',
'ecountry'=>'country'
);
$sqlparams = array();
foreach($fields as $sql=>$form) {
if ( !isset($_POST[$form]) ) {
die('missing post parameter '. $form);
}
$sqlparams[$sql] = "'".mysql_real_escape_string($_POST[$form], $mysql)."'";
}
$query = '
INSERT INTO
employer
'. join(', ', array_keys($sqlparams)) .'
VALUES
('.join(',', $sqlparams).')
';
// table:employer has been defined with "unique key idxName (eusername)"
$result = mysql_query($query, $mysql);
if ( false!==$result ) {
echo " Thanks for registration";
}
else if ( ER_DUP_ENTRY===mysql_errno($mysql) ) {
echo 'username already exists';
}
else {
echo 'an error occurred';
}
That is because you do not define $username anywhere. It looks as though you want to use $_POST['username']
mysql_query("SELECT * FROM employer WHERE eusername='{$_POST['username']}'");
Also, your code is vulnerable to a SQL Injection
You never define $usernameanywhere, so it gives that error because you are trying to use a variable that it doesn't have a value for.
This is most likely because you've not defined the '$username' variable. I presume that you're relying on this being populated from the incoming GET/POST data (most likely via the depreciated register_globals) which is bad practice.
As such, you'll need to either populate $username via $_POST or $_GET.
More importantly, you should update the insert query to escape the incoming 'untrusted' data using mysql_real_escape_string (e.g.: mysql_real_escape_string($_POST['username']), etc.)
As #Yacoby said your code is vulnerable to an SQL Injection to prevent it you can use mysqli or PDO , if you would like to use mysqli use the following code:
<?php
include"include/connection.php";
$query = "SELECT
*
FROM
employer
WHERE
eusername='". mysql_real_escape_string($username). "'
";
$checkusername=mysql_query($query) or die(mysql_error());
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = $conn->prepare("INSERT INTO employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry)) values ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)"; // preparing the insert
$query->bind_param("ssssssssss" , $variable1 , $variable2 , $variable3 , $variable4 , $variable5 , $variable6 , $variable7 , $variable8 , $variable9 , $variable10); // binding parameters
$query->execute(); // sending the parameter values
$query->close(); // closing the query
$conn->close(); // closing the connection
if ($query) { // checking if the query has been executed with no errors
echo " Thanks for registration";
}
}
?>
BE SURE TO CHANGE THE $conn AND variables to whatever you want!