Does anybody know why the following PHP code keeps throwing errors: I have been unable to log any proper error other than the if statement $result not going through and giving me the Echo 'Error' statement. Is there something wrong with my insertion?
$new_tbl_name = 'Password_Reset';
$sql = "INSERT INTO $new_tbl_name (Email, Key) VALUES ('$email','$resetHash')";
$result = mysql_query($sql);
if ($result) {
}
else {
echo 'Error';
}
key is a reserved word, you'll have to escape it:
INSERT INTO $new_tbl_name (Email, `Key`) VALUES
^ ^
As a general suggestion, simply saying "error" is utterly useless for debugging purposes. Have mysql TELL you what's wrong:
if (!$result) {
die(mysql_error());
}
so you have a clue as to what's wrong, instead of just poking around in the dark.
Related
I looked at a dozen questions and nothing helps. Some give contradictory advice.
I have a simple INSERT INTO query with PHP mysqli. The query and the connection are both ok, and the query actually executes on an older version of xampp. But when I switched to a newer one - nothing! No errors, but, no new data, either.
<?php
$connection = mysqli_connect("localhost", "standard_user", "standard", "liquidity");
if (!$connection) {
die("Error: ".mysqli_connect_errno());
}
$table = "clan";
$username = "someusername";
$ime = "My name";
$query = "INSERT INTO ";
$query.=$table;
$query.=" (username, ime) ";
$query.="VALUES ('".$username."','".$ime."');";
//$query = "INSERT INTO clan (username, ime) VALUES ('someusername', 'My name')";
mysqli_query($connection, $query);
if ($query) {
echo("Success: ".$ime);
} else {
echo("There has been an error. Try again.");
}
mysqli_close($connection);
?>
This is the query it echoed when I tried it: INSERT INTO clan (username, ime) VALUES ('someusername','My name');
Since every time I reload it prints "Success: My name", I guess it somehow executes. But, no data is saved. I can't figure it out. Any help?
[SOLUTION] The clan table had a foreign key (username) to another table which had no entries, so there was nothing wrong with the query, but a silly overlook actually. Thanks to Deivison Francisco's answer, it was easy to determine the cause of the problem by simply reading an error.
Please use the return value of mysqli_query() to determine the result.
Also think about using prepared statements to mitigate SQL Injections.
$result = mysqli_query($connection, $query);
if ($result) {
echo("Success: ".$ime);
} else {
echo("There has been an error. Try again. Error message: ".mysqli_error($connection));
}
Alter for:
$query = "INSERT INTO clan (username, ime) VALUES ('someusername', 'My name')";
$return = mysqli_query($connection, $query);
if ($return) {
echo("Success: ".$ime);
} else {
echo("There has been an error. Try again.");
}
mysqli_close($connection);
I'm currently working on creating a login system, one part of which is of course registration. It's been going smoothly up until this point, where I'm getting an error.
I've researched this as thoroughly as I can, but I can't find the solution as it is giving me an incorrect line number.
The error I'm getting is:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
My SQL query is
$token = (round(microtime(true) * 1000));
$query = mysql_query("INSERT INTO "
. "`users` "
. "(name, password, email, token) "
. "VALUES "
. "('$_POST[user]'"
. ",'".hash('sha512',$_POST['pass'])."'"
. ",'$_POST[email]'"
. ",'$token')") or die(mysql_error());
if (mysql_query($query) === TRUE) {
//echo "Sucsessfuly registered! Check your email for a confirmation link.";
} else {
echo "Error: " . mysql_error();
}
(this is not the first line of the file, it's the 22d)
When the code runs, even though it throws the error it still is inserting the values into the table correctly.
Also when I run the same query in phpmyadmin, it runs just fine with no errors.
I've been trying to solve this error for the last 3 hours so any help would be appreciated ;)
You're calling mysql_query twice: first with the SQL, and then you're using the result of the query as if it were a query. The error you're getting is because $query is true, which gets turned into 1 when treated as a string.
Either you should just set $query to the SQL string:
$query = "INSERT INTO ...";
if (mysql_query($query)) {
...
} else {
...
}
or you should just check the value of $query:
$query = mysql_query(...);
if ($query) {
...
} else {
...
}
I have the following stored procedure that executes correctly when I run my program:
$insertIntoEmployeesProcedure = "
CREATE PROCEDURE EmployeeInsert(name VARCHAR(50),password VARCHAR(50), email VARCHAR(50))
BEGIN
INSERT INTO employees(name,password,email) values(name,password,email);
END";
$returnInsertIntoEmpProc = $conn->query($insertIntoEmployeesProcedure);
if(! $returnInsertIntoEmpProc )
{
die('Could not create insert procedure: ' . $conn->error);
}
else
{
echo "Insert Procedure created successfully<br/>";
}
I then call this procedure in another class when needed:
$insertEmp = mysqli_query($conn, "Call EmployeeInsert('$username','$password', '$email')");
$executeInsertEmp = $conn->query($insertEmp);
if(!$executeInsertEmp )
{
die('Employees not added: ' . $conn->error);
}
else
{
echo "Employees added<br/>";
}
The problem is, when I execute this code, I get the following error
Employees not added: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
The main issue I have with this is that even though it returns this error, the record is still added into the database and everything seems to be working fine. I guess I'm more curious as to why I'm getting this error as clearly I'm overlooking something.
Ah I see what I've done, I seem to have added an additional query which was unnecessary, the line:
$executeInsertEmp = $conn->query($insertEmp);
can be ommited, the check in the if statement is then done on the variable which holds the stored procedure. The following code works:
$insertEmp = mysqli_query($conn, "Call EmployeeInsert('$username','$password', '$email')");
if(!$insertEmp )
{
die('Employees not added: ' . $conn->error);
}
else
{
echo "Employees added<br/>";
}
I have writen this pice of code that should insert into my Database some event data, but it does not insert a thing in the DB, can you tell me why?
try {
$pdo = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch( PDOException $excepiton ) {
echo "Connection error :" . $excepiton->getMessage();
}
try{
$sql = "INSERT INTO events_DB (event_id, event_end_time, event_location, event_name) VALUES (:event_id, :event_end_time, :event_location, :event_name) ON DUPLICATE KEY UPDATE event_id = :event_id, event_end_time = :event_end_time, event_location = :event_location, event_name = :event_name";
$stm = $db->prepare($sql);
$stm->execute(array(":event_id" => $event[id], ":event_end_time" => $event[end_time], ":event_location" => $event[location], ":event_name" => $event[name]));
}
catch ( PDOException $exception )
{
// decomentati sa vedeti erorile
echo "PDO error :" . $exception->getMessage();
}
Thanks
The code you've posted is different than the code you're running as the posted code would result in a syntax error at parse time and never actually run.
However, what's happening is the SQL being sent to the prepare method is not valid in some way so that the result returned and stored in $stm is a boolean (false) rather than a valid statement object. Double check your SQL (you could try running it in another application such as phpMyAdmin or via the mysql command-line program) to ensure its validity. You could also add some error handling to find the cause with:
$stm = $db->prepare($sql);
if (!$stm) {
die($db->errorInfo());
}
Edit: You've modified the posted source code which now shows use of exception handling. However, you've commented out the line that echos the exception message. This information will be useful in telling you what's causing the error condition. Uncomment to see the message (which will most likely inform you that the SQL is invalid and which part of it caused the error).
Try to remove the <br> tag from the first line and a " is messing
$sql = "INSERT INTO events_DB (event_id, event_end_time, event_location, event_name);"
I am using a simple PHP script for the activation part of one of my applications. The applications posts one variable to the page (http://validate.zbrowntechnology.info/WebLock.php?method=validate). The variable is the serial number, posted as 'Serial'. Each time I post to this page, it returns Invalid. Here is the code:
<?php
$serial = $_POST['Serial'];
$method = $_GET['method'];
$con = mysql_connect("HOSTHERE", "USERHERE", "PASSHERE");
if(!$con) {
die('Unable to connect to MySQL: ' . mysql_error());
}
if($method == "validate") {
mysql_select_db("zach_WebLock", $con);
$query = "SELECT Key, Status FROM Validation WHERE Key='".mysql_real_escape_string($serial)."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
echo "Valid";
} else {
echo "Invalid";
}
} else {
echo "Unkown Method";
}
?>
Here Is The Error From PHP,
PHP Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given
Right after the query use mysql_error() to see what happened. And Key is a bad choice for a column name because it's a reserved word in SQL. You can enclose it in `` to tell MySQL it's an identifier. Do some more debugging like this:
...
if (!mysql_select_db("zach_WebLock", $con)) die('mysql_select_db failed');
$query = "SELECT `Key`, Status FROM Validation WHERE `Key`='".mysql_real_escape_string($serial)."'";
print "query=$query<br>\n";
$result = mysql_query($query, $con);
print "error=" . mysql_error($con);
...
You're missing a closing parenthesis on this line:
if(mysql_num_rows($result) > 0 {
Is that missing in your code or just your question?
You may also want to add
if (!$result) {
print mysql_error();
}
after your query
Try Like This
$query = "SELECT Key, Status FROM Validation WHERE Key='".$serial."'";
What happens if at the last line you add this?
else echo 'Unknown method';
What may be happening is that $_POST and $_GET are not getting populated, this is a setting in php.ini, if I remember correctly (search for "superglobals" in the php docs).
edit: also, you have a very bad security risk there, google "sql injection". Basically the problem is that you could get any SQL directly into your database, and if the php user has enough permissions it could mean that anyone can, for example, delete all the data from your Validation table. You should at least do something like this:
$query = "SELECT Key, Status FROM Validation WHERE Key='".addslashes($serial)."'";
It could be a typo but you are missing a closing parenthesis here:
if(mysql_num_rows($result) > 0 {
^
And you might have turned off you error reporting, in which case you get a blank page.
Try echoing $serial:
echo $serial;
And is it what you typed in form?