First of all thanks for your help, I'm asking how can I insert data into fields starting from the left? Depending on the entity sometimes several fields at the end are left blank but I need to insert the filled fields into the table. If I try to do this, I obviously get a column-values mismatch error.
Thanks!
The column count you use and the number of values you try to insert have to match. You can specify what you want to insert, so you don't have to pass the columns which aren't needed (and so you don't need to pass "blanks").
INSERT INTO Store_Information (store_name, Sales, Date)
VALUES ('Los Angeles', 900, 'Jan-10-1999')
More information:
http://www.1keydata.com/sql/sqlinsert.html
Just specify only fields names you gonna insert at the moment:
INSERT INTO table (field1, field2, field3) VALUES (value1, value2, value3)
or this way
INSERT INTO table SET field1=value1, field2=value2, field3=value3
no matter is it from left, right or checkered
as SQL query is just a string, you could use some PHP code to build this string in the way you want.
hereis an example code in the form of very simple helper function to produce SET statement dynamically:
function dbSet($fields) {
$set='';
foreach ($fields as $field) {
if (isset($_POST[$field])) {
$set.="`$field`='".mysql_real_escape_string($_POST[$field])."', ";
}
}
return substr($set, 0, -2);
}
it can be controlled by $fields array.
used like this
//if we have full set of data
$fields = explode(" ","name surname lastname address zip fax phone");
$query = "INSERT INTO $table SET ".dbSet($fields);
//if we have only three fields ready
$fields = explode(" ","name surname lastname");
$query = "INSERT INTO $table SET ".dbSet($fields);
but you desperately need to learn basic PHP string operations to be able to do such things yourself.
string operations are most important in PHP, as almost every task for PHP is just string manipulation like in your case.
Use querys like
insert into table set col1=val1, col2=val2;
or
insert into table(col1, col2) values(val1, val2);
That is the only way around it. I think method 2 is the most commonly used.
If there is any way you can supply default values for each column use them for the columns you don't have values for.
if all the data can be "NULL", you can setup your query with variables that, if not set, are NULL, example:
$col1 = null;
$col2 = null;
$col3 = null;
$col4 = null;
$col5 = null;
then populate the columns you need
$col1 = 'val1';
$col2 = 'val2';
$query = "INSERT INTO (col1, col2, col3, col4, col5) VALUES ($col1, $col2, $col3, $col4)";
Sincerely I'll never use something like this... but you asked for it...
mysql_query("INSERT INTO People (First_Name, Last_Name, Age)
VALUES ('Marcus', 'Porter', '28')");
mysql_query("INSERT INTO People (First_Name, Last_Name, Email)
VALUES ('Marcin', 'Kruk', 'marcin.kruk#gmail.com')");
Related
I have 17 columns in my DB
I'm inserting values from different sources. Somewhere I haven't, for example, company/company_info values (I'm setting in PHP FALSE values for relevant variables).
So, I need some kind of PHP INSERT query to insert only not empty variables and columns of certain list.
For example, I could do:
$q = "INSERT INTO `$tname` (`phone`,`location`, `pagelang`, `company`, `company_url`, `phone_no_cc`, `phone_type`, `operator`, `pageviews`, `rating`, `comments_number`, `activity_by_days`, `activity_by_hours`) VALUES (
'$main_number', '$number_advanced_info[location]', '$pagelang', '$company[name]', '$company[site]', '$number_advanced_info[number_no_countrycode]', '$number_advanced_info[phone_type]', '$number_advanced_info[operator]', '$searches_comments[searches]', '$rating', '$searches_comments[comments]', '$history_search', '$daily_history'
);";
With insert of 14 columns and their values.
But sometimes I need to insert less columns/values and let MYSQL set default values for not listed columns. For Example, I want to insert only 5 columns.
$q = "INSERT INTO `$tname` (`phone`,`location`, `pageviews`, `rating`) VALUES (
'$main_number', '$number_advanced_info[location]', '$searches_comments[searches]', '$rating'
);";
Is there some CLASS or any solution like binding values which will automatically build query depending which values are not NULL?
I need some kind of code:
if (!$phone) {
$columns .= "`column_name`," ;
$values .= "value";
}
I have a mysql table with over 100 columns, but I've shortened it to 6 for this example:
col0(autoincrement), col1, col2, col3, col4, col5, col6
I'm getting data from external sources ($csvcontent below), and that data will have 6 or less values per line. I'd like to use PHP to read these values into an array, and insert the array values into into my mysql table.
$csvcontent = file from external source
$fieldseparator = ",";
$lineseparator = "\n";
$linearray = array();
foreach(explode($lineseparator,$csvcontent) as $line) {
$linearray = explode($fieldseparator,$line);
$linemysql = implode("','",$linearray);
$query = "insert into MYTABLE values('','$linemysql');";
}
How can I insert the following rows, assuming that I don't know ahead of time how many values are stored inside of $csvcontent? This existing code works well when I always have 6 values, but not when I have fewer.
insert into MYTABLE values('','1','2','3','4','5','6'); //works
insert into MYTABLE values('','1','2','3','4'); //doesn't work
insert into MYTABLE values('','1','2','3','4','5'); //doesn't work
Well, based on the size of $linearray, you can create a column sequence and attach that to your insert query.
<?php
$columns = ['col1','col2','col3','col4','col5','col6'];
$linearray_samples = [
[1,2,3,4,5],
[1,2,3],
[1,2,3,4],
[1],
[1,2],
[1,2,3,4,5,6]
];
foreach($linearray_samples as $each_sample){
echo "(",commaSeparatedColumns($each_sample,$columns),")",PHP_EOL;
}
function commaSeparatedColumns($sample,$columns){
return implode(",",array_slice($columns,0,count($sample)));
}
The code outputs:
(col1,col2,col3,col4,col5)
(col1,col2,col3)
(col1,col2,col3,col4)
(col1)
(col1,col2)
(col1,col2,col3,col4,col5,col6)
Demo: https://3v4l.org/QLnFo
<html>
<head>
HTML CODE
<?
$username="xxxxxx";
$password="xxxxxx";
$database="xxxxxx";
mysql_connect(localhost,$username,$password);
$escape = "INSERT INTO monster VALUES ('',$_POST["name"],$_POST["soort"])";
$escape2 = "DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL";
$query=mysql_real_escape_string($escape);
$query2=mysql_real_escape_string($escape2);
#mysql_select_db($database) or die("MySQL error: Kan inte ansluta till databasen.");
mysql_close();
?>
</body>
</html>
Every time i run this(from another file, containing the name and soort post's) I get an 500 internal server error. First I figured that the queries may be the problem, but they don't even get executed. However, i tried to escape the queries. But still error.
What is wrong with this code? (note: $escape2 is some code i found that removes duplicates in the database. But i don't really know how to format it so that it can be used through php.)
Use something like below...
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Please do not insert values without escaping.
problem in insert into statement
it should be
$escape = "INSERT INTO monster VALUES ('',".$_POST['name'].",".$_POST['soort'].")";
it is preferable to write colums name while writing insert queries
if column contains string values like VARCHAR or TEXT then use quoted_printable_decode
pass null if column is autoincrement
insert statment
$escape = "INSERT INTO monster (col1, col2, col3) VALUES (NULL,'".$_POST['name']."',".$_POST['soort'].")";
or
$escape = "INSERT INTO monster (col2, col3) VALUES ('".$_POST['name']."',".$_POST['soort'].")";
It looks like you need something like this:
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Also I would suggest to use prepared statements because it is bad experience to build queries.
First of all I have cool proposition for you. What do you say about some advanced PHP? One step further into great world of safe PHP + MySQL apps?
Introducting to you a PDO. (I know this is not answer to your question but you can consider it). Example of use on your queries:
$db = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
$insertQuery = $db->prepare('INSERT INTO monster VALUES ("", :name, :soort)');
$deleteQuery = $db->prepare('DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL');
//to execute query:
$deleteQuery->execute();
//or with params:
$insertQuery->execute(array(
':name' => $_POST['name'],
':soort' => $_POST['soort'],
));
Cool, huh? There is more... Now according to your problem it could be everything (as we don't have error log) but my guess is:
Try to use <?php instead of <?
$escape = "INSERT INTO monster VALUES ('',{$_POST["name"]},{$_POST["soort"]})";
EDIT:
As you provided error log - now I'm sure that problem is in $escape query. It's because you used $escape = " <- and then $_POST["name"] so there was a collision of " (if I can say so).
Try this:
Whenever you insert string type of values in the database using query it has to pass in the quote format. So you just need to change your insert query here.
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
write query like this.
-
Thanks
I have 2 tables: STD and SMS. What I need to do is to select from table STD the copy the result to an array then insert each element of the array to another table, SMS.
Here's my code:
$query=mysql_query("Select from STD WHEre <my conditions>");
$result=mysql_fetch_array($query)
foreach($result as $value)
mysql_query("INSERT INTO SMS set SMS.column='$value'")
It is not updating the SMS table at all. Can someone here have a better idea or tell me what's wrong with the code? thanks.
You about updating or inserting data? if You want to insert user JW already answered, else you must set condition on Your update query.
$query=mysql_query("Select from STD WHEre <my conditions>");
$result=mysql_fetch_array($query)
foreach($result as $value)
mysql_query("Update SMS set SMS.column='$value' where SMS.std_id = '{$value['id']}'"); /// fieldnames are my example, You must generate Your condition..
or You can use update from another table
try this, but this will update all the values of the table like your actual query does:
$query=mysql_query("Update SMS set
SMS.column=(Select <column_name> from STD where <my conditions> limit 1)");
You can do that in just one query, use INSERT INTO...SELECT statement.
INSERT INTO SMS (col1, col2, ...., Coll3)
SELECT col1, col2, ...., Coll3
FROM STD
I presume you're trying to get all rows from the STD table and insert them into the SMS table, and that the SMS table definition is the same as the STD one?
If so, this should work:
$result = mysql_query('SELECT * FROM `STD` WHERE <my_conditions>');
while (($row = mysql_fetch_assoc($result)) !== FALSE) // Loop over all rows selected
{
$columns = implode(', ', array_keys($row)); // returns string of column names e.g. "col1, col2, col3" etc.
$values = "'" . implode("', '", array_values($row)) . "'"; // returns string of quoted values e.g. "'val1', 'val2', 'val3'"
mysql_query("INSERT INTO `SMS` ($columns) VALUES ($values)"); // inserts the row into the SMS database table
}
is there a clean way of INSERT a lot of field entry values without them having to be in order? similar to how you can do with the UPDATE like below. can INSERT be done in that format?
$qstring="UPDATE test SET word = 'something' ,";
$qstring .= " word1 = 'something1',";
...
mysql_query($qstring);
Yupp,
insert into
your_table
set
field_1='Yay!',
field_2='Mmmbop!',
...
You can use the SET syntax:
insert into my_table set col1='value', col2='value'
Or, you can specify column names with a VALUES clause:
insert into my_table (col1, col2, col3) VALUES ('value1', 'value2', 'value3')
Using this later form, the values in the VALUES clause must match the order of the values in the column list that precedes the VALUES clause.
If you turn on "extended inserts" (it's usually on by default), you can use the latter form to insert multiple rows with a single statement:
insert into my_table (col1, col2, col3) VALUES
('value1', 'value2', 'value3'),
('row2value1', 'row2value2', 'row2value3'),
('row3value1', 'row3value2', 'row3value3')
INSERT INTO test SET word = 'something', word1 = 'something1'
yes we can do this also with INSERT
$qstring="Insert into test SET";
$qstring .= "word = 'something' ,";
$qstring .= " word1 = 'something1',";
...
mysql_query($qstring);