I am trying to write a php script that take a text file break down its contents and and insert it into a MySql database, the code is as follows:
$file = "my_file.txt";
$db = "db_name";
$link = mysql_connect("localhost","root");
if(!$link) die("Connection Failed");
mysql_select_db($db) or die("Could not open $db: ".mysql_error()."<br />");
$fp = fopen($file, 'r') or die("Could not open file");
$my_filesize = filesize($file);
while(!feof($fp)) {
$prod_doc.=fread($fp, $my_filesize); // store the file in a variable
}
$prod_array = explode("~",$prod_doc); // create a array with the explode function
for($i=0; $i<count($prod_array); $i++){
$prod_items[$i] = explode(',', $prod_array[$i]); // create a malti-dimensional array
}
$query = "INSERT INTO my_table(feild1, feild two, feild three)
VALUES ('$prod_items[$i][0]','$prod_items[$i][1]','$prod_items[$i][2]')
";
$result = mysql_query($query);
if(!$result) die(mysql_error());
$result = mysql_affected_rows($result);
echo $result;
mysql_close($link); `
My problem is this: Array[0], Array[1], Array[3] is what is entered into the database instead of my data. Thanks in advance, cheers.
To access array variable element values used inside a double-quote string need braces delimiters:
"'{$prod_items[$i][0]}','{$prod_items[$i][1]}','{$prod_items[$i][2]}') ";
Another way to code this is by concatenation (in which case you don't need the extra delimiters):
"'" . $prod_items[$i][0] . "','" . $prod_items[$i][1] . "','" . $prod_items[$i][2] . "') ";
Don't forget, if the input data is unpredictable, you need to filter out characters that can break your sequel or compromise security principles. SEE How can I prevent SQL injection in PHP?
Also, junmats's comment is correct, you are only running the query outside the for loop which doesn't make sense.
You have to iterate over your $prod_items array as well, then concate the values
$insert = array();
for($i=0; $i<count($prod_array); $i++){
$prod_items[$i] = explode(',', $prod_array[$i]); // create a malti-dimensional array
$insert[] = '( ' .$prod_items[$i][0]. ', '.$prod_items[$i][1]. ', '. $prod_items[$i][3] .')';
}
$insert_string = implode(', ', $insert);
$query = "INSERT INTO my_table(feild1, feild two, feild three)
VALUES" . $insert_string;
And you should use foreach insted of for.
Seems like you've skipped some code.
After explode you'll have array of strings, not 2d array.
Also it's better to update the code a bit.
$query = "INSERT INTO my_table(feild1, feild_two, feild_three) VALUES ('".$prod_items[$i][0]."','".$prod_items[$i][1]."','".$prod_items[$i][2]."') ";
You should use the standard concatenation(.) technique for this.
PHP can only evaluate simple variables inside a string:
"$var" --> var is evaluated
"$var->var" --> is not evaluated
"$var[0]" --> is not evaluated
$query = "INSERT INTO my_table(feild1, feild two, feild three)
VALUES ('".$prod_items[$i][0]."','".$prod_items[$i][1]."','".$prod_items[$i][2]".')
";
Related
I'm trying to create a function which checks if word in a string is in the DB.
So, for example, I have a list with basic words in my DB. I type a sentence and would like to get all the words from that sentence which are not yet in the DB.
Any tips on how to work this out?
First convert search string to an array using this function
$str = "Hello user how are you.";
$find_it = explode(" ",$str);
Now use mysql query to find if this exist in DB or NOT...
$filterExisting = "'" . implode("', '", $find_it ) . "'";
$sql = "SELECT * FROM table WHERE field NOT IN (". $filterExisting .")";
$result = $db->query($sql);
I am inserting data from a excel sheet but i receive error and it looks like it is breaking because the value contain a space character in between. As far as i remember space characters allowed in VARCHAR(200)
This is the code i am using
//CREATE SQL QUERY FOR INSERTING DATA IN DATABASE
$sql = "INSERT INTO ".$month."_".$year."(";
foreach($sheetData[1] as $columnName){
$sql .= preg_replace('#[ ]#', '_',$columnName). ",";
}
$sql = rtrim($sql, ',');//REMOVES COMMA FROM END OF THE STRING
$sql .= ")";
//
$sql .= " VALUES((";
for($i=2;$i < count($sheetData);$i++){
foreach($sheetData[$i] as $columnName){
$sql .= $columnName.",";
}
$sql = rtrim($sql,',');//
$sql .= "),";
}
$sql = rtrim($sql,',');//
$sql .= ")";
echo $sql;
$query = mysqli_query($conn,$sql) or die(mysqli_error($conn));
After loops this is how my SQL QUERY look
INSERT INTO December_2015(S_No,Zone,State,City2,VM_Town,Distibutor_Code,Distributor_Name,Dealer_Code,Dealer_Name,Category,Address,Location,Contact,Mobile_No,Visit_1,Visit_2,Visit_3,Visit_4,Visit_5,Visit_6) VALUES( (1,South,Telanagana,Hyderabad,Y,1006704,Sai Santhoshi Enterprises,TG000999,Sree Laxmi Mobiles,A,F4,anthem Arcade,gujarathi Galli,koti ,Koti,Rajesh,8790575680,7-Nov,18-Nov,28-Nov))
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 'Santhoshi Enterprises,TG000999,Sree Laxmi Mobiles,A,F4,anthem Arcade,gujarathi G' at line 1
It says near 'Santhoshi Enterprises ... ' before that there is a space character
You have two "(" instead of one after "VALUES"
Akash,
Didn't you asked a question just a while ago regarding same/similar code with a different error you got, here at: How to loop inside a variable ?!
By the looks of it in general you write messy code, and you are having trouble reading/understanding the error messages. So I'm gonna guess you are new at this.
Here are some good reads for you:
Top 15+ Best Practices for Writing Super Readable Code
PHP the right way
When all said and done, here is your code broken down into more readable segments:
// prepare dummy data
$month = date('M');
$year = date('Y');
$sheetData = array(
array('data00', 'data01')
,array('col1', 'col2', 'col3', 'col4', 'col5', 'col6')
,array('data20', "data21")
,array('data30', 'data31')
,array('data40', 'data41')
);
// prepare vars
$tableName = "{$month}_{$year}";
$dataCount = count($sheetData);
// prepare columns
$columnsSQL = "";
foreach ($sheetData[1] as $columnName) {
// wrap with ` ticks
$columnsSQL .= '`'. preg_replace('#[ ]#', '_', $columnName).'`'.',';
}
$columnsSQL = rtrim($columnsSQL, ',');
// prepare values
$valuesSQL = "";
for ($i=2;$i < $dataCount;$i++) {
foreach($sheetData[$i] as $columnValue){
$valuesSQL .= "'{$columnValue}', ";
}
}
$valuesSQL = rtrim($valuesSQL, ', ');
$SQL = "
INSERT INTO {$tableName}( {$columnsSQL} )
VALUES ( {$valuesSQL} )";
At the end you end up with something like this:
INSERT INTO Nov_2015( `col1`,`col2`,`col3`,`col4`,`col5`,`col6` )
VALUES ( 'data20', 'data21', 'data30', 'data31', 'data40', 'data41' )
Additional note and tips:
Considering that you said you are reading data from excel sheet... Never trust input data without some tests/checks/validation. Not just because of security but stability and in general you don't want things breaking.
Those excel tables could be manually made which automatically means its prone for human error, so you can't be always 100% sure what are you gonna get.
Consider using PDO and prepared statements (security reasons, but also good practice)
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);
if(isset($_POST['usersadded'])){
$value = $_POST['usersadded'];
$lines = explode("\n", $value);
foreach ($lines as $line) {
mysql_query("INSERT INTO Users_$support (Users) VALUES ('$line')");
};
I have a valid connection to the database already, so it's not that that's wrong. But it never submits anything :(
$support is a number, e.g. 19.
I would always suggest using this SQL syntax when inserting something with PHP variables inside.
mysql_query("
INSERT INTO
`table_name`
SET
`field` = '" . $field_variable . "'
");
The error might appear when you don't phrase your PHP variables correctly inside the query string.
Try this
mysql_query("INSERT INTO Users_$support (Users) VALUES (\"'\".$line.\"'\")");
I should be able to figure this out, but I keep going in circles. I have a form with checkboxes. When the checkboxes are selected they tagged to be deleted.
I process those selected checkboxes with a foreach:
foreach (array_keys($_POST['checkboxselect']) as $k) {
$str .= $k.',';
}
This is my lame attempt to put the list of videos together. The sql delete I'm using is:
DELETE FROM `videos` WHERE `video_name` IN ($str)
So I'm missing lots of things here. The $str needs to have:
Only one checkbox is returned so return string with quotes (i.e. "myvideo.mp4")
Multiple checkboxes are selected so build a string with quotes and commas (i.e. "myvideo.mp4","myvideo2.mp4","myvideo3.mp4")
Thanks for the help.
Try using PHP's implode:
// Init links
$mysqliLink = mysqli_connect('host', 'user', 'password') or die('Could not connect: ' . mysqli_error());
$mysqlLink = mysql_connect('host', 'user', 'password') or die('Could not connect: ' . mysql_error());
//-----
// Prep values for query
//-----
// Only pick one of the following depending upon the mysql library you are using
// If using mysql, passing the 2nd argument is not necessary, but for
// clarity, adding it
$deleteNames = array_map('mysql_real_escape_string', array_keys($_POST['checkboxselect']), array_fill(0, count($_POST['checkboxselect']), $mysqlLink));
// If using mysqli
// This will ensure that $mysqliLink will be passed in as first arg for
// every iteration satisfying the function signature
$deleteNames = array_map('mysqli_real_escape_string', array_fill(0, count($_POST['checkboxselect']), $mysqliLink), array_keys($_POST['checkboxselect']));
//-----
// Because you are passing strings, we need to ensure each is wrapped in quotes
$deleteNames = "'" . implode("','", $deleteNames) . "'";
// Construct query using implode
$sql = sprintf('DELETE FROM `videos` WHERE `video_name` IN (%s)', $deleteNames);
-- Update --
Using Joomla APIs:
$db = &JFactory::getDBO();
// Localize and sanitize each individual value
foreach (array_keys($_POST['checkboxselect']) as $element) {
$deleteNames[] = $db->quote($element);
}
// Because you are passing strings, we need to ensure each is wrapped in quotes
// No longer true because $db->quote taking care of quoting out each name for us
$deleteNames = implode(',', $deleteNames);
// Construct query using implode
$sql = sprintf('DELETE FROM `videos` WHERE `video_name` IN (%s)', $deleteNames);
Use implode() like this:
$str = '"' . implode('","', array_keys($_POST['checkboxselect'])) . '"';
implode() will take an array and join each value in the array with the "glue" string. In this case the "glue" is "," and the array is composed of the keys in $_POST['checkboxselect']. Finally, the resulting string is wrapped in ".
This will result in your desired example string "myvideo.mp4","myvideo2.mp4","myvideo3.mp4".