We have a table vehicle and a simple php form. Before inserting data I do check if the vehicle registration number exist but some client pc could enter duplicate entries. Below is the code snippet. What else could be causing this ?
$vehicleRegistrationNumber=$_POST['vehicleRegistrationNumber'];
$selectQuery1 ="Select vehicleRegistrationNumber From Vehicle Where vehicleRegistrationNumber='".$vehicleRegistrationNumber."'";
$result1 = mysqli_query($link,$selectQuery1);
$row1 = mysqli_fetch_array($result1, MYSQL_ASSOC);
$n1 = mysqli_num_rows($result1);
if($n1 > 0) {
$status="<span class=\"statusFailed\">: Vehicle ".$vehicleRegistrationNumber." Already Exist.</span>";
}
else {
//insert codes
}
First of all your code is vulnerable to SQL injection. This check can be bypassed by submitting something like XYZ0001' AND 1='0 or even more malicious values. To prevent this, use prepared statements and param binding instead of string concatenation.
Other possibility is simply user mistake, for example trailing space ("XYZ001" != "XYZ0001 ") that is hard to spot on the first glance ad records in DB. Before checking its existence in DB you should check with PHP if submitted value includes only allowed chars and is free from common mistakes.
try this with group by
$selectQuery1 ="Select vehicleRegistrationNumber From Vehicle Where vehicleRegistrationNumber='".$vehicleRegistrationNumber."' GROUP BY vehicleRegistrationNumber";
The best way is to handle it on the SQL side. Just define the field as UNIQUE INDEX.
Now when trying to insert a duplicate index an error will be thrown and you can catch it like this:
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
Like this you can avoid the select query before every insert query. Just handle the error as you want.
Related
I'm wrapping up my website, but I've an issue with breaking
if statement inside foreach statement,
I want when a student try to pick a job that he/she already had chosen, the if() fail and break from the WHOLE foreach() loop, this is my code,the break inside the if() only break out the if(), not the whole foreach
please please help me.
thank you
foreach($_POST['JobId'] AS $i){
$sqlCheckingBeofrAdding ="SELECT * FROM JobsLists WHERE JobId = '".$i."' AND SSU = '".$SSU."' ";
$rs = mysqli_query($dbCIE ,$sqlCheckingBeofrAdding);
$row1 = mysqli_fetch_assoc($rs);
if($row1 > 0){
echo "You Already Have this Job In your List";
break;
}
//insert into junction table..
$sqlUpdate = "UPDATE Jobs SET NoStudent=NoStudent-1 WHERE JobId = '" . $i . "'";
$resultUpdate = mysqli_query($dbCIE,$sqlUpdate) or die(mysqli_error($dbCIE));
$sqlInsert ="INSERT INTO JobsLists(`JobID` , `SSU`) VALUES(".$i.",'".$SSU."' )";
$MyQuery= mysqli_query($dbCIE, $sqlInsert) or die(mysqli_error($dbCIE));
}
If your query is only return the single student record than you can use return and this will not execute the further code inside the loop.
If your query returns multiple students record than you can use continue
For point 1:
if($row1 > 0){
echo "You Already Have this Job In your List";
return;
}
For point 2:
if(condition){
echo "You Already Have this Job In your List";
continue;
}
You can use break; OR return; (if this is a function.) Let me know if you need code.
The break statement in PHP accepts a numeric argument.
Try changing your break; to break 2; or use a return;
The php manual says:
break ends execution of the current for, foreach, while, do-while or switch structure.
I do not think your break is breaking out of the if. I suspect a different problem with your code.
Break does not break ifs. This is how the language works.
Ensure you have a debug line before and after the if instead of simple MySQL operations. This seems to be a problem with the code.
For example, add some echo lines before and after the if and you'll have a better idea on what's going on.
The code itself seems to have a lot of problems:
1-You don't need to retrieve all fields (select *) in order to see if at least one entry exists. This is a misuse of the database layer.
2-In case you need to check if one entry exists, add LIMIT 1 to your SQL query. This will avoid MySQL to scan the entire table in case the query is not using any unique key, which is very likely.
3-mysqli_fetch_assoc returns an associative array, but then you compare the array against "> 0". Would you confirm that Array() > 0 ?
4-You seem to be using camelCased variables, but then all of the sudden you have $MyQuery, when it should be $myQuery to match the convention you're using.
5-You're storing the result of the query, in a variable named $MyQuery. This is a bad practice, as the variable name should describe what it contains. Therefore you'll want to call it $myResult or $rs as you did in the first query.
6-None of the variables used in the SQL statements are escaped.
Double check your code using the rubber duck technique and I'm sure you'll find the issue is not related to the if/break; but to something else. Not to offend, but this code seems very immature.
I have an advanced search with 4 fields, only one name_first is mandatory
There are many variations of search as the other fields are not mandatory so I need a select statement that only selects the fields that have been populated, but there are so many variations
I have tried the below script but it does not show the correct information (I think it is completely wrong?!)
$name_first=$_GET["name_first"];
$status=$_GET["status"];
$type=$_GET["type"];
$manstaff=$_GET["manstaff"];
$result401=mysql_query("SELECT * FROM `hr_employees` WHERE
(name_first LIKE '$name_first%')
AND
(status LIKE '$status%')
AND
(manages_staff LIKE '$manstaff%');")or die('Error' . mysql_error());
Any ideas what the script above should be? Basically if the field isnt completed it doesnt need to search for it?
First define your SQL with only the required criteria
$sql = "SELECT * FROM `hr_employees` WHERE (name_first LIKE '$name_first%')";
then add the optional criteria... optionally
if ($status) {
$sql .= " AND (status LIKE '$status%') ";
}
if ($manstaff) {
$sql .= " AND (manages_staff LIKE '$manstaff%')";
}
$result401=mysql_query($sql) or die ('Error' . mysql_error());
Incidentally, please consider updating your code to avoid using the deprecated mysql functions, and keep in mind that concatenating variables into your SQL like this makes your code vulnerable to SQL injection.
$sqlorg = mysql_query("SELECT * FROM `organization`");
while($orgrows = mysql_fetch_array($sqlorg)) {
//$dborgid = $orgrows['org_id'];
$dborgnme = $orgrows['org_name'];
}
if ($dborgnme == $orgexist) {
echo "<script type='text/javascript'>
alert('Organization Name Already Used by other Organization');
history.back();
</script>";
} else {
$orginsrt = mysql_query("INSERT INTO `organization`(`org_id`,`org_name`,`org_desc`,`category`,`vision`,`mission`,`col_id`,`image`) VALUES ('$orgid','$orgexist','$orgdesc','$orgcat','$orgvis','$orgmis','$getcol','$image')");
echo "<script type='text/javascript'>
alert('Proceed to next Step');</script>";
//require ('orgsignup.php');
header ('Location:orgsignup2.php');
//echo "Not in the Record";
}
There are multiple issues with this question, and as such can't easily be answered - I'm writing this "answer" as a quick guide to Kio Rii and to get more information:
1) Don't use MySQL, use MySQLi for procedural DB/PHP interactions.
2)
while($orgrows = mysql_fetch_array($sqlorg)) {
//$dborgid = $orgrows['org_id'];
$dborgnme = $orgrows['org_name'];
}
The value $dborgnme will only ever hold the final value from all the rows fetched from the database. Consider reformatting the While statement to wrap outside the following if(){} ... else{}
3) Add some context and information to your question - what are you checking for? Where do values such as $orgexist come from? What events do you want to occur if a data exists or what happens if a data doesn't exist?
4) If you're only checking the name, you can better do it with a better SELECT statement as the current select is grabbing all the MySQL rows, so try
take :
$sqlorg = mysql_query("SELECT * FROM `organization`");
and turn it into
$sqlorg = mysql_query("SELECT * FROM `organization` WHERE org_name LIKE '%".$orgexist."%' ");
which will only return you rows if the names are very similar. You can then use the output of this (count of rows returned) to carry on the script logic.
5) Yes, my solution in part 4 is quick and dirty, and PDO or MySQLi prepared statements are much, MUCH better and more secure than old MySQL and variable injection into the SQL statement.
Additional debugging:
you would probably find this very useful:
$orginsrt = mysql_query("INSERT INTO `organization`(`org_id`,`org_name`,`org_desc`,`category`,`vision`,`mission`,`col_id`,`image`) VALUES ('$orgid','$orgexist','$orgdesc','$orgcat','$orgvis','$orgmis','$getcol','$image')") or die("insert fail: ".mysql_error());
This will tell you why an insert failed, if it did fail.
I generate the below query in two ways, but use the same function to insert into the database:
INSERT INTO person VALUES('','john', 'smith','new york', 'NY', '123456');
The below method results in CORRECT inserts, with no extra blank row in the sql database
foreach($_POST as $item)
$statement .= "'$item', ";
$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";
The code below should be generating an identical query to the one above (they echo identically), but when I use it, an extra blank row (with an id) is inserted into the database, after the correct row with data. so two rows are inserted each time.
$mytest = "INSERT INTO person VALUES('','$_POST[name]', '$_POST[address]','$_POST[city]', '$_POST[state]', '$_POST[zip]');";
Because I need to run validations on posted items from the form, and need to do some manipulations before storing it into the database, I need to be able to use the second query method.
I can't understand how the two could be different. I'm using the exact same functions to connect and insert into the database, so the problem can't be there.
below is my insert function for reference:
function do_insertion($query) {
$db = get_db_connection();
if(!($result = mysqli_query($db, $query))) {
#die('SQL ERROR: '. mysqli_error($db));
write_error_page(mysqli_error($db));
} #end if
}
Thank you for any insite/help on this.
Using your $_POST directly in your query is opening you up to a lot of bad things, it's just bad practice. You should at least do something to clean your data before going to your database.
The $_POST variable often times can contain additional values depending on the browser, form submit. Have you tried doing a null/empty check in your foreach?
!~ Pseudo Code DO NOT USE IN PRODUCTION ~!
foreach($_POST as $item)
{
if(isset($item) && $item != "")
{
$statement .= "'$item', ";
$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";
}
}
Please read #tadman's comment about using bind_param and protecting yourself against SQL injection. For the sake of answering your question it's likely your $_POST contains empty data that is being put into your query and resulting in the added row.
as #yycdev stated, you are in risk of SQL injection. Start by reading this and rewrite your code by proper use of protecting your database. SQL injection is not fun and will produce many bugs.
HI everyone i tried for 3 days and i'm not able to solve this problem. This is the codes and i have went through it again and again but i found no errors. I tried at a blank page and it worked but when i put it inside the calendar it has the syntax error. Thanks a million for whoever who can assist.
/** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/
$testquery = mysql_query("SELECT orgid FROM sub WHERE userid='$userid'");
while($row4 = mysql_fetch_assoc($testquery))
{
$org = $row4['orgid'];
echo "$org<br>";
$test2 = mysql_query("SELECT nameevent FROM event WHERE `userid`=$org AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'") or die(mysql_error());
while($row5=mysql_fetch_assoc($test2))
{
$namethis = $row5['nameevent'];
$calendar.=$namethis;
}
}
First question: what calendar are you talking about?
And here are my 2-cents: does the EXTRACT function returns a string or a number?
Are the "backticks" (userid) really in your query? Try to strip them off.
Bye!
It's a guess, given that you haven't provided the error message you're seeing, but I imagine that userid is a text field and so the value $org in the WHERE clause needs quotes around it. I say this as the commented out testquery has quotes around the userid field, although I appreciate that it works on a different table. Anyway try this:
SELECT nameevent FROM event WHERE userid='$org' AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'
In such cases it's often useful to echo the sql statement and run it using a database client
First step in debugging problems like this, is to print out the acutal statement you are running. I don't know PHP, but can you first build up the SQL and then print it before calling mysql_query()?
EXTRACT() returns a number not a character value, so you don't need the single quotes when comparing EXTRACT(YEAR FROM startdate) = 2010, but I doubt that this would throw an error (unlike in other databases) but there might be a system configuration that does this.
Another thing that looks a bit strange by just looking at the names of your columns/variables: you are first retrieving a column orgid from the user table. But you compare that to the userid column in the event table. Shouldn't you also be using $userid to retrieve from the event table?
Also in the first query you are putting single quotes around $userid while you are not doing that for the userid column in the event table. Is userid a number or a string? Numbers don't need single quotes.
Any of the mysql_* functions can fail. You have to test all the return values and if one of them indicates an error (usually when the function returns false) your script has to handle it somehow.
E.g. in your query
mysql_query("SELECT orgid FROM sub WHERE userid='$userid'")
you mix a parameter into the sql statement. Have you assured that this value (the value of $userid) is secure for this purpose? see http://en.wikipedia.org/wiki/SQL_injection
You can use a JOIN statement two combine your two sql queryies into one.
see also:
http://docs.php.net/mysql_error
http://docs.php.net/mysql_real_escape_string
http://www.w3schools.com/sql/sql_join.asp
Example of rudimentary error handling:
$mysql = mysql_connect('Fill in', 'the correct', 'values here');
if ( !$mysql ) { // some went wrong, error hanlding here
echo 'connection failed. ', mysql_error();
return;
}
$result = mysql_select_db('dbname', $mysql);
if (!$result ) {
echo 'select_db failed. ', mysql_error($mysql);
return;
}
// Is it safe to use $userid as a parmeter within an sql statement?
// see http://docs.php.net/mysql_real_escape_string
$sql = "SELECT orgid FROM sub WHERE userid='$userid'";
$testquery = mysql_query($sql, $mysql);
if (!$testquery ) {
echo 'query failed. ', mysql_error($mysql), "<br />\n";
echo 'query=<pre>', $sql, '</pre>';
return;
}