My query isn't executed while there aren't any errors - php

I have a login script in which I also execute a query to log when and from where people try to log in to my site. This little piece of code doesn't return any errors and the header works, but the query doesn't work for some reason. Does anyone have any idea what I'm doing wrong?
if($count==1){
$securityquery = "INSERT INTO security_kk (action,datetime,country,IP,Affected table,comment) VALUES (:action,:datetime,:country,:IP,:Affected_table,:comment)";
$q = $db->prepare($securityquery);
$q->execute(array(':action'=>"Login",
':datetime'=>$datetime,
':country'=>$country,
':IP'=>$_SERVER['REMOTE_ADDR'],
':Affected_table'=>"members",
':comment'=>"Authenticated as ".$myusername));
$_SESSION['username'] = $myusername;
$_SESSION['privileges'] = $row['privileges'];
$_SESSION['email'] = $row['email'];
header("location:index.php");
}
I'm a beginner at PDO, but since there are no errors. I don't know where to look.

datetime is a data type in MySQL. Wrap that column identifier in ticks. Also, column identifiers with spaces in their name must be wrapped in ticks.
$securityquery = "INSERT INTO security_kk (`action`,`datetime`,`country`,`IP`,`Affected table`,`comment`) VALUES (:action,:datetime,:country,:IP,:Affected_table,:meta)";

Your error (or possibly one of the errors) is the difference between
:meta // your query contains this
and
':comment'=>"Authenticated as ".$myusername;
Your array has no value for the placeholder named :meta
It doesn't hurt to check for errors using the error checking functions though, rather than having others try to figure out a simple typo.
while there aren't any errors
Because you aren't checking for them.

DateTime is a datatype of mysql.
check your Affected table column name - No space in column name
best way to use like below.
$securityquery = "INSERT INTO security_kk (action,[datetime],country,IP,Affected table,comment) VALUES (:action,:datetime,:country,:IP,:Affected_table,:meta)";

Related

Is this update statement missing something?

I have made a database where email id and corresponding name and password is stored. I have successfully obtained a form's data.. where the user enters updated name and password. But the problem is occuring with the query which is as follows
$db = mysqli_connect(all details)...
$name = $_POST['name'];
$password = $_POST['password']:
$email = $_POST['email'];
$query = "UPDATE mytable SET name='$name',password='$password' WHERE emailid='$email'";
$result = mysqli_query($db,$query);
Though I am getting all form values succesffuly and until and unless I put the 'where' clause.It works.But obviously updates all values. i want it to work with where..but so far unsuccessful :(
you need to put {} around the variables if its surrounded by quote ''
so your query should look like this
$query = "UPDATE mytable SET name='{$name}',password='{$password}' WHERE emailid='{$email}'";
$result = mysqli_query($db,$query);
EDIT : also before saving data to database make sure to filter and validate data
You need to make sure that emailid exists in mytable, you truly intended to filter by it and in your database scheme it has a type which supports the posted data. It seems that you are sending strings, like 'foo#bar.lorem' and your emailid is an int or something in the database scheme. Check it by running
desc mytable;
You need to put curly brackets around variables if you use apostrophe around them, but as a matter of style I like to close the string and attach the $variable with a . as this coding style is closer to me personally.
If everything fails, see what is generated, by echoing out the query string, try to run that directly, see what the error is and fix until...
... until it is fixed.
Also, you do not encrypt the password and your code is vulnerable to SQL injection too. Please, read about password encryption and SQL injection and then protect your project against these dangers.
You can write your statement as:
$query = "UPDATE mytable SET name='".$name."',password='".$password."' WHERE emailid='".$email."'";
using . as string concatenating operator

update the session field in database

I have a database. I had created a a table containing only one row in DB if it wasn't constructed before.
Why it has only 1 row is that I just use it to keep some info.
There is a field of TYPE NVARCHAR(100) which I want to use it to store session id,
and here comes the headache for me:
It seems that I can't even properly INSERT(I use phpmyadmin to check and it's blank) and UPDATE(syntax error...) it with a session id obtained from session_id(), which is returned as a string.
Here is the portion of my code relating to my action:
//uamip,uamport is in URL;I use $_GET[]
$_SESSION[uamport] = $_GET['uamport'];
$_SESSION[uamip] = $_GET['uamip'];
**$_SESSION[sid] = session_id();**
//construct
$sql="CREATE TABLE trans_vector(
`index` INT NOT NULL AUTO_INCREMENT,
`sid` NVARCHAR(100),
`uamip` CHAR(15),
`uamport` INT,
PRIMARY KEY (`index`)
)" ;
mysql_query($sql);
//insert(first time, so not constructed)
$sql="INSERT INTO trans_vector (sid,uamip,uamport) VALUES(
'$_SESSION[sid]',
'$_SESSION[myuamip]',
'$_SESSION[myuamport]'
)";
mysql_query($sql);
//update(from 2nd time and later, table exists, so I want to update the sid part)
$sql="UPDATE trans_vector SET sid="**.**$_SESSION[sid];
mysql_query($sql)
Now, when I use phpmyadmin to check the sid field after INSERT or UPDATE, It is blank;
But if I do this:
$vector=mysql_fetch_array(mysql_query("SELECT TABLES LIKE 'trans_vector'"));
and echo $vector[sid] ,then it's printed on webpage.
Another question is:
With the UPDATE statement above, I always get such error:
"Unknown column xxxxxx....(some session id returned, it seems it always translate it first and put it in the SQL statement, ** treating it as a column NAME** that's not what I want!)"
I tried some TYPE in CREATE statement, and also lots of syntax of the UPDATE statement(everything!!!) but it always give this error.
I am dealing trouble with ' and string representation containing a variable where the latter's value is actually what I want... and maybe the problem arise from type in CREATE and string representation in UPDATE statement?
Should CAST() statement helpful for me?
Wish you can help me deal with this...and probably list some real reference of such issue in PHP?
Thanks so much!!
$insert = "INSERT INTO trans_vector (`sid`, `uamip`, `uamport`) VALUES(
'".$_SESSION["sid"]."',
'".$_SESSION["myuamip"]."',
'".$_SESSION["myuamport"]."'
)";
this should solve at least some warnings, if not errors.
and for update...
$update = "UPDATE trans_vector SET `sid`='".$_SESSION["sid"]."';";
Notes about your code:
Array values have to be put into the string with operator '.' and cannot be inserted directly. Array indexes must be strings (note the ") or integers.
Column names should have `` around them. To insert a string with SQL, you have to put string into ''s, so the parser knows what is string and what column name. Without ''s parser is assuming you are stating a column.
and for mysql_escape_string, I assumed you handle that before storing data to sessions. Without those, you might can get unwanted SQL injections. And in case you did not do that, you can either do that (before you create queries):
foreach($_SESSION as $key => $value)
$_SESSION[$key] = mysql_escape_string($value);
or manually escape strings when you create a query.
As for the update statement, it’s clear that there are apostrophes missing. You always need apostrophes, when you want to insert a string value into the database. Moreover, you should use mysql_real_escape_string.
However, I think standard mysql is deprecated and has been removed in newer versions of PHP in favor of MySQLi and PDO. Thus you should switch to MySQLi or PDO soon.
You should also use apostrophes when referencing values within $_SESSION. Otherwise PHP will try to find a constanst with the name sid and later fallback to the string 'sid'. You will get into trouble if there once really is a constant called sid defined.
Here, the corrected update statement in mysql library:
$sql = "UPDATE trans_vector SET sid='" . mysql_real_escape_string($_SESSION['sid']) . "'";
Even better:
$sql = "UPDATE `trans_vector` SET `sid`='" . mysql_real_escape_string($_SESSION['sid']) . "'";
Using backticks makes clear for MySQL that this is a column name. Sometimes you will have column names that are called like reserved keywords in SQL. Then you will need apostrophes. A common example is a column called order for the sequence of entries.

What am I doing wrong with inserting?

I tried both
$query = "INSERT INTO reservation VALUES ('".$hour."','".$minute."','".$day."','".$month."','".$year."','".$name."','".$table."')";
$query = "INSERT INTO reservation VALUES ('$hour','$minute','$day','$month','$year','$name','$table')";
But none of them work, I get a blank page, and no errors in my error logs. I tried doing echo to all the variables and I got their values.
Here is the overall function:
function makeReservation($trtime,$hour,$minute,$day,$month,$year,$name,$table,&$db)
{
//$query = "INSERT INTO reservation VALUES ('".$hour."','".$minute."','".$day."','".$month."','".$year."','".$name."','".$table."')";
$query = "INSERT INTO reservation VALUES ('$hour','$minute','$day','$month','$year','$name','$table')";
$result = $db->query($query) or die(mysql_error());
}
I'll make a few suggestions. First, I'll assume that you actually know what you're doing when you say there is no error.
1) Make sure you work on the good database. You can do a SHOW TABLES query to see what tables it contains, or a SELECT * FROM reservation to see its content.
2) Right after you insert the row, do a SELECT * FROM reservation query and check if your row is there.
3) Make sure you call your function...
Then, as I said in comments, you should use the DATETIME type instead of using different columns for hours, minutes, etc. If you need to select a particular attribute, use the appropriate function (for example, SELECT HOUR(your_column))
The quotes around integers shouldn't make your query fails, but it's still better for clean code purposes to remove them if not necessary (and make sure you escape your data correctly, of course).
The php you posted looks fine.
If you're getting a blank page, it's likely that something is failing before the function calls. Maybe a parsing error?
If you're not seeing anything in the error logs, try changing your error logging settings in the php.ini.
display_errors = E_ALL
If you're on shared hosting, you can often override using .htaccess http://davidwalsh.name/php-values-htaccess

PHP Query to Insert Variables into MySQL not working

The query below is not inserting the variables into MySQL. I know that the function valid_email2 works because I put a non-email address into $inviteeemail and it redirected per the code below.
I know that I have the right MySQL connection string.
Any idea why nothing is being put into MySQL?
$invitorname = $_POST['invitorname'];
$inviteename = $_POST['inviteename'];
$inviteeemail = $_POST['inviteeemail'];
$uid = $_POST['uid'];
$subcheck = (isset($_POST['subcheckinvite'])) ? 1 : 0;
if ( ! valid_email2($inviteeemail))
{
session_write_close();
header("Location:http://www...com/.../file.php");
exit;
}
else
{
mysql_query("INSERT INTO invites VALUES (NULL, '$uid', '$inviteeemail', '$invitorname', '$inviteename', NULL, '$subcheckinvite', NULL)");
}
In your query you have $subcheckinvite but you're setting it as $subcheck at the beginning of your script. Maybe that's it.
Does the fields that you insert NULL for, can be null?
Check the return value of mysql_query. If it is false, then the query was not valid, and you can print mysql_error() to see the error message.
It's not unlikely that this stems from the fact that you're not escaping any of the user input. Aside from allowing someone to completely change your query by carefully crafting the form inputs, your query will simply fail if any of the fields contain a single quote mark.
Besides fixing your error, you should consider improving the quality of your code.
You use variables that don't exist ($checksubinvite)
You insert NULLs into columns rather than simply specifying which columns you do want to insert into
You do not validate all of the inputs
You have single quotes around what are likely numeric columns
You have enormous amounts of whitespace and inconsistent indentation
...etc.

Sql query problem

I have the below sql query that will update the the values from a form to the database
$sql=
"update leads set
category='$Category',
type='$stype',
contactName='$ContactName',
email='$Email',
phone='$Phone',
altphone='$PhoneAlt', mobile='$Mobile',
fax='$Fax',
address='$Address',
city='$City',
country='$Country',
DateEdited='$today',
printed='$Printed',
remarks='$Remarks'
where id='$id'";
$result=mysql_query($sql) or die(mysql_error());
echo '<h1>Successfully Updated!!.</h1>';
when i submit I dont get any errors and the success message is displayed but the database isnt updated . When i echo the $sql, all the values are set properly. and when i ech the $result i get the value 1.
can someone please tell me what am i doing wrong here??
Have you tried running the echo of $sql directly using some DB tool? It may provide a more informative error. Alternatively, if that works you may have an issue where the transaction isn't being committed. Often a connection is set to automatically commit transactions, but that may not be the case here. Try adding a commit.
And have you ever heard of SQL injection attacks?
If you have a query that is not giving the expected result or receiving an error, and the problem isn't obvious, you should generally take a look at the final query just before it's run. Try using this right before running the query:
echo $sql;
exit;
Viewing the actual query often makes it obvious what the problem is, especially when the query includes variables. If the problem still isn't obvious, you can paste the query as is into a query browser to get feedback directly from the database engine.
Interestingly, using parametrized queries, you won't get to see the parameter values, as the parameters get replaced by MySQL, not PHP, however, you'll still get to see the entire prepared query.
Also, you can see the number of affected rows from your UPDATE statement with the mysql_affected_rows() function. You could put this immediately after the query is run:
echo ("Updated records:", mysql_affected_rows());
Spaces are often forgotten when concatenating queries.
$sql = "SELECT * FROM ducks";
$sql .= "WHERE duck = 'goose'";
When echoing the above query, we see:
SELECT * FROM ducksWHERE duck <> 'goose'
I'm guessing that the WHERE clause in your UPDATE statement isn't matching an "id = '$id'".
Also, is the id column really a string? You've put single quotes around the value. MySQL will cast the string to an integer if needed, but if it's an integer, save the database some work and remove the single quotes.
try to echo $sql and run it directly in any database console, may be there is no record with id = $id
SQL Injection can be the answer. Not an intentional attack (at this moment), but if your parameters have some unexpected information like quotes or other reserved characters you can have strange results. So, try to run this SQL directly in your database administration utility.
Try doing this
"""update leads set
category="$Category",
type="$stype", etc...; """
See if that works

Categories