I ran this SQL statement in PHP to copy data from all columns from "other" into "table" (both table and other have same column names)
$x=mysqli_query($conn,"INSERT INTO table SELECT * from other WHERE item_id='33'");
$nid=mysqli_insert_id($conn);
I would expect $nid to have the new ID from "table" that it just inserted, but instead it returns "33", the ID of the other table coping from.
Maybe it copied everything including the ID from the other table and returned that?
Anybody knows why or how to fix?
Thanks
As both tables have the same column names your insert is setting the id as well as all the other fields.
To avoid that select from other all the fields except the item_id
You can write statically all the column names (except one) in the query in place of * or you can build the column list dinamically with a preliminary query:
// Get all columns names except one
// as comma separated list
// Column names are bacltick quoted
$result = $conn->query(
"SELECT `COLUMN_NAME` "
. "FROM `INFORMATION_SCHEMA`.`COLUMNS` "
. "WHERE `TABLE_SCHEMA`='your_db_name' " // DB name here
. "AND `TABLE_NAME`='other' " // TABLE name here
. "AND `COLUMN_NAME` != 'item_id'" ); // EXCLUDED column here
if( ! $result )
{
// HANDLE EXCEPTION
}
$columns = $result->fetch_all();
foreach( $columns as &$c )
{
$c = '`' . $c[ 0 ] . '`';
}
$columns = implode( ',', $columns );
// Perform the copy
$x = mysqli_query( $conn, "INSERT INTO `table` SELECT $columns from `other` WHERE item_id='33'");
$nid = mysqli_insert_id( $conn );
Side note: if your destination table name is table it must be escaped between backticks `table`.
Related
I am trying to run a query to determine if a column A is true. If its true, get the contents of a different column B (possible array separated by ",") and use those contents to query a different table. My problem is, column B may be one number or may be 10 numbers all separated by "," and I need to query the second table for a column for each of the numbers of the previous query. If someone can help that would be great.
edit: I tried to use the array explode function but can't figure out how to query the next table to include those values.
I picture it being something like
query = select * from table where location = arrayValue[1] or location = arrayValue[2]
Adaptation of Telmo Marques here but improved :
<?php
//Let's say $bcolumn is a string with the values of B column, separated by colons
$bcolumnArray = explode(",", $bcolumn);
array_walk($bcolumnArray, 'htmlentities');
//Build SQL query
$SQL = 'SELECT * FROM table';
if(count($bcolumnArray)){
$SQL.= ' WHERE IN ("'.implode('", "', $vbcolumnArray).'")';
}
//Query your second table here
$Qry = mysql_query($sql);
// Results here :
while($Res = mysql_fetch_assoc($Qry)){
print_r($Res);
}
?>
I would suggest PDO also... take a look : PDO.
Use PHP's explode() function to transform your string into an array.
<?php
//Let's say $bcolumn is a string with the values of B column, separated by colons
$bcolumnArray = explode(",", $bcolumn);
//Build SQL query
$sql = "SELECT * FROM table WHERE ";
for($i=0; $i < count($bcolumnArray); $i++)
{
$sql .= "location = " . $value;
if($i != count($bcolumnArray)-1)
{
$sql .= " or ";
}
}
//Query your second table here
mysql_query($sql);
?>
Documentation: http://php.net/manual/en/function.explode.php
I have two databases($db1, $db2) with exact table structure(table1). $db2.table1 has new rows which i want to insert into $db1.table1 (i.e. if $db2 is new and $db1 is old, I want to update $db1 with new entries from $db2).
I came up with following php code, and it should work fine, but I am worried about special characters in column ids as well as values to be inserted in it.
Here's the code:
require('update_functions.php'); //contains helper functions
function arraywalk_mysql_real_escape_string(&$value, &$key, $sql_connection) {
$value = mysql_real_escape_string($value, $sql_connection);
$key = mysql_real_escape_string($key, $sql_connection);
}
$sql_connection_old = connectdb('old');
$sql_connection_new = connectdb('new');
$table = 'member'; $pkey = 'id'; //table name and primary key
$last_row_member = mysql_fetch_assoc(last_row($sql_connection_old, $table, $pkey));
//fetches last row from old db
$new_row = new_row($sql_connection_new, $pkey, $last_row_member[$pkey], $table, 'ASC LIMIT 1');
//the new_row function executes following query (after sanitizing input)
//'SELECT * FROM '.$table.' WHERE '.$pkey.'>'.$pkey_value.' ORDER BY '.$pkey.' '.$extra
while($result = mysql_fetch_assoc($new_row)) {
array_walk($result, 'arraywalk_mysql_real_escape_string', $sql_connection_old);
$update_member_query = 'INSERT INTO ' . $table . '( '
. implode(", ", array_keys($insert_vars))
. ' ) VALUES ( \''
. implode("', '", $insert_vars)
. '\' )';
}
I don't know if there will be any special characters in column names. Should I enclose them in backticks?
If yes then should I parse them using mysql_real_escape_srting()?
What about VALUES ? Should I enclose them in quotes 'value'? What if the value to be inserted is a number? what if its Date/Time?
Is there a way where I can bypass fetching data from old database into PHP variables and inserting it back to database (so above questions become irrelevant)?
Note : Even though there are two connections, I have the same SQL server serving the two $db
You can do it in SQL:
INSERT INTO db1.table1
SELECT * FROM db2.table1
WHERE db2.table1.id > (SELECT MAX(id) FROM db1.table1)
I am trying to write a MySQL query (in PHP) that will update a set of fieldnames contained within an (imploded) array with a set of values contained within another (imploded) array.
What I have right now is this:
$edit= mysql_query ("UPDATE tablename SET `".$EXPfields."` = '".$EXPvalues."'
WHERE ID = '$ID'");
But for $EXPfields = EXP1, ?EXP2?, ?EXP3
and $EXPvalues = Communications', 'Electronics', 'Engineering
(both imploded arrays, ? is actually a backtick: `)
I get the following error message:
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 ' ?EXP2?, ?EXP3? = 'Communications', 'Electronics', 'Engineering' ' at line 2
(again, ? is actually a backtick `)
I've been playing around with this for ages, but I can't see where I have gone wrong, help pls! Thanks!
Update queries have the following syntax:
UPDATE table
SET column = expression
WHERE predicates;
You could loop through the array of fields and create a new array containing both column names and values. For example:
$update_sql = '';
for($i = 0; $i < count($EXPfields); ++i)
{
$update_sql = "`" . $EXPfields[$i] . "` = '" . $EXPvalues[$i] . "', ";
}
$update_sql = substr($update_sql, 0, -2);
$edit = mysql_query("
UPDATE
tablename
SET
" . $update_sql . "
WHERE
ID = '$ID'");
UPDATE table
SET
field1 = expression1,
field2 = expression2,
field3 = expression3
WHERE ...
You need to do comma separated field=value pairs. eg:
$query = UPDATE ?tablename? SET ?field1?='value1', ?field2?='value2' WHERE (?field3?='value3')
How do insert multiple rows into a mysql table, with one column remaining constant, and the other as an array.
//inserted profession into professions table, return id
$new_profession_id = mysql_insert_id();
$qualification_array = array();
foreach ($_POST['qualification'] as $qual){
array_push($qualification_array, $qual);
}
$query = "???
now how would I insert this into the profession_has_qualification table? its got me stumped...
You can do like this:
$new_profession_id = mysql_insert_id();
foreach ($_POST['qualification'] as $qual){
mysql_query("insert into TableName set pid = $new_profession_id, qualification = '" . mysql_real_escape_string($qual) . "'");
}
I have to add some enum options to a database table. The problem being, I will have to do this to several tables & databases, and they may not all have the same enum data type. Is there a why to write an alter table query or something similar to append options to a enum data type?
If there is no way to do this purely in MySQL, how would you approach this problem with a PHP script?
there is not easy way to append enum values.
this is ugly and untested, but i think it will give you an idea:
<?php
$sql = "select table_schema
, table_name
, column_name
, column_type
, is_nullable
, column_default
from information_schema
where data_type = 'enum'";
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
// these are important --> leading comma --v close paren --v
$new_enum = substr($row['column_type', 0, -1) . ",'new','enums','here')"
$sql = "alter table `{$row['table_schema']}`.`{$row['table_name']}`";
$sql .= " modify column `{$row['column_name']}`";
$sql .= " $new_enum";
$sql .= ($row['is_nullable'] == 'YES') ? " NULL" : " NOT NULL";
$sql .= " default $row['column_default']";
mysql_query($sql);
}
you could probably do this "purely in mysql" with a stored procedure, but that's more than i can wrap my brain around right now. :)