I'm trying to insert data's(multiple records) into table with php loop.
This the code :
<?php
$array = array('blue','red','green','yellow','black','white','blue','green');
$array = array_values(array_unique($array)); // remove duplicate and re-index array also
$vals = array_count_values($array);
print_r($array);
?>
And out put will look like :
Array ( [0] => blue [1] => red [2] => green [3] => yellow [4] => black [5] => white )
Now I want to insert the output into my table(colours) with this code :
<?php
for($i = 0; $i < count($vals); $i++){
$query = "INSERT INTO colours VALUES('$array[$i]');";
mysql_connect('localhost','root','');
mysql_query($query);
}
?>
What am I doing wrong?
There are several things you need to correct here. The first, is to address the fact that you're not specifying a database, like this:
$conn = mysql_connect('localhost','root','');
$db = mysql_select_db('YourDataBaseHere', $conn);
I assume if you've already created a table, then it must live in some database that you've already created.
Second, I think your query may need some correcting. You are not specifying any column names for your test table. Third, you shouldn't be running queries in a loop. Instead, you can try building a query that does multiple inserts with a single request, like this:
$sql = "INSERT INTO colours (`color`) VALUES ('" . implode("'),('", $array) . "')";
mysql_query($sql, $conn);
For the intents and purposes of your particular use case, you do not even need a looping structure because the entire array's values are imploded into a string to form the final query, as shown. This will insert multiple rows for all your colors. This strategy may not be advisable for ultra-large arrays. I advise that you separately look up how to do multiple inserts with a single query using MySQL/PHP. Then the $sql line might make more sense to you.
Fourth, your original, unedited question used a table called "test" so I'm going to assume you're not in a production environment. Regardless, I would advise putting a password for your root admin account instead of leaving it blank. It's just good practice.
Also, read this: Why shouldn't I use mysql_* functions in PHP?
You probably want to do something a bit like this, specifying the column name you are inserting into for the colors table.
$conn = mysql_connect('localhost', 'root', '');
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
for($i = 0; $i<$vals; $i++) {
$sql="INSERT INTO colors (Column_Name) VALUES ('$array[$i]');";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
That should get you on the right track.
You can do it without using for loop.
you query will be.
$array = array('blue','red','green','yellow','black','white','blue','green');
$array = array_values(array_unique($array));
$query = "INSERT INTO test VALUES ('".implode("'),('",$array)."');";
Your code should be like
mysql_connect('localhost','root',''); //put this line at the start
mysql_select_db("your db name"); //and add this line after it
$array = array('blue','red','green','yellow','black','white','blue','green');
$array = array_values(array_unique($array)); // remove duplicate and re-index array also
$arr_str = implode("'),('",$array);
$sql_query = "INSERT INTO `test` (`colours`) VALUES ('".$arr_str."')";
mysql_query($sql_query);
Related
For days I've been trying the following: I have a HTML form. After receiving the data (MENGE / PRODUKT / LIEFERANT) I want to insert the data into the table "bestellung". For this purpose, I need two different data points from two different tables: the Waren_ID from the WARE table and the kunde_lieferant_ID from the kunde_lieferant table.
Every time I try this, I get a new error in whatever form (syntax, ...). I've read dozens of Stack Overflow posts, but none helped me out. It would be great if someone could give me a hint :-)
<?php
$server="localhost";
$username="xy";
$passwort="xy";
$database="xy";
$conn=mysqli_connect($server, $username, $passwort, $database)
or die ("Fehler im System");
if (!empty($_POST["Lieferant"]) AND !empty ($_POST["Produkt"]) AND !empty ($_POST["Menge"]))
{
$Menge = $_POST ["Menge"];
$Produkt = $_POST["Produkt"];
$Lieferant = $_POST ["Lieferant"];
$sql="SELECT Waren_ID FROM ware WHERE Name='$Produkt'";
$speichern = mysqli_query($conn, $sql);
$rs = mysqli_fetch_array($speichern);
$Waren_ID=$rs['Waren_ID'];
$abfrage="SELECT kunde_lieferant_ID FROM kunde_lieferant WHERE Name='$Lieferant'";
$result = mysqli_query($conn, $abfrage);
$ts = mysqli_fetch_array($result);
$kunde_lieferant_ID=$ts['kunde_lieferant_ID'];
$final="INSERT INTO bestellung (Menge, Waren_ID, kunde_lieferant_ID) values ($Menge, $Waren_ID, $kunde_lieferant_ID)";
$ende=mysqli_query($conn, $final)
or die ("Fehlgeschlagen: SQL-Error:" . mysqli_error($conn));
}
mysqli_close($conn);
?>
Add MYSQLI_ASSOC as a second argument to mysqli_fetch_array() to use the key name instead of the integer index number:
$rs = mysqli_fetch_array($speichern); becomes $rs = mysqli_fetch_array($speichern, MYSQLI_ASSOC);
and
$ts = mysqli_fetch_array($result); becomes $ts = mysqli_fetch_array($result, MYSQLI_ASSOC);
You may also use $rs = mysqli_fetch_assoc($speichern); and $rs = mysqli_fetch_assoc($speichern); to access the associative array by key name instead of index.
One potential problem in your insert statement is that you are not single-quoting the values that your are passing : to MySQL, this means that they are all numeric (but is « Menge » numeric for example ?).
To avoid this and also prevent your code from SQL injection, you probably should use parameterized queries.
By looking more globally at your code, I think that you should be able to achieve what you want in a single INSERT ...SELECT statement, like :
INSERT INTO bestellung
SELECT
:menge,
w.Waren_ID,
k.kunde_lieferant_ID
FROM
ware w
INNER JOIN kunde_lieferant k
ON k.Name = :lieferant
WHERE w.Name = :produkt
Here i have made a function to produce random key,
function gen_link(){
$link = '';
$s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for ($i= 0 ; $i <= 4 ; $i++)
$link = $link.$s[rand(0,63)];
return $link;
}
I dont want to repeat the key in mysql table, i have made it unique in mysql, but what i want to do is, when the key already exists i want to regenerate another random key and try to add it to table again, i tried this code below.
$con = mysqli_connect("localhost","shashi","asd123","redir");
$sql = " insert into 'links' ('link') values('$link') ";
do{
$link = gen_link();
$result = mysqli_query($con,$sql);
}while(mysqli_errno($con)==1064);
mysqli_close($con);
but it doesn't seem to work at all, it keeps looping. what can i do?
Instead of generating an actual error, use an INSERT IGNORE query like this:
$sql = "insert ignore into `links` (`link`) values ('$link')";
And check mysqli_affected_rows() to ensure something was actually inserted:
while (mysqli_affected_rows($con) == 0);
All together, that looks like this:
$con = mysqli_connect("localhost", "shashi", "asd123", "redir");
do {
$link = gen_link();
$sql = "insert ignore into `links` (`link`) values ('$link')";
$result = mysqli_query($con, $sql);
} while (mysqli_affected_rows($con) == 0);
mysqli_close($con);
Also, a couple notes about your queries:
I changed your quotes around the table and column names to backticks, which is the correct way to quote them in sql.
Because you're including the $link variable directly in the query, you need to define your query after you give the $link variable a value - so I moved that line inside the loop. This is probably the source of your original problem where you kept looping.
It's not important in this instance because you have full control of the value you're inserting (generated in gen_link()), but it's a good idea to get in the habit of properly escaping the variables you insert into a query. Alternatively, read up a bit on prepared statements, and use them instead.
Get the existing key values from the DB as array. Then search your current key with your existing keys using in_array() function. If it is true generate new key. If the condition is false , insert your new key.
http://php.net/manual/en/function.in-array.php
if(in_array($new_key,$existing))
{
//generate new key
}
else
{
//insert current key
}
I'm working with Prepared Statement an using "ON DUPLICATE KEY", to change the duplicate Value with MYSQL:
$sql = "INSERT INTO ".$this->table." ".
"(".implode(',',$fields).") VALUES
(".implode(',',$values).")
ON DUPLICATE KEY
UPDATE key_field = concat(substr(key_field,1,".($laenge_key-3)."),FORMAT(FLOOR(RAND()*999),0))
I have a question on how to go about the next phase of a project I am working on.
Phase I:
create a php script that scraped directory for all .txt file..
Open/parse each line, explode into array...
Loop through array picking out pieces of data that were needed and INSERTING everything into the database (120+ .txt files & 100k records inserted)..
this leads me to my next step,
Phase II:
I need to take a 'list' of several 10's of thousand of numbers..
loop through each one, using that piece of data (number) as the search term to QUERY the database.. if a match is found I need to grab a piece of data in a different column of the same record/row..
General thoughts/steps I plan to take
scrape directory to find 'source' text file.
open/parse 'source file'.... line by line...
explode each line by its delimiting character.. and grab the 'target search number'
dump each number into a 'master list' array...
loop through my 'master list' array.. using each number in my search (SELECT) statement..
if a match is found, grab a piece of data in another column in the matching/returned row (record)...
output this data.. either to screen or .txt file (havent decided on that step yet,..most likely text file through each returned number on a new line)
Specifics:
I am not sure how to go about doing a 'multiple' search/select statement like this?
How can I do multiple SELECT statements each with a unique search term? and also collect the returned column data?
is the DB fast enough to return the matching value/data in a loop like this? Do I need to wait/pause/delay somehow for the return data before iterating through the loop again?
thanks!
current function I am using/trying:
this is where I am currently:
$harNumArray2 = implode(',', $harNumArray);
//$harNumArray2 = '"' . implode('","', $harNumArray) . '"';
$query = "SELECT guar_nu FROM placements WHERE har_id IN ($harNumArray2)";
echo $query;
$match = mysql_query($query);
//$match = mysql_query('"' . $query . '"');
$results = $match;
echo("<BR><BR>");
print_r($results);
I get these outputs respectively:
Array ( [0] => sample_source.txt )
Total FILES TO GRAB HAR ID's FROM: 1
TOAL HARS FOUND IN ALL FILES: 5
SELECT guar_nu FROM placements WHERE har_id IN ("108383442","106620416","109570835","109700427","100022236")
&
Array ( [0] => sample_source.txt )
Total FILES TO GRAB HAR ID's FROM: 1
TOAL HARS FOUND IN ALL FILES: 5
SELECT guar_nu FROM placements WHERE har_id IN (108383442,106620416,109570835,109700427,100022236)
Where do I stick this to actually execute it now?
thanks!
update:
this code seems to be working 'ok'.. but I dont understand on how to handle the retirned data correctly.. I seem to only be outputting (printing) the last variable/rows data..instead of the entire list..
$harNumArray2 = implode(',', $harNumArray);
//$harNumArray2 = '"' . implode('","', $harNumArray) . '"';
//$query = "'SELECT guar_num FROM placements WHERE har_id IN ($harNumArray2)'";
$result = mysql_query("SELECT har_id, guar_num FROM placements WHERE har_id IN (" . $harNumArray2 . ")")
//$result = mysql_query("SELECT har_id, guar_num FROM placements WHERE har_id IN (0108383442,0106620416)")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array($result);
$numRows = mysql_num_rows($result);
/*
while($row = #mysql_fetch_assoc($result) ){
// do something
echo("something <BR>");
}
*/
// Print out the contents of the entry
echo("TOTAL ROWS RETURNED : " . $numRows . "<BR>");
echo "HAR ID: ".$row['har_id'];
echo " GUAR ID: ".$row['guar_num'];
How do I handle this returned data properly?
thanks!
I don't know if this answers your question but I think you're asking about sub-queries. They're pretty straightforward and just look something like this
SELECT * FROM tbl1 WHERE id = (SELECT num FROM tbl2 WHERE id = 1);
That will only work if there is one unique value to that second subquery. If it returns multiple rows it will return a parse error. If you have to select multiple rows research JOIN statements. This can get you started
http://www.w3schools.com/sql/sql_join.asp
I am not sure how to go about doing a 'multiple' search/select statement like this?
With regards to a multiple select, (and I'll assume that you're using MySQL) you can perform that simply with the "IN" keyword:
for example:
SELECT *
FROM YOUR_TABLE
WHERE COLUMN_NAME IN (LIST, OF, SEARCH, VALUES, SEPARATED, BY COMMAS)
EDIT: following your updated code in the question.
just a point before we go on... you should try to avoid the mysql_ functions in PHP for new code, as they are about to be deprecated. Think about using the generic PHP DB handler PDO or the newer mysqli_ functions. More help on choosing the "right" API for you is here.
How do I handle this returned data properly?
For handling more than one row of data (which you are), you should use a loop. Something like the following should do it (and my example will use the mysqli_ functions - which are probably a little more similar to the API you've been using):
$mysqli = mysqli_connect("localhost", "user", "pass");
mysqli_select_db($mysqli, "YOUR_DB");
// make a comma separated list of the $ids.
$ids = join(", ", $id_list);
// note: you need to pass the db connection to many of these methods with the mysqli_ API
$results = mysqli_query($mysqli, "SELECT har_id, guar_num FROM placements WHERE har_id IN ($ids)");
$num_rows = mysqli_num_rows($results);
while ($row = mysqli_fetch_assoc($results)) {
echo "HAR_ID: ". $row["har_id"]. "\tGUAR_NUM: " . $row["guar_num"] . "\n";
}
Please be aware that this is very basic (and untested!) code, just to show the bare minimum of the steps. :)
I have multiple arrays which I am passing to a file sales_process.php on the form submit action. The arrays are named like this : boards1 = {a , b , c}, boards2 = {b , c , d}, boards3 = {a , c , d} . . and so on (The values are not a,b,c,d). I am passing them through multiple 'multiple select boxes' in my form like this where a,b,c,d are my multiple select options :
for ($count=1;$count<10;$count++)
echo "<td>"."<select name='boards".$count."[]' multiple='multiple'>".showOptionsDrop($boards,$arr)."</select></td>";
Now when i pass them to the file sales_process.php, i want to convert these arrays into strings using implode function so that i can store them into my 'schools' table. In sales_process.php file, I am doing this:
for ($i=0;$i<$count;$i++) {
$board = implode(',',${'boards'.$i});
$query = "UPDATE schools SET board = '$board' where schoolcode = (some_no)";
$result = mysql_query($query) or die("Error in updating table :".mysql_error());
}
So in this way, every time my loop runs, the values of boardsX gets converted into string and gets stored in the table, where X is 1,2,3.... and so on.
The problem is the implode function is not working and giving error :
Warning: implode() [function.implode]: Invalid arguments passed in C:\xampp\htdocs\relationshipReport\sales_process.php on line 18
Now if you say that the variable ${'boards'.$i} is not an array, i did this and found out that its giving me an array only :
$i=1;
var_dump(${'boards'.$i});
print_r(${'boards'.$i});
which gives the output as :
array(3) { [0]=> string(4) "CBSE" [1]=> string(4) "ICSE" [2]=> string(5) "IGCSE" }
Array ( [0] => CBSE [1] => ICSE [2] => IGCSE )
I hope my question is clear. Please help me in finding out whats going wrong in the implode function. If you don't understand the question, please mention it.
From your examples, I believe this is your current code:
for ($i=0;$i<$count;$i++) {
$board = implode(',',${'boards'.$i});
$query = "UPDATE schools SET board = '$board' where schoolcode = (some_no)";
$result = mysql_query($query) or die("Error in updating table :".mysql_error());
}
If so, try altering it so it looks like this:
for ($i=0;$i<$count;$i++) {
if(isset($_POST['boards'.$i]))
{
$board = mysql_real_escape_string(implode(',',$_POST['boards'.$i]));
$query = "UPDATE schools SET board = '$board' where schoolcode = (some_no)";
$result = mysql_query($query) or die("Error in updating table :".mysql_error());
}
else
{
echo '$_POST[\'boards' . $i . '\'] doesn\'t exist or is null.<br>';
}
}
This contains an if condition, checking that the array entry actually exists. If it does exist, it runs the query. If it doesn't, it echos back a message, telling you which one doesn't exist.
Even if you have confirmed at the frontend with Javascript, you should always check before running code, just to be sure it won't break it. You can never be too safe, especially if your code contains sensitive information.
Try this, and let me know how you go.
Assume ${'boards'.$i} comes from $_POST['boards'.$i]. (If not, you are using register_globals, but that is not good.)
For multiple select, if no options is selected, then $_POST['boards'.$i] will give you null instead of an array.
I have a 1 dimensional array of strings ($answers). I want to store each string as a new record a long with an itemId (the same itemId for each answer) into my table "answers_tb".
I have tried.....
using a foreach to construct a new array 2 dimensional array, with the $answers array and the itemID and then imploding this new array into my query.
not working.
i get this error:
Column count doesn't match value count at row 1
here is my code:
$records = array();
foreach($answers as $item_id => $text_value) {
$records[] = '("' . $item_id . '","' . $text_value . '")';
}
$sql = "INSERT INTO answers_tb (item_id, text_value) VALUES('" . implode(',', $records)." ')";
mysql_query($sql) or die(mysql_error());
many thanks for getting this far, even if you cant help.
regards,
Aside from particular problem, just to teach you a lesson.
You are working on your task in wrong way, upside down.
To put it straight, you're writing a program that builds some text.
So, first of all, it would be extremely handy to know, what particular text you want to get as a result. Thus, you have to write desired SQL query by hand and run in SQL console to see if it works okay or has any errors. If you experience any problem on this stage, you may ask under mysql tag, what query you need.
The rest is going to be easy. Upon finishing your program just print it's result out, and compare with example you've got before. Then correct your code to make them match. Repeat.
Done.
Always do your job this way and you will have no problem.
This should work:
$records = array ();
$itemid = 3; // or any arbitrary value
foreach ($answers as $text_value) {
$records[] = '("' . $itemid . '","' . $text_value . '")';
}
$sql = "INSERT INTO answers_tb (item_id, text_value) VALUES " . implode(',', $records);
mysql_query ($sql)
or die (mysql_error ());
With your current solution you create a query like:
INSERT INTO answers_tb (item_id, text_value) VALUES (('1', 'asd'),('2', 'bsd'))
It shoould look like:
INSERT INTO answers_tb (item_id, text_value) VALUES ('1', 'asd'),('2', 'bsd')
So you don't need the extra parens.