I have a SQL string that updates my DB
I have left out most of the insert code as this is not where I need help. I run the string updating numerous tables but I need to stop the string once an error is detected.
I have in the first SQL string a Unique coulomb that i do not want duplicates of but in the other tables duplicates of the same coulomb doesn't matter. As this is history tables keeping history of the objects
This section is the sql section thereafter I start the sql 1
if ($conn->query($sql) === TRUE) {
echo "Client and Unit has been loaded ";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
echo("Error description: " . mysqli_error($con));
echo "Error in uploading information";
}
$sql1 = "INSERT INTO unit_history SET
The error is correct and the table is not populated but it goes on to the next sql1 string I need it to stop once the error is found.
Duplicate entry '111' for key 'unitnr'
Notice: Undefined variable: con in client_rep.php on line 120
Is there a way I can Kill the script once error is noted on duplicate entry?
If you want to stop execution only then use die(); or exit();
Or
You can return from there:
if ($conn->query($sql) === TRUE) {
echo "Client and Unit has been loaded ";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
echo("Error description: " . mysqli_error($con));
echo "Error in uploading information";
die; // Use die or exit here.
}
Related
I have basic PHP/MySQL experience, having taken an introductory class. My knowledge is literally limited to the following PHP codes:
if(!($stmt = $mysqli->prepare...)
if(!($stmt->bind_param...)
if(!$stmt->execute...)
I'm currently trying to write a program that allows a user to enter a new password, and checks the password against existing passwords in the database.
Here is what I have:
<?php
foreach($Password){
$dupesql = "SELECT PasswordID Passwords WHERE (Password = '$Password')";
$duperaw = mysql_query($dupesql);
if(mysql_num_rows($duperaw){
echo nl2br("$Password has already been used \n");
}
else{
echo "Password added \n";
}
}
?>
I got the code from this post: Check for duplicates before inserting
I'm not sure if the code itself has problems or if I need to add anything else to my PHP code to get this working, as it's currently producing an "Error 500".
MySQL extension is deprecated and probably you have PHP 7.0 from where it is removed. Rewrite your code to MySQLi or PDO. Check this question on how to convert to MySQLi: How could I change this mysql to mysqli?
Also, your code just doesn't add a password (never). Probably you expect to add it before the "Password Added" message, but be aware: the solution you want to use is not ideal, because there is a risk of race condition between checking the password for existence and adding it. This means that it is possible to add a password twice.
To solve this problem, you might want to use transactions. More details are covered in this question: PHP + MySQL transactions examples
I decided to go an entirely different route, which is to set the Password column as unique.
Then I did a simple INSERT that would prompt an error if the user attempts to add a duplicate:
<?php
if(!($stmt = $mysqli->prepare("INSERT INTO Heroes(HeroName, FirstName, LastName, Age, HomeCountry, RoleID) VALUES (?,?,?,?,?,?)"))){
echo "Prepare failed: " . $stmt->errno . " " . $stmt->error;
}
if(!($stmt->bind_param("sssisi",$_POST['HeroName'],$_POST['FirstName'],$_POST['LastName'],$_POST['Age'],$_POST['HomeCountry'],$_POST['RoleID']))){
echo "Bind failed: " . $stmt->errno . " " . $stmt->error;
}
if(!$stmt->execute()){
echo "Execute failed: " . $stmt->errno . " " . $stmt->error;
} else {
echo "Added " . $stmt->affected_rows . " row to Heroes.";
}
?>
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 been reading about the Commands out of sync; you can't run this command now problem for some time now, and see that you cannot have any unread results left, which makes sense to me. However, in the following case, I don't see which results I am missing to free. I have left out the irrelevant things from my PHP and SQL code below.
# Set local variables
$sql = "
SET #STARTDATE = '2014-09-01';
SET #RANK = 0;
";
if (mysqli_multi_query($conn, $sql)) {
# Success: do nothing else
} else {
# Failure: output the error message
echo "Error: " . $sql . "<br>" . $conn->error;
}
# Fetch and store the results
$sql = "
SELECT * FROM MyTable
";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
The second query (the if (!$result) block) returns the infamous Commands out of sync error. If I comment out the first part, the second query runs no problem. If I change the first query into only one SET statement instead of two, the second query runs no problem. Therefore, it seems that I have to clear the 'success-flag' of every individual SQL statement from the first part. Is this correct? If so, how shall this be done?
EDIT: indeed it seems you have to flush all results in between. Adding the following line between part 1 and part 2 solves the problem.
while (mysqli_next_result($conn)) {;} // Flush multi_queries
I found this solution in a user comment on the PHP manual: http://nl3.php.net/manual/en/mysqli.multi-query.php
Quite simply, your first query
SET #STARTDATE = '2014-09-01';
SET #RANK = 0;
Will generate 2 result sets and until they have been processed, even though the result will be just a status you cannot continue.
So you need to do something like this :-
if (mysqli_multi_query($conn, $sql)) {
do {
/* unload result set */
if ($result = $mysqli->store_result()) {
// Check status
$result->free();
}
} while ($mysqli->next_result());
} else {
# Failure: output the error message
echo "Error: " . $sql . "<br>" . $conn->error;
}
Of course you should probably check for errors in that loop
I want to store one's friends of facebook into a table. The result of below code shows only a single record is inserted. It wasn't the problem of my loop because I echo the name, it all appeared.
foreach($user_friends['data'] as $friend){
//echo $friend['name'] . "</br>";
$userImg = "https://graph.facebook.com/".$friend['id']."/picture?width=200&height=200";
$friendsName = $friend['name'];
$stmt3 = $db->prepare("INSERT INTO allfriend(`uId`,`name`,`img`,`friendOf`) VALUES (?,?,?,?)");
$stmt3->bind_param('ssss', $user_fbid, $friendsName, $userImg, $user_fbid);
$stmt3->execute();
}
You're misusing the prepare / bind feature slightly. You only need to prepare once, but you do need to reset the statement after each use.
Also, you should check for failure of your statements. If you do that you may find out why things might work differently from what you expect.
Is it possible your column friend.uID is in fact a primary key? The code you've shown tries to insert the same value into multiple rows. That could be your problem.
Try this:
$stmt3 = $db->prepare
("INSERT INTO allfriend(`uId`,`name`,`img`,`friendOf`) VALUES (?,?,?,?)")
|| die "prepare failed: ". $db->error;
foreach($user_friends['data'] as $friend) {
//echo $friend['name'] . "</br>";
$userImg = "https://graph.facebook.com/".$friend['id']."/picture?width=200&height=200";
$friendsName = $friend['name'];
$stmt3->bind_param('ssss', $user_fbid, $friendsName, $userImg, $user_fbid)
|| die "bind_param failed " . $db->error;
$stmt3->execute()
|| die "execute failed " . $db->error;
$stmt3->reset()
|| die "reset failed " . $db->error;
}
I have two very long list:
$countryCode
And
$countryName
To insert these list i have created the following loop:
$i = 0;
$con=mysqli_connect("localhost","root","root","system_bloglic_com_test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
foreach($countryCode as $cCode){
mysqli_query($con,"INSERT INTO Contries (contries_id, contries_name, contries_code)
VALUES(NULL,$cCode,$countryName[$i])");
$i++;
}
When i run this i get no erros but no rows have been inserted into database how come?
did you check mysqli_error(); it will help you to find exactly the error.
It returns FALSE if an error occurred. In that case mysqli_error() gives you more information about the error.
$result = mysqli_query($con,"INSERT INTO Contries (contries_id, contries_name, contries_code)
VALUES(NULL,$cCode,$countryName[$i])");
if ( false===$result ) {
printf("error: %s\n", mysqli_error($con));
}
else {
echo 'done.';
}
Your string values should always be enclosed within quotes
mysqli_query($con,"INSERT INTO Contries (contries_id, contries_name, contries_code)
VALUES(NULL,'{$cCode}','{$countryName[$i]}')");
and also you should use error handling as instructed by others using die() method
You should change
mysqli_query(...);
into
mysqli_query(...) or die("error in query: " . mysqli_error($con));
To echo out any errors. Otherwise errors are silently ignored.
You need to check for errors in your code.
if(!mysqli_query($con,"INSERT INTO Contries (contries_id, contries_name, contries_code)
VALUES(NULL,'$cCode','$countryName[$i]')")){
echo mysqli_error($con);
}