When I enter data to mysql it shows as below, I want to take all the data to a one row. but since I'm entering data using an array I only have access to two elements at once. So how can I enter data to a single line? below is a snip of my code
$array = array("AAPL","GOOG","YHOO","FB","MSFT","NKE","SBUX");
foreach ($array as $s) {
$sql = "INSERT INTO portfolio ({$s} , {$sss}) VALUES ('{$amount}', '{$value}')";
}
Snip from MYSQL table
Your array is not of data values but column names. Your insert needs to be more like;
$sql = "INSERT INTO portfolio ("
foreach ($array as $s) {
$sql = $sql + " $s, ";
}
$sql = $sql + ") values (";
foreach ($amount as $s) {
$sql = $sql + " $s, ";
};
$sql = $sql + ");"
However, you should be using mysqli, binding parameters not building strings as in this example. Also, your table as shown has only one value per stock, no value and amount, only room for one value.
Related
can you see what is wrong on this query? I have been watching it for really long time and I can't see it.
ERROR:
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 ''' at line 1
$sql="SELECT country_name FROM countries WHERE country_id IN (";
foreach($cartContentVsDatabase as $key => $val){
$sql.= $key['country_id'].",";
}
")";
Some issues:
You have a trailing comma in your country list,
countries should be quoted as strings,
you are accessing the values from the key instead of the value part of the array elements.
you have a dangling closing parenthesis, which does nothing.
You should not even inject country strings, as that makes your code vulnerable for code injection: use prepared statements.
Here is code you could use:
// first put the countries in an array
foreach($cartContentVsDatabase as $key => $val){
$countries[] = $val['country_id'];
}
// create a list of `?`: one for every country
$in = join(',', array_fill(0, count($countries), '?'));
// use that in the query
$sql="SELECT country_name FROM countries WHERE country_id IN ($in)";
// Prepare the statement (this is PDO syntax)
$statement = $pdo->prepare($select);
// Pass the countries as parameter values, and execute
$statement->execute($countries);
See this Q&A for more on prepared statements in the context of this in (...) clause.
try this,
change ")"; to $sql.= ")";
$array_count = count($cartContentVsDatabase);
$temp_count = 0;
$sql="SELECT country_name FROM countries WHERE country_id IN (";
foreach($cartContentVsDatabase as $key => $val){
$temp_count++;
if($array_count < $temp_count)
{
$sql.= $val['country_id'];
}
else
{
$sql.= $val['country_id'].",";
}
}
$sql.= ")";
You could make your life a lot easier by
$sql= "SELECT country_name FROM countries WHERE country_id IN (".implode(",",array_column($cartContentVsDatabase,"country_id")). ")";
You can (and probably should) use a prepared query e.g. like the one below:
$sql= "SELECT country_name FROM countries WHERE country_id IN (".implode(",",array_fill(0,count($cartContentVsDatabase),"?")). ")";
and then bind the contents of $cartContentVsDatabase when you execute.
In your code you are not concatenate ")"; properly at the end. you can also store data into array and than use implode() for comma separated values like:
Example:
<?php
$sql = "SELECT country_name FROM countries ";
$countries = array();
foreach($cartContentVsDatabase as $key => $val){
$countries[] = $val['country_id']; // store country id in your array
}
if(count($countries) > 0){
$countrylist = implode("','",$countries); // implode all country list with comma.
$sql .= "WHERE country_id IN ('$countrylist')";
}
echo $sql; // print your query.
?>
Still i don't know, $key['country_id'] is the correct one or not, i think this should be $val['country_id'].
I try to upload my data to mysql Its working but it takes 35sec, too many sec.
What do I need to change in my code that it will work faster than 35 sec?
I use php to write my code and SQL query to send the data to my table that called "words" .
At my table in the database I have 4 columns ('word', 'num', 'hit', 'instoplist').
What I can do to fix this problem?
Thanks
This is my code:
<?php
function removeStopWordsFromArray($words)
{
.......
insert($words);
}
function insert($myWords)
{
global $conn;
foreach ($myWords as $key => $value) {
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql = "INSERT INTO words (word,num,hit,instoplist) VALUES ('$word', '$number', '$hit','$stop')";
if($conn->query($sql)!== TRUE)
{
echo "error". $conn->error;
}
}
fclose($fp);
}
$temp = pareseDocs();
removeStopWordsFromArray($temp);
?>
For every data you are running a query in DB. But the correct way in your case is to insert data in batches. You can write the code is following way:
$sql = "INSERT INTO words (word,num,hit,instoplist) VALUES";
foreach ($myWords as $key => $value) {
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql .= "('$word', '$number', '$hit','$stop'),";
}
$sql = rtrim($sql,',') //to remove last comma
if($conn->query($sql)!== TRUE)
{
echo "error". $conn->error;
}
This will run only single query in DB. Hence will be faster.
You can try this query outside of loop pass only one query:
INSERT IGNORE INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
IGNORE FOR HANDLING ERRORS
Your problem is that you are making each query separately in a for loop.
Take a look at https://stackoverflow.com/a/452934/4988637 to find out more on how to insert mutliple rows in a single query.
If you change your method to one single query, you should find your program's run-time to be drastically shortened.
In SQL Server 2008 you can insert multiple rows using a single SQL
INSERT statement.
INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
For reference to this have a look at MOC Course 2778A - Writing SQL
Queries in SQL Server 2008.
In your case, you could modify your code to look something like the following.
$sql = "INSERT INTO words (word, num, hit, instoplist) VALUES ";
foreach($myWords as $key => $value) {
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql .= "('$word', '$number', '$hit','$stop'),";
}
$sql = rtrim($sql, ',');
if($conn->query($sql) !== true) {
echo "error".$conn->error;
}
I have an array $members that contains some ID(maximum 6 in number) from the table users. Using the following code, I loop through each index of $members, search for the details and store them in another array.
foreach($members as $key=>$value){
$res = mysql_query("SELECT id,name,email FROM users WHERE id='$value'");
if ($res === false) {
echo mysql_error();
die;
}
$row = mysql_fetch_assoc($res);
if($row['id'])
{
$members_name[]=$row['name'];//array for name
}
}
Now I want to insert the ID & names that are stored in the array into another TABLE register in the following format:
(The left side are the rows in my TABLE register)
mem_0_id-->$members[0]
mem_0_name-->$members_name[0]
mem_1_id-->$members[1]
mem_1_name-->$members_name[1]
mem_2_id-->$members[2]
mem_2_name-->$members_name[2]
mem_3_id-->$members[3]
mem_3_name-->$members_name[3]
mem_4_id-->$members[4]
mem_4_name-->$members_name[4]
How can I insert in this way? using just a single INSERT statement?
haven't tried this, but here is my answer anyway :)
$query = "INSERT INTO register(id, name) VALUES ($members[0], $members_name[0])";
for($i=1; $i<count($members); $i++)
{
$query .= ", ($members[$i], $members_name[$i])";
}
then try to execute the query..
Do you do anything else with the array, or are you just retrieving it from one table in order to insert it into another?
If so then you can do the whole thing like this.
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "insert into register (id, name) select id, name from users where id in ($memberIds)";
mysql_query($query); // this will select and insert in one go
If you do need to keep the array in memory, then it's still a good idea to get it all out at once
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "select id, name from users where id in ($memberIds)";
$res = mysql_query($query);
while ($row = mysql_fetch_assoc($res)) {
$memberData[] = $row;
}
That's because running a query inside a loop is very bad for performance. Every time you run a query there is an overhead, so getting all the data at once means you pay this overhead once rather than multiple times.
Then you can build a statement to insert multiple rows:
$sql = "insert into register (id, name) values ";
$sql .= "(" . $memberData[0]['id'] . "," . $memberData[0]['name'] . ")";
for($i = 1; $i < count($memberData); $i++) {
$sql .= ",(" . $memberData[$i]['id'] . ",'" . $memberData[$i]['name'] . "')";
}
mysql_query($sql);
It's a bit nasty because of the commas and quotes but if I've done it correctly then if you do
echo $sql;
you should get something like
insert into register (id, name) values (1, 'john'), (2, 'jane'), (3, 'alice');
You can see that the first way, where you select and insert in one statment, is a lot nicer and easier so if you don't do anything else with the array then I highly recommend doing it that way.
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 an array that grabs checkbox data and posts certain information into the database if the checkbox data isn't a copy of something already in the database. What I would like to know is how can I create a code that scans through the database and finds data that wasn't part of my checkbox data and delete it from the database.
Okay, for example let's say I have values 1,2,3,4 in my database, but in my checkboxes I only get back 1,2,4. I would like a code that scans my database and deletes that value(s) (in this case 3) from the database.
Here is my current code:
foreach($_POST['publish'] as $index => $val){
$matches = mysql_query("SELECT * FROM `$blog_table` WHERE `postID` = '$val");
if (mysql_num_rows($matches) > 0)
{
// do nothing
} else {
$query3 = "insert into `$blog_table`
(`postID`)values
('$val')";
mysql_query($query3);
}
}
Here would be the code I would use with escaped input
if (!empty($_POST['publish']))
{
$inserts = array();
$deletes = array();
foreach ($_POST['publish'] as $val)
{
$deletes[] = intval($val);
$inserts[] = '('.intval($val).')';
}
$delete = "DELETE FROM `".$blog_table."` WHERE postID NOT IN (".implode(',',$deletes).");";
$insert = "INSERT INTO `".$blog_table."` (`postID`) VALUES ".implode(',',$inserts)."";
}
you should use query like this:
delete from table where id NOT in (3)
in php like:
$query = "DELETE FROM `$blog_table` WHERE `postID` NOT IN (" . implode(',', $array) . ")";
For the MySQL query, you can use NOT IN:
DELETE FROM tablename
WHERE col1 NOT IN (1, 2, 4)