I have this script add new users to MySql andnow I have created secondary Mysql table for black-list name. so I want MySql check the black-list name before allow insert the data.
$all = implode(",",$_POST);
$all = explode(",",$all);
$insert = "INSERT INTO name VALUES (";
for ($x=0;$x<5;$x++)
{
$all[$x] = clean($all[$x]);
if ($all[$x] == "" || strlen($all[$x]) > 300)
die("<p>Please fill in the whole form." . $x);
$insert .= "'" . $all[$x] . "',";
}
$insert .= "'')";
$res = #mysql_query($insert) ;
I have change to
$insert = "INSERT INTO name VALUES (";
for ($x=0;$x<5;$x++) NOT IN (SELECT `blacklist` FROM `exclude`)
but didn't get what I am looking for. how I can fix that?
AS far as I am aware you are going to have to do a seperate select on your exclude table using whatever is the key to that table that is shared with the name table to check this user is not in the exclude list.
There is no INSERT syntax to allow a concept like INSERT unless something exists within another table.
As a matter of fact, you could (ab)use INSERT ... SELECT to do what you want:
-- insert one name:
INSERT INTO user SELECT "john" FROM DUAL
WHERE "john" NOT IN (SELECT name FROM blacklist);
INSERT INTO user SELECT "ringo" FROM DUAL
WHERE "ringo" NOT IN (SELECT name FROM blacklist);
-- insert several names
CREATE TEMPORARY TABLE candidate(name char(40));
INSERT INTO candidate VALUES
("paul"), ("ringo"), ("georges");
INSERT INTO user SELECT name FROM candidate
WHERE name NOT IN (SELECT name FROM blacklist);
See http://sqlfiddle.com/#!2/7ea68/1 for an example.
Related
I am trying to run an query using php into a database, I need to check if the customers address is already exists then do not insert, but if not exists then insert into table, I have based it around the following:
$query = "INSERT INTO address(id,address_type)
SELECT('1111','bill')FROM DUAL
WHERE NOT EXISTS
(SELECT * FROM address
WHERE id='1111' AND address_type='bill')";
$n = mysql_query($query, $connect ) or die(mysql_error());
This allows me to insert just the id but not the address_type.
I will have the same id for both bill & ship addresses making a unique field not possible.
I have about 8 fields to insert, what am I doing wrong?
$query = "INSERT INTO address(id,address_type)
SELECT('1111','bill')FROM DUAL
WHERE NOT EXISTS
(SELECT * FROM address
WHERE id='1111' )";
remove address_type='bill' and check
Im creating a website for booking activities. I have 3 centres. The customer is cant book the same activity twice neither in a different centre. Im using a table in mysql which i store the infos provided by the costumers. Is there any way to filter or to check in my php code if a customer has already booked the same activity more than one time and echo an error msg?
my table(and the info im asking) contains these columns:
ID(Primary)
FirstName
LastName
Email
ContactNumber
ClassName
Week
Intensity
CentreName
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
When you create the table add the unique attribute to the fields you want to prevent, something like this
CREATE TABLE Persons
(
P_Id INT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
)
If you already have created the table just edit it like this
ALTER TABLE Persons
ADD UNIQUE (P_Id)
Hope this helps you; If you do not have a unique id i believe this will suit you best on what you need; Note that this is not the full code; You need to add some to other information to fit in your question;
// Checks if the value already exist on the database
$query = SELECT EXISTS(SELECT column_name FROM table_name WHERE
condition LIMIT 1)
// If condition is not met it will proceed with save
if (mysql_num_rows(!$query) > 0) {
echo "Activity Booked";
} else { // If condition is met it will echo an error message
echo "Unable to booked activity"; }
You need to create a unique (composite) index on the column(s) that you wish to be unique. You can disregard your PK when making your unique index. In your case your sql would look something like:
Alter table yourtablename
add unique index idx_unq(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`);
Then do an INSERT IGNORE INTO instead of an INSERT INTO.
This post may also help you.
"INSERT INTO .. ON DUPLICATE KEY UPDATE" Only inserts new entries rather than replace?
In order to see if record already exist in table you must first "test" to see if that exact record exist in your table. This is to be done before the 'Insert IGNORE Into' in your logic. Using the variables your code would look something like this:
$testcount = "Select count(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`)
from yourtablename
where
(LastName = '$LastName' AND FirstName= '$FirstName' AND Email= '$EMAIL' AND ContactNumber= '$ContactNumber' AND ClassName= '$ClassName' AND Week= '$Week' Intensity = '$Intensity' AND CentreName = '$CentreName' )";
This query will give you back (assuming there are no duplicates already in the table) a 0 or a 1 and store it in your $testcount variable. This can then be used to either determine based on the value to insert the record into the table or print a message to end user informing them that it already exist.
I am not sure how you want to structure the php code but the psuedocode would look something like:
If $testcount = 1 then do your insert.
else if $testcount = 0 then echo your message.
I have to insert from table 1 into table 2 the values of username, name, lastname, roomnum and dormID.
I have to insert into table 2 the current date of today(it changes everyday), comments(the user wishes to enter- this is a textbox) and the attendance(present, absent, late)(these are the checkboxes).
When trying to click on the submit button the only thing that inserts into the database is the records that I am pulling from table1 into table 2.
When i try to incorporate to also insert the date, latecomments(textbox), and the attendance(checkboxes) it does not store any record.
This are the inserts:
$checkbox1 = $_POST['chk1'];
$latecomment=trim($_POST['latecomment']);
$d=strtotime("today");//todays date
$day=date("Y-m-d", $d);//date format
if($_POST["Submit"]=="Submit"){
for ($i=0; $i < sizeof ($checkbox1); $i++){
$query="Insert into dailyattendance (attendance) VALUES ('".$checkbox1[$i]."')";
mysql_query($query);
$daily=mysql_query("INSERT INTO dailyattendance(username, name, lastname, roomnum, dormID) SELECT user.username, user.name, user.lastname, user.roomnum, user.dormID FROM user WHERE user.role='Student'" );
$otherinfo=mysql_query("INSERT INTO daily attendance set date='".$day."', latecomment='".$latecomment."' WHERE dailyid=''");
}
}
There's a blank in your table name (in your given code):
INSERT INTO daily attendance
There's a WHERE clause in your INSERT statement and you are using UPDATE syntax with SET:
INSERT INTO daily attendance set date='".$day."', latecomment='".$latecomment."' WHERE dailyid=''");
Question: Is there a column named "attendance" in your table?
You should use only one INSERT statement if you want to add one row with all columns.
To clearify it a bit here is a code example you could start with. The SELECT on user is once before the loop because it seems to be same data all the time. You should add a function to escape strings before using them in the SQL statement to avoid errors when quotes are in it. Have a look at PHP or SQL error messages if something went wrong.
if($_POST["Submit"]=="Submit"){
$sql = "SELECT username, name, lastname, roomnum, dormID FROM user WHERE user.role='Student'";
$result = mysql_query($sql);
$student = mysql_fetch_assoc($result);
for($i=0; $i < sizeof ($checkbox1); $i++){
$sql = "INSERT INTO dailyattendance (username, name, lastname, roomnum, dormID, attendance, date, latecomment)";
$sql.= " VALUES ('".$student["username"]."', '".$student["name"]."', '".$student["lastname"]."', '".$student["roomnum"]."', '".$student["dormID"]."'";
$sql.= ", '".$checkbox1[$i]."', now(), '".$latecomment."')";
mysql_query($sql);
}
}
I've created a form that submits data into multiple tables. My fields are First Name, Last Name, Email, City/Region/Country and they're all inserted into 3 different tables (User, Email, Location).
The data goes into User and Email just fine, but I'm confused about what to do with Location.
I have 3 separate tables for Location (City, Region, Country). What I want to do is insert CityID, RegionID, and CountryID into the Location table. I have the City/Region/Country field set up so it autocompletes based on the city like this:
My Cities table has all the necessary info (CityID, RegionID, CountryID). How can I pull that data from the Cities table and insert it into my Location table?
Here's part of my code. I'm very very new to PHP and MySQL, so I apologize for the sloppiness of this. The first part of the code works, but the 2nd part doesn't (inserting data into the Location table).
//Insert static values into people table
$sql_user = sprintf("INSERT INTO User (FirstName, LastName,) VALUES ('%s','%s')",
mysql_real_escape_string($_POST['FirstName']),
mysql_real_escape_string($_POST['LastName']),
$result_user = $db->query($sql_user);
//get last inserted userid
$inserted_user_id = $db->last_insert_id();
//Insert values into location table
$sql_city = sprintf("INSERT INTO Location (UserID, CityID, RegionID, CountryID)
VALUES ('$inserted_user_id',(SELECT CityID, RegionID, CountryID, FROM Cities))");
$result_city = $db->query($sql_city);
I figure maybe I need to have "WHERE..." after FROM Cities, but I don't know what my condition would be.
That condition is up to you. If you're taking the value from the input box, it looks like you need to figure out the best way to read the location from the input field. Taking it as is you might want to first break the input into an array:
$location = explode(',',$_POST['location'])
$city = $location[0];
$region = $location[1];
$country = $location[2];
Now in your query -
"...WHERE city_name = '{$city}' AND region_name = '{$region_name}' AND country_name = '{$country}'";
*EDIT
To be more detailed, you need to setup a separate query to get the location by using SQL Joins. Your join combined with the WHERE constraints should return the city you are looking for. So here:
"SELECT Cities.CityID,Cities.RegionID,Cities.CountryID FROM Cities JOIN (Regions,Countries) ON Cities.RegionID = Regions.RegionID AND Cities.CountryID = Countries.CountryID WHERE Cities.CityName = '{city}' AND Regions.RegionName = '{$region}' AND Countries.CountryName = '{$country}' LIMIT 1"
**UPDATE
This is pretty basic stuff that you can get by looking at the PHP manual on MySQL.
http://php.net/manual/en/function.mysql-query.php
Since you're new, I will grant you a pass.
After you run your this query:
$location_result = mysql_query("SELECT Cities.CityID,Cities.RegionID,Cities.CountryID FROM Cities JOIN (Regions,Countries) ON Cities.RegionID = Regions.RegionID AND Cities.CountryID = Countries.CountryID WHERE Cities.CityName = '{$city}' AND Regions.RegionName = '{$region}' AND Countries.CountryName = '{$country}' LIMIT 1");
You need to access the result. So:
while ($row = mysql_fetch_assoc($location_result)) {
$cityID = $location_result['CityID'];
//etc... for each associative column
}
And then in your insert query, insert the $cityID variable for CityID column, etc...
I have a mysql table called
jos_users_quizzes with the following columns:
id
quiz_i
duser_id
I have a second table called jos_users with this columns
id
name
username
department
the user_id on first table is linked with the id of second table so quiz_id = id (jos_users)
How can build a query to multiple insert the ids of a selected department into the jos_users_quizzes table... IN ONE CLICK
I am thinking a sub query or a loop will do , but no sure how to contruct the query.
I need to select all user ids from selected department. For example have a list of departments, and once the department is selected , select all ids pertaining that department and insert all the Ids into the other table (quizid , (alldepartment ids)
Thanks in advance!
Code from and ASP.NET form to insert ....
string quizidselected = DropDownList1.SelectedValue;
string deptselected = ListBox2.SelectedValue;
//OdbcCommand cmd = new OdbcCommand("INSERT INTO jos_jquarks_users_quizzes (quiz_id,user_id) VALUES (' " + quizidselected + " ',677)");
OdbcCommand cmd = new OdbcCommand("INSERT INTO jos_jquarks_users_quizzes (user_id, quiz_id) SELECT id, ' " + quizidselected + " ' FROM jos_users WHERE department = ' " + deptselected + " '");
Based on my interpretation of what you want...
INSERT INTO jos_users_quizzes (user_id, quiz_id)
SELECT id, :new_quiz_id
FROM jos_users
WHERE department = :department
If you set the id using auto increment, then you can do something like this
insert into jos_users_quizzes (quiz_i) select id from jos_users;
It is easy if you know keyword like email address, department id or department name.
For example:
$depname = "Logistics"; // PHP // department name
$quizid = "Quiz-12"; // PHP // quiz name
Then make insert query:
<?php
$query = "INSERT INTO `to_table` (user_id, quiz_id)
SELECT id, '$quizid' FROM `from_table`
WHERE department = '$depname'";
?>
For more compatibility you can use Lower case if you obtained values from web page, like:
<?php
$query = "INSERT INTO `to_table` (user_id, quiz_id)
SELECT id, LOWER('%$quizid%')
FROM `from_table`
WHERE department like LOWER('%$depname%')";
?>
Use addslashes command for protecting database when you insert data from web page:
<?php
$query = "INSERT INTO `to_table` (user_id, quiz_id)
SELECT id, LOWER('%".addslashes($quizid)."%')
FROM `from_table`
WHERE department like LOWER('%".addslashes($depname)."%')";
?>