complicated query entry mysql php - php

I'm having great trouble with "INSERT INTO"...
I have a variable part number so this my code...:
<?php
include ("db_conn.php");
$mem_id = "1";
$descript = "chair";
$qualifier = "sitting";
$major = "Y";
$value = "6";
//$mesh_cell_string = "tree_0,tree_1,tree_2,tree_3,tree_4";
//$mesh_values_string = "'C23','550','291','687','500'";
$part_number = "C23.550.291.687.500";
$parts = explode('.', $part_number);
$n = 0;
foreach ($parts as $something => $number)
{
$mesh_cell_string .= "tree_" . $n . ",";
$mesh_values_string .= "'" . $number . "'," ;
$n++;
}
$mesh_values_string = substr($mesh_values_string, 0, -1);
$mesh_cell_string = substr($mesh_cell_string, 0, -1);
$insert_string = "mem_id,mesh_heading_name," . $mesh_cell_string . ",qualifier_name,major,rank";
$values_string = "'$mem_id','$descript'," .$mesh_values_string. ",'$qualifier','$major','$value'";
$sql = "INSERT INTO mesh_table (" . $insert_string .") VALUES (" . $values_string .")";
$result = mysqli_query($cxn,$sql) or die ("couldn't execute the query");
?>
The strange thing is... i don't get an error ("couldn't execute the query") so i thought it went alright but when i look into my database there aren't any values written... when i un-comment the the 2 variables:
//$mesh_cell_string = "tree_0,tree_1,tree_2,tree_3,tree_4";
//$mesh_values_string = "'C23','550','291','687','500'";
And comment the foreach loop, it works...? So there goes something wrong in the foreach loop, but when i echo the $sql on both methods i get the same:
INSERT INTO mesh_table (mem_id,mesh_heading_name,tree_0,tree_1,tree_2,tree_3,tree_4,qualifier_name,major,rank) VALUES ('1','Chair','C23','550','291','687','500','sitting','Y','6')
I really don't know what i am doing wrong...?
Best regards,
Thijs

change $values_string = "'$mem_id','$descript'," .$mesh_values_string. ",'$qualifier','$major','$value'";
To
$values_string = "'".$mem_id."','".$descript."'," .$mesh_values_string. ",'".$qualifier."','".$major."','".$value."'";

Related

Dynamic amount of bindParam

So I am trying to make an undetermined amount of bindParam calls within a foreach, but for some reason it fails. I know the $sql variable is working fine, but I am pretty sure it is failing at the bindParam. Is there any reason for this?
$sql = "INSERT INTO " . $row1["rand"] . " (" . $areas . ") VALUES (" . $vals . ")";
echo $sql;
$entry2 = $conn->prepare("'".$sql."'");
//echo "swag";
foreach($splitHeader as $element){
if(strlen($element)>0) {
$thisVal = "':" . $element . "'";
$entry2->bindParam($thisVal,$_POST[$element]);
}
}
$entry2->execute();
The number of parameters that you define in the query must match the number of parameters that you bind.
You would need to loop twice trough your data : once to dynamically construct a sql statement (that you can then prepare), and then a second time to bind the parameters, before finally calling execute.
Here is an adaptation of your code that demonstrates the principle :
$cols = "";
$vals = "";
foreach( $splitHeader as $element ) {
if( strlen($element) > 0 ) {
if ( strlen($cols) > 0 ) {
$cols .= ", ";
$vals .= ", ";
}
$cols .= $element;
$vals .= "?";
}
}
$sql = "INSERT INTO " . $row1["rand"] . " (". $cols . ") VALUES(". $vals . ")";
echo $sql;
$sth = $conn->prepare($sql);
$i = 1;
foreach($splitHeader as $element){
if( strlen($element) > 0 ) {
$sth->bindParam( $i, $_POST[$element] );
$i++;
}
}
$sth->execute();

Importing text file into MySQL php program

I have a code that I took from https://www.howtoforge.com/community/threads/importing-text-file-into-mysql.7925/ and changed to what I needed it for but when I run the program it doesn't import the data into the database
Text file
GeoID|X|Y|Wood|Clay|Iron|Stone|Food|TerrainSpecificTypeID|TerrainCombatTypeID|RegionID
7025277|279|-1321|0|0|0|0|0|62|14|31
7025278|279|-1320|0|0|0|0|0|62|14|31
7025279|279|-1319|0|0|0|0|0|62|14|31
7025280|279|-1318|0|0|0|0|0|62|14|31
7025281|279|-1317|0|0|0|0|0|62|14|31
7025282|279|-1316|0|0|0|0|0|62|14|31
7025283|279|-1315|0|0|0|0|0|62|14|31
7025284|279|-1314|0|0|0|0|0|62|14|31
7025285|279|-1313|0|0|0|0|0|62|14|31
7025286|279|-1312|0|0|0|0|0|62|14|31
PHP code that i am currently using
<?php
// Set Mysql Variables
$username = "root";
$auth = 'i-have-removed-it';
$db = mysql_connect("localhost", $username, $auth);
mysql_select_db("testdb",$db);
$file = "/tmp/map_datafile_test.txtt";
$fp = fopen($file, "r");
$data = fread($fp, filesize($file));
fclose($fp);
$output = str_replace("\t|\t", "|", $data);
$output = explode("\n", $output);
$language_id = "1";
$categories_id = 0;
foreach($output as $var) {
$categories_id = $categories_id + 1;
$tmp = explode("|", $var);
$GeoID = $tmp[0];
$X = $tmp[1];
$Y = $tmp[2];
$Wood = $tmp[3];
$Clay = $tmp[4];
$Iron = $tmp[5];
$Stone = $tmp[6];
$Food = $tmp[7];
$TerrainSpecificTypeID = $tmp[8];
$TerrainCombatTypeID = $tmp[9];
$RegionID = $tmp[10];
echo " categories_id: " . $categories_id . " Artikelgroep: " . $Artikelgroep . "<br>";
$sql = "INSERT INTO `World_Map`(`GeoID`, `X`, `Y`, `Wood`, `Clay`, `Iron`, `Stone`, `Food`, `TerrainSpecificTypeID`, `TerrainCombatTypeID`, `RegionID`) VALUES ('$GeoID','$X','$Y','$Wood','$Clay','$Iron','$Stone','$Food','$TerrainSpecificTypeID ','$TerrainCombatTypeID ','$RegionID')" or die("Insert failed: " . mysql_error());
mysql_query($sql);
}
echo "Done!";
?>
You need to set the variables $GeoID, $X, $Y, $Wood, $Clay, ...
In the foreach loop you get each line of the file, and in $tmp you get each column. So $GeoID should be $tmp[0], $X should be $tmp[1] and so on.

SQL update with PHP arrays

Let's say i have and array like this
$array= Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
Keys from this array are name of columns in table and values are value of columns which i need to update.
I want to update the table based on keys and values.
I am using ADODB
Please help me
try this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
$sql .= $key . " = " . $value . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
and of course the WHERE clause:
$sql .= " WHERE condition = value";
you will get the string:
UPDATE table SET id = 3, name = NAME, age = 12 WHERE condition = value
L.E: You might need to add apostrophes to strings so I have to change my code to something like this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
if(is_numeric($value))
$sql .= $key . " = " . $value . ", ";
else
$sql .= $key . " = " . "'" . $value . "'" . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
$sql .= " WHERE condition = value";
which will produce this:
UPDATE table SET id = 3, name = 'NAME', age = 12 WHERE condition = value
L.E 2: If you want the id column in your condition, the code becomes this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
if($key == 'id'){
$sql_condition = " WHERE " . $key . " = " . $value;
continue;
}
if(is_numeric($value))
$sql .= $key . " = " . $value . ", ";
else
$sql .= $key . " = " . "'" . $value . "'" . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
$sql .= $sql_condition;
which will produce this result:
UPDATE table SET name = 'NAME', age = 12 WHERE id = 3
Hope this helps! :D
foreach ($update_array as $key => $testimonials) {
$name = mysql_real_escape_string($testimonials->name);
$content = mysql_real_escape_string($testimonials->content);
$id = intval($testimonials->id);
$sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id=$id";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error());
}
}
Source : https://stackoverflow.com/a/7884331/3793639
Other sources to check.
PHP SQL Update array and Simple UPDATE MySQl table from php array
You could use something like this for achieving that:
foreach($values as $value) {
if(!key_exists($value, $item)) {
return false;
}
$table->{$value} = $items[$value];
}
Assuming that the key index is always id and that adodb can use named placeholders you could do this:
$array = Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
$set = array();
$data = array();
while(list($key,$value)=each($array)) {
$data[':'.$key] = $value;
if($key!='id') {
$set[] = $key . ' = :' . $key;
// if no placeholders use $set[] = $key . " = '" . database_escape_function($value) . "'";
}
}
$sql = "UPDATE table SET ".implode($set, ',')." WHERE id=:id";
//$data is now Array(':id'=>'3', ':name'=>'NAME', ':age'=>'12');
//$sql is now "UPDATE table SET name=:name, age=:age WHERE id=:id";
$stmt = $DB->Prepare($sql);
$stmt = $DB->Execute($stmt, $data);
This is probably the shortest and easiest for you, you can also use something like this to achieve it:
$array = Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
$sql = "UPDATE table SET ";
$sql .= implode(', ', array_map(function($key, $value){
return is_numeric($value) ? "{$key} = {$value}" : "{$key} = '". mysql_real_escape_string($value). "'";
}, array_keys($array), $array));
$sql .= " WHERE id = 123";
// Result : UPDATE table SET id = 3, name = 'NAME', age = 12 WHERE id = 123

Insert an array in the database

I want to insert an array in the database. The array can be changed all the time. I want different rows in the database.
My code:
$var = file_get_contents("test2.txt");
$test = preg_replace('/\\\\/', '', $var);
$poep = explode(" ", $test);
Yeah, there is no database connection, because I want to know how to 'split' the array to insert it in the database.
I have tried this:
foreach($poep as $row) {
$row = $mysqli->real_escape_string($row);
if($mysqli->query("insert into data('array') VALUES ($row)") == false){
echo 'Doesnt works!';
}
It returns 'Doesnt works', so I think there is a problem with query?
#NadirDev Hi. Assuming that you are using Core PHP programming. After exploding the string by the space, run foreach loop and then insert individual rows. Look at this rough code to get idea:
foreach($poep as $row) {
// $row now contains one word. Add that in database.
$row = mysql_real_escape_string($row);
$query = mysql_query("insert into tableName('fieldName') VALUES ($row)");
}
here's some code I wrote. It processes a CSV file and stores separate rows into a db table (difference is just that you have a TXT file). It does the mysql insertion in batches of 250 rows. Hope it can help you!
// read all input rows into an array
echo "Processing input..<br /><br />";
$row = 0;
$input = array();
if (($handle = fopen($file['tmp_name'], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$input[$row][] = addslashes($data[$c]);
}
$row++;
}
fclose($handle);
}
$count = 0;
$q = "INSERT INTO `inputs` (`keyword`, `percent`, `link`, `added_on`) VALUES ";
foreach ($input as $inp) {
$q .= "('" . addslashes($inp[0]) . "', '" . addslashes($inp[1]) . "', '" . addslashes($inp[2]) . "', '" . date('Y-m-d H:i:s') . "'), ";
$count++;
if ($count >= 250) {
$q = substr($q, 0, -2);
$q = mysqli_query($con, $q);
$q = "INSERT INTO `inputs` (`keyword`, `percent`, `link`, `added_on`) VALUES ";
$count = 0;
}
}
if ($count > 0) {
$q = substr($q, 0, -2);
$q = mysqli_query($con, $q);
}
echo "Successfully added " . count($input) . " rows to the input list.";

Create and insert variables into mysql from for loop using php

I want to create an array or variables that can be inserted into the sql query instead of do it manually like in my code below.
Is this possible with the simple php, not using PDO, just some kind of trick that will solve this issue.
You can see that I manually inserted 10 columns and 10 values, can I do it shorter?
So, I want to have a variable/array that will consist pt1-pt10 and another that will be consisted of a[1]-a[10].
for($j=1;$j<11;$j++) {
$a[$j] = "";
}
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'my_db';
$table = 'jos_answers';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("INSERT into ".$table."(id, title, pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8, pt9, pt10) VALUES ((select id from jos_content where title='$title'),'$title','$a[1]','$a[2]','$a[3]','$a[4]','$a[5]','$a[6]','$a[7]','$a[8]','$a[9]','$a[10]')");
?>
for($j=1;$j<11;$j++) {
$a["pt".$j] = $j;
}
"INSERT into ".$table. "(id, title,".implode(",", array_keys(a)).") VALUES ((select id from jos_content where title='$title'),'$title',".implode(",", array_values(a)).")";
Try this:
$insert = "INSERT INTO" . $table . "(id, title,";
$value = " VALUES((select id from jos_content where title='$title'),'$title',";
for($x = 1; $x < 11; $x++){
$insert .= " pt" . $x . ",";
$value .= " '$a[" . $x . "]'," //this line is iffy....
}
$insert = substr($insert, 0, -1);//to remove last comma
$value = substr($value, 0, -1);//to remove last comma
$insert .= ")";//final paren
$value .= ")";//final paren
$sql = $insert . $value; //combine parts
$result = mysql_query($sql);
The reason I think that line is iffy is becuase the ' ' surronding the varibles kinda confuses me. Do you want the varibles value to be inserted to the DB? If so I would go with this line instead:
$values .= " " . $a[$x] . ",";
If you want the ' and the values go with this:
$values .= " '" . $a[$x] . "',";
Here is a working example of the code edited a bit obviously because it is not in your SQL environment and you did not give us all the variable values: http://viper-7.com/cDAcRl
Good Luck!

Categories