I'm new to PHP, and I do not it's syntax and principles very well.
I have such code:
function exportFromTransbase($table_name) {
//$odbc_query = "SELECT * FROM " . $table_name. " WHERE ((CDS_CTM subrange(248 cast integer) = 1) AND (CDS_LNG_ID = 16))";
$odbc_query = "SELECT * FROM " . $table_name. "";
$data = odbc_exec($this->odbc_id, $odbc_query);
odbc_longreadlen($data, 10485760);
$oufile=fopen($table_name.".sql", 'w') or die("error writing file");
$q1='INSERT INTO `' . substr($table_name, 4) . '` VALUES';
fwrite($oufile, $q1);
while($row = odbc_fetch_array($data))
{
foreach($row as $key => $value) {
$keys[] = "`" . $key . "`";
if ($value == ""){
$value = 'NULL';
$values[] = "" . mysql_real_escape_string($value) . "";
}
else{
$values[] = "'" . mysql_real_escape_string($value) . "'";
}
//echo "\n \n ololo ".$value;
}
$mysql_query = "\n (".implode(",", $values).")," ;
fwrite($oufile, $mysql_query);
//mysql_query($mysql_query);
set_time_limit(0);
unset($keys);
unset($values);
unset($row);
}
$stat = fstat($oufile);
ftruncate($oufile, $stat['size']-1);
fseek($oufile, 0, SEEK_END);
fwrite($oufile, ";".$r);
//} while ($r < 5 );
fclose($oufile);
if ($mysql_query){
print "Ýêñïîðò äàííûõ èç òàáëèöû " . $table_name . " çàâåðøåí!";
//strtolower(substr($table_name, 4))
}
}
what and where i need to custom, so that i export all table fields except one, for example called Size, i must insert in db is this field nulls....
Also if it is easy, how to split my sql query in batches of 5000 rows? so insert (5000 rows) then insert another 5000....
But first i need to export all fields, except one...
To the best of my knowledge, it can't be possible.
You can use simply:
SELECT field1, field2, field3, field4 FROM table
See Select all columns except one in MySQL?
And if you have more fields in your table then you can use * only.
At the time of insert you can make a condition which ignores the field which you don't want in new table.
Can you use
"select * from {table} where {sth} != {condition}"
Then you can fetch all data except one. The one is excrpted follow your condition.
Meanwhile,if you want to insert by 5000, you can read 5000 lines one time and insert into.
Related
When I try to export MySQL table to csv (use php) and make it a list in app inventor, but the list doesn't show.
My Block :
My php file :
if ($result = mysqli_query($dbc, "SHOW COLOMNS FROM Absent")){
$numberOfRows = mysqli_num_rows($result);
}
if($numberOfRows > 0) {
$values = mysqli_query($dbc, "SELECT full_name FROM Absent");
while($rowr = mysqli_fetch_row($values)){
for($j=0; $j<$numberOfRows; $j++) {
$csv_output .=$rowr [$j]. " ,";
}
$csv_output .= "\n";
}
}
print $csv_output;
exit;
Try to export to csv using mysql native method, for example:
SELECT id, name, email INTO OUTFILE '/tmp/result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY ‘\\’
LINES TERMINATED BY '\n'
FROM users WHERE 1
i don't know much about app-inventor, but as for the sql queries:
the first table is "CUSTOMER", your second is: "Absent", is it a typo?
(your'e iterating your "Absent" row with the number of columns you're getting from "CUSTOMER", was that your intention?)
your "$rowr" var has only 1 column ("full_name"), so you could easily:
drop the "for loop", to:
$csv_output .=$rowr [0];
P.S.
an alternative way of coding that in php would be:
$result = mysqli_query($dbc, "SELECT column1, column2, column3 FROM Absent");
while ($row = mysqli_fetch_assoc($result))
{
$comma = "";
foreach( $row as $key=>$value )
{
$csv_output .= $comma . $value;
$comma = ", ";
}
$csv_output .= "\n";
}
print $csv_output;
exit;
I have a PHP script that is passing large quantities of queries to a DB very quickly. Does a MySQL DB queue the queries as they come in if it can't process them at the same speed they are being passed, or do they get lost?
My program has written and passed syntactically correct queries to the DB, but the DB is very far behind in terms of information contained in tables and number of tables.
Some example code (I am slightly new to PHP, so my code/coding style may be horrifying):
//If table has one primary key
$val = $tblColPkArray[0];
$pkInsert = ", PRIMARY KEY (". $val['COLUMN_NAME'] .")";
$pkColName = $val['COLUMN_NAME'];
$string = ltrim($string, ",");
$oneCreateTableQuery = $beginning . $string . $pkInsert . $end;
echo $oneCreateTableQuery . "\n";
$newLink->query($oneCreateTableQuery);
$pkValuesInOld = "SELECT " . $pkColName . " FROM " . $tables . ";";
$pkValsResult = $link->query($pkValuesInOld);
while($pkValues = $pkValsResult->fetch(PDO::FETCH_ASSOC))
{
$pkRowValuesQuery = "SELECT * FROM " . $tables . " WHERE " . $pkColName . " = '" . $pkValues[$pkColName] . "';";
echo $pkRowValuesQuery . "\n";
$valsOfPkInOldTable = $link->query($pkRowValuesQuery);
while($pkVals = $valsOfPkInOldTable->fetch(PDO::FETCH_ASSOC))
{
//var_dump($ckVals);
$insertBeginning = "INSERT INTO " . $tables . "(";
$insertValuesSection = ") VALUES (";
$insertEnd = ");";
$keys = "";
$rowValues = "";
foreach($pkVals as $key => $value)
{
$keys = $keys . ", " . $key;
$rowValues = $rowValues . ", '" . $value . "'";
}
$insertStatement = $insertBeginning . ltrim($keys, ",") . $insertValuesSection . ltrim($rowValues, ",") . $insertEnd;
echo $insertStatement . "\n";
$newLink->query($insertStatement);
}//While loop: Inserting values of old table into new table via INSERT INTO statement
//unset();
} //While loop: Selecting all values from old table based on PK values per table, pass result of that query to next while loop
You can do this in a single query, instead of calling multiple insert statements.
For instance, instead of running these 3 queries,
INSERT INTO table VALUES(1, 2);
INSERT INTO table VALUES(3, 4);
INSERT INTO table VALUES(5, 6);
...
You could run this query:
INSERT INTO table VALUES(1, 2), (3, 4), (5, 6), ...;
Looks like you could do even combine the INSERT and SELECT:
INSERT INTO table (...)
SELECT ... FROM ...;
Furthermore, your nested loops look like this might work:
INSERT INTO table (...)
SELECT ... FROM ...
JOIN ...;
That would get it down to one call to ->query() and eliminate most of your code.
I am writing a code, where I have to produce a query with many OR statements, and I think there is a more comfortable way to this than:
foreach ($plz as &$value) {
if (empty($i)) {
$query = "WHERE plz='$value'";
} else {
$query = "$query OR plz='$value'";
}
$i++;
}
$sql = mysql_query("SELECT * FROM table $query");
while ($data = mysql_fetch_array($sql)) {
//do something
}
If you have multiple values a column may take, just connect them using the IN operator:
Instead of writing
... WHERE col=1 OR col=2 OR col=3
just write
... WHERE col IN (1,2,3)
To collect all entries in PHP, use an array and implode() later on:
// collecting values
$vals = array();
$vals[] = 1;
$vals[] = 2;
// ...
// add them to your query
$query .= ' WHERE col IN ( ' . implode( ',', $vals ) . ')';
// execute the query ...
In case your values are not integer, but need to be enclosed in apostrophes within the query, insert them that way into the array in the first place:
$vals[] = "'my string value'";
You're looking for ;
SELECT * FROM table WHERE plz in ('value1', 'value2', 'value3')
Be aware of SQL injections...
If the column plz is INT type, and all $plz are also integers, then:
$query = 'WHERE plz IN( ' . implode(',', $plz) . ')';
would work. Otherwise, trying this might work(not tested):
$query = 'WHERE plz IN( \'' . implode("','", $plz) . '\')';
I have a sql table in my database "accounts" whose structure looks like this.
ItemNo CostPrice SellingPrice Discount(10%) Price(INR)
100 $100 $150 $135 Rs.7425
101 $200 $250 $225 Rs.10395
102 $150 $200 $180 Rs.7920
103 $500 $550 $495 Rs.25245
Here each column is dependent on the previous one.
SellingPrice = CostPrice + 50
Discount = SellingPrice + (0.1 * SellingPrice)
Price(INR) = SellingPrice * ($_Conversion_rate_to_Rs)
I need to calculate the SellingPrice and update it in the table.
Then I calculate the Discount and update the table
Then I calculate the Price(INR) and update the table.
I am trying the following code but it doesnt seem to be working.
$i = 0;
foreach($item_no as $item ){
mysql_query("UPDATE accounts SET SellingPrice = CostPrice + 50 WHERE item_no = '$item[$i]'") or die(mysql_error());
++$i;
}
Now after updating the SellingPrice I need to calculate the discount and update the database.
$i = 0;
foreach($item_no as $item ){
mysql_query("UPDATE accounts SET Discount = SellingPrice + (0.1 * SellingPrice) WHERE item_no = '$item[$i]'") or die(mysql_error());
++$i;
}
And so on..
My doubt may be quite simple but I tried a lot and couldn find a correct solution.
Can I know my mistakes and the correct solution ?
EDIT!
The way I edit multiple fields is with a custom update function. The function takes an associative array of "field"=>"new value". Here's the function:
function update($table,$values,$conditions){
$query = "UPDATE `" . $table . "` SET ";
foreach($values as $key => $value){
if($key == "password")
$query .= "`password` = PASSWORD('" . $mysqli->real_escape_string($value) . "'),";
else if(is_numeric($value))
$query .= "`" . $mysqli->real_escape_string($key) . "` = " . $mysqli->real_escape_string($value) . ",";
else
$query .= "`" . $mysqli->real_escape_string($key) . "` = '" . sanitize($value) . "',";
}
$query = substr($query,0,-1);
if(!is_string($conditions)){
$conditionStr = "";
foreach($conditions as $key => $value){
if($key == "password")
$conditionStr .= "`password` = PASSWORD('" . $mysqli->real_escape_string($value) . "') AND ";
else if(is_numeric($value))
$conditionStr .= "`" . $mysqli->real_escape_string($key) . "` = " . $mysqli->real_escape_string($value) . " AND ";
else
$conditionStr .= "`" . $mysqli->real_escape_string($key) . "` = '" . sanitize($value) . "' AND ";
}
$conditionStr .= substr($conditionStr,0,-4);
$conditions = $conditionStr;
}
$query .= " WHERE " . $conditions . " ;";
$mysqli->query($query);
}
You use it like this:
update("theTable",array("username"=>"whateverTheNewNameIs"),array("userID"=>55));
That updates userID=55 and makes the username something new. You can just expand the second array to update more things.
I think you a problem in your updates and your where clause
I'd make a variable for your new cost price,
$newSellingPrice = $item[$i]['sellingPrice'] + 50;
In your update you can use $newSellingPrice
Then in your where, you have a typo, you didn't use the $ to get the item array.
You'll need to leave the query string if you're using square bracket notation
"... WHERE item_no = " . $item[$i] . " ;";
To answer your question, if you want to update all fields in the table, there is no need to add a WHERE condition, you can just use:
UPDATE accounts SET SellingPrice = CostPrice + 50
and run only one query in total instead of one query per item.
However, all columns that depend on other columns really don't need to be separate columns, you would be a lot better of with a table with just 2 columns and calculate the prices as you need them. Now you have a lot of duplicate information as the cost price and the multipliers are the only values you really need to store.
I've got a SQL query within a foreach loop. Sometimes there can be many, and I mean a lot of queries to do, depending on several criteria, up to 78 queries potentially.
Now, I know that premature optimisation is root cause of all evil, but I don't want to see 78 queries - it's just not healthy.
Here's the code:
$crumbs = explode(",", $user['data']['depts']);
foreach ($crumbs as &$value) {
$data = $db->query("SELECT id FROM tbl_depts WHERE id = '" . $value . "'");
$crumb = $data->fetch_assoc();
$dsn = $db->query("SELECT msg, datetime FROM tbl_motd WHERE deptid = '" . $value . "'");
$motd = $dsn->fetch_assoc();
if ($motd['msg'] != "") {
<?php echo $motd['msg']; ?>
}
}
Can I make it any better?
Use IN MySQL operator to search over a set of values for id:
$ids = '"' . implode('", "',$crumbs) . '"';
$query1 = "SELECT id FROM tbl_depts WHERE id IN (" . $ids . ")";
$query2 = "SELECT msg, datetime FROM tbl_motd WHERE deptid IN (" . $ids . ")";
And so you will not need to retrieve all data you need using foreach loop, so you will have only 2 queries instead of 78.
Example: I have a table named table with 10 records which ids are: 1,2,3,4,5,6,7,8,9,10 (auto-incremented). I know I need records with ids 1,5,8. My query will be:
$sql = "SELECT * FROM `table` WHERE id in (1,5,8);";
And I don't understand why do you need to use & operator in foreach loop if you don't modify the $crubms arrays values.
I think this is want you want.
SELECT msg, datetime
FROM tbl_depts td
INNER JOIN tbl_motd tm ON td.id = tm.deptid