I have an array containing column names of a table i want to create which i got from an excel sheet.
I tried something like this
$sql = "CREATE TABLE IF NOT EXISTS ".$month."-".date('Y')."(
".foreach($tableColumnNames as $columnName){
echo $columnName." VARCHAR(200) NULL,";
}
."
)";
It returns error saying Parse error: syntax error, unexpected 'foreach' same thing with while loops
How can i create Table with column names i have in an array. And How can i set each column data type unique (INT,VARCHAR,..)
you want to build the sql string like so:
$sql = "CREATE TABLE IF NOT EXISTS ".$month."-".date('Y')."(";
foreach($tableColumnNames as $columnName){
$sql .= $columnName." VARCHAR(200) NULL,";
}
$sql=rtrim($sql,',');//remove last comma
$sql .=")";
Related
I need to populate several columns of MYSQL table with data from arrays. So one column corresponds to one array. I have used the following code to fill just one column with data:
function addSystemDataTanks ($db, $tankNamesArray, $tankVolumesArray) {
$myArray = array();
$myString = implode ("'), ('",$myArray);
$statement = "replace into myTable (ID, NAME)";
$statement .= "values (' ";
$statement .= $myString;
$statement .= "')";
$result = mysqli_query($db, $statement);
if ($result) {
return true;
}
}
I need the ID field to be populated by auto-generated incremented numbers. But I need these rows to be replaced with new values next time this form is submitted. For the "replace" to work the ID has to be the same as previously used, otherwise it will just create new entries.
Also, is there a better way to input arrays as columns in MYSQL table, other than one by one, cause I need all row values to match to each other and the ID should be unique and start from 0 or 1 next time the form is submitted.
Thanks for any help.
If you just want the row ID to be incremental you're making life hard for yourself! When you create the table in MySQL, use AUTO_INCREMENT on the ID, then you can just enter a NULL value for the ID in your code:
CREATE TABLE blah (ID INT NOT NULL AUTO_INCREMENT, name VARCHAR(50), PRIMARY KEY(ID));
$sql = "INSERT INTO blah VALUES(NULL, 'Adam')";
"Adam" will now have an ID of 1 :)
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 been trying to create a database by using the first row of a CSV file, however I keep getting an error about my PDO syntax. Apparently something is going wrong with varchar(250) in the $columns variable:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 'varchar(250))' at line 1
The code is below:
<?
/********************************************************************************/
// Parameters: filename.csv table_name
$argv = 'seo_domains.csv seo_domains';
if($argv[1]) { $file = $argv[1]; }
else {
echo "Please provide a file name\n"; exit;
}
if($argv[2]) { $table = $argv[2]; }
else {
$table = pathinfo($file);
$table = 'seo_domains';
}
/********************************************************************************/
// Get the first row to create the column headings
$fp = fopen('seo_domains.csv', 'r');
$frow = fgetcsv($fp);
$ccount = 0;
foreach($frow as $column) {
$ccount++;
if($columns) $columns .= ', ';
$columns .= "$column varchar(250)";
}
$qry = $dbcon->prepare("CREATE TABLE if not exists $table ($columns);");
$qry->execute();
/********************************************************************************/
// Import the data into the newly created table.
$file = $file;
$qry = $dbcon->prepare("load data infile '$file' into table $table fields terminated by ',' ignore 1 lines");
$qry->execute();
?>
I changed the $fp fopen to a static value instead of using $file because apparently the guy who coded the code mentioned above, did not mention how to format the $argv variable. Yes, I already tried formatting according to his "Parameters" comment on the first line but still, no avail. I also statically changed the $table variable to 'seo_domains' since the $argv variable is not being split properly. Instead of re-coding the above code, I am wondering if anyone has any thoughts as to why my database would be resulting in the described error. Any help is appreciated. Just trying to create a table based on first row of the CSV file provided. Upon creation I would like to continue to insert all the row values below row 1 in the CSV, per usual.
try:
CREATE TABLE if not exists seo_domains (Domain varchar(250), Server varchar(250), IP varchar(250), Username varchar(250), Password varchar(250), Nameserver varchar(250), NameCheap varchar(250), GA varchar(250), WMT varchar(250), SB varchar(250), GAW varchar(250), notes varchar(250), BlankField varchar(250), id INT KEY NOT NULL AUTO_INCREMENT varchar(250));
key is a reserved word in SQL. See image below
As you may find that some of the column names in CSV could be reserved words you will need to escape them. In MySQL backticks are used. ie `key`
A user is creating a table. The user enters the number of fields that will be in the table, and a form is generated based on the number they entered. They then enter the names of the columns and the type. I then create the table based on what they entered.
I can get the arrays to populate correctly, but my error message says I have a syntax error. I'm sure I did something wrong, but I tried to add a while loop inside the query since there is no set number of variables to be entered. This is what I have. If there's a better way to do it, I'm all ears.
$sql = 'CREATE TABLE $table (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id), ';
while($numDone < $totalFields){
$sql .= $colName[$x] . ' ' . $types[$x] . ', ';
$x++;
$numDone++;
}
$sql .= ')';
$query1 = mysql_query($sql) or die(mysql_error());
**Solved
I changed the single quotes to double quotes, used the dot operator for $table, and added an if statement for the comma. It's working now.
For one, this
'CREATE TABLE $table'
will NOT fill in $table, but will be LITERALLY
CREATE TABLE $table
use " if you want variables to be shown. You would've spotted that if you'd just echo your $sql. There might be more, but probably easily discoverable trough mentioned debugging...
You apparenty have an extra trailing comma:
CREATE TABLE $table (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
col1 INT,
col2 INT,
-- ^ here
)
1
change the single quotes (') to double quotes (") for your query.
2
or use dot operator (.) to append php variable.
$tableName = "mytable";
echo $query1 = "SELECT * FROM $tableName";
echo $query2 = 'SELECT * FROM $tableName';
// Output
SELECT * FROM mytable
SELECT * FROM $tableName
You may have VARCHAR field entered without size like fieldname VARCHAR will return error instead it should be like fieldname VARCHAR(100) ? Trailing comma may also be the reason for error as Quassnoi commented.
If you are trying to get rid of the trailing slash you can also do this by using a counter.
$fieldsCount = count($listingFields);
foreach($listingFields as $key => $listing)
{ // create the insert statement (do not add comma at the end)
$query .=" ".$listing[0];
if ( $key+1 != $fieldsCount )
{
$query .=',';
}
}
Trying to check if a name is already stored in the database from the login user. The name is a set of dynamic arrays entered by the user threw a set of dynamic form fields added by the user. Can some show me how to check and see if the name is already entered by the login user? I know my code can't be right. Thanks!
MySQL code.
SELECT *
FROM names
WHERE name = '" . $_POST['name'] . "'
AND userID = '$userID'
Here is the MySQL table.
CREATE TABLE names (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
userID INT NOT NULL,
name VARCHAR(255) NOT NULL,
meaning VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
If $_POST['name'] is actually an array of strings, as you say, then try this PHP:
$namesString = '';
foreach ($i=0; $i < count($_POST['name']) $i++)
{
$namesString .= "'" . mysql_real_escape_string($_POST['name'][$i]) . "'";
if(isset($_POST['name'][$i + 1]) $nameString .= ', ';
}
With this query:
SELECT * FROM `names`
WHERE `name` IN ( $namesString )
AND `userID` = '$userID'
The query will return all the rows in which the name is the same as string in $_POST['name'].
First of all, if the userID field is unique, you should add a unique index on it in your table.
Also, watch out for SQL injection attacks!
Using something like this is much more secure:
$sqlQuery = sprintf('SELECT COUNT(id) AS "found" FROM names WHERE userID = "%s"', mysql_real_escape_string($_POST['name'], $conn));
This SQL query will return 1 row with 1 field (named found) which will return you the number of matched rows (0 if none). This is perfect if you only want to check if the userID exists (you don't need to fetch all data for this).
As for the dynamic array, you will have to post more information and I'll update my answer.
Meanwhile here are some usefull PHP functions that can help you do what you want:
For MySQL queries:
mysql_connect
mysql_real_escape_string
mysql_query
mysql_fetch_assoc
For your list of users:
explode
implode
Stated as you say, I'm quite sure the code does exactly what you are asking for. The SELECT should return the records that respond both to the name sent and the current user ID.
If you need some php code, here it is (should be refined):
$result = mysql_query('YOUR SELECT HERE');
if (!$result) {
die('ERROR MESSAGE');
} else {
$row = mysql_fetch_assoc($result));
// $row is an associative array whose keys are the columns of your select.
}
Remember to escape the $_POST.