array set as a column name from an array using php mysql - php

I have an foreach loop that is creating a table with new column names from an array collected from a site. At the moment only the first element of the array is being set as a column name, can someone help?
H
Here is my code:
<?php
include 'simple_html_dom.php';
include 'connection.php';
function getsquad($url, $tablename){
$html = file_get_html($url);
$player_fromsite = array();
$space = ' ';
$replacespace = '_';
$player = array();
foreach($html->find('td[align=left]') as $element) {
if ($element->children(0)) { // work only when children exists
array_push($player_fromsite ,$element->children(0)->innertext);
}
}
//$player[] = str_replace($space, $replacespace, $player_fromsite);
//unset($player_fromsite);
$length = count($player);
foreach($player_fromsite as $player_name) {
mysql_query("CREATE TABLE " . $tablename . "(" . str_replace($space, $replacespace, $player_name) . " VARCHAR(30))") or die(mysql_error());
}
echo "Table Created!";
}
$Squad = new squad();
$Squad->getsquad('site', 'Ars');
?>
any spaces are replace with a "_", in the foreach loop

I am not quite sure if I correctly understand what you want: In $player_fromsite you have some strings, which should become columns of the new table with the name from $tablename, whereas all columns are VARCHAR(30).
If so, replace your last foreach loop with the following:
$columns = array();
foreach ($player_fromsite as $player_name) {
$columns[] = '`' . str_replace($space, $resplacespace, $player_name) . '` VARCHAR(30)';
}
$query = 'CREATE TABLE `' . $tablename . '` (' . implode(',', $columns) . ')';
mysql_query($query) or die(mysql_error());
The foreach loop basically prepares all the columns, which afterwards get concatenated to the actual query which is send to the database.
So for exmaple let $player_fromsite = array('foo', 'bar'), you would end up with the query
CREATE TABLE `Ars` (`foo` VARCHAR(30),`bar` VARCHAR(30));

Related

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

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!

phpmysql inserts blank instead of value

I have the following function:
function insert($database, $table, $data_array)
{
# Connect to MySQL server and select database
$mysql_connect = connect_to_database();
mysql_select_db ($database, $mysql_connect);
# Create column and data values for SQL command
foreach ($data_array as $key => $value)
{
$tmp_col[] = $key;
$tmp_dat[] = "'$value'";
}
$columns = join(",", $tmp_col);
$data = join(",", $tmp_dat);
# Create and execute SQL command
$sql = "INSERT INTO ".$table."(".$columns.")VALUES(". $data.");";
$result = mysql_query($sql, $mysql_connect);
# Report SQL error, if one occured, otherwise return result
if(mysql_error($mysql_connect))
{
echo "MySQL Update Error: ".mysql_error($mysql_connect);
$result = "";
}
else
{
return $result;
}
}
The values in php are the following:
$content_table = "p_content";
$insert_array['title'] = $title;
$insert_array['content'] = $content;
$insert_array['url'] = $get_source;
$insert_array['video'] = $video;
$insert_array['date'] = $date;
insert(DATABASE, $content_table, $insert_array);
The result of all this adds a row with id (key, autoimcrement), url, and date. Title, content and video are blank. If I echo title I get the correct result, if i var_dump the title I get string(15)"blablablabla", again correct.
Now if I hand set the $title = "asdf"; it is getting inserted correctly. Same goes for content and video.
table structure
id int(8) unsigned NO PRI NULL auto_increment
title varchar(1000) YES NULL
content longtext YES NULL
video varchar(3000) YES NULL
url varchar(300) YES NULL
date date YES NULL
Try adding quotes to your variables. :-) The reason is that you MYSQL column types are set as VARCHAR. And inserting data requires that you surround your inserts with quotes.
B.T.W. if this is new code I would recommend to switch to the MYSQLI or PDO library.
Try:
function insert($database, $table, $data_array)
{
# Connect to MySQL server and select database
$mysql_connect = connect_to_database();
mysql_select_db($database, $mysql_connect);
$cols = array();
$vals = array();
foreach ($data_array as $key => $value) {
$cols[] = "`" . $key . "`";
if (is_int($value) || is_float($value)) {
$vals[] = $value;
} else {
$vals[] = "'" . mysql_real_escape_string($value) . "'";
}
}
$sql = "INSERT INTO " . $table
. ' (' . implode(', ', $cols) . ') '
. 'VALUES (' . implode(', ', $vals) . ')';
$result = mysql_query($sql, $mysql_connect);
# Report SQL error, if one occured, otherwise return result
if(mysql_error($mysql_connect)) {
echo "MySQL Update Error: " . mysql_error($mysql_connect);
$result = ""; // FIXME should probably return false here
} else {
return $result;
}
}
IMPORTANT
Your code and the above is potentially vulnerable to SQL Injections. Go read about them.

AJAX - JSON chained dynamic MySQL Select elements do not work with text but work fine with numerical value

I have the following code snippet that builds chained select boxes based on data pulled from MySQL.
The first select uses a DISTINCT on a column called PartTypeDescription. This code works awesome if the values in the column are numerical in nature (example: 11). You choose the first select and then the second select is populated as it should.
The problem occurs when the data is text (example: Plumbing). You choose Plumbing for example and the second select box is empty. I'm assuming the second query that builds the second select box is not working correctly. Is there something in the code below that does not allow text values?
/* Configure the select boxes */
if (isset($_GET['key'])) {
$key = $_GET['key'];
switch ($key) {
case 'callTypeSelect':
$select = new SelectBox('What vehicle are you working from?','Choose a vehicle');
$res = mysql_query('SELECT DISTINCT PartTypeDescription FROM ' . DB_TABLE2);
$callTypes = array();
for ($i = 0; list($callType) = mysql_fetch_row($res); $i++) {
$callTypes[] = $callType;
$select->addItem($callType, 'brandSelect-' . $callType);
}
header('Content-type: application/json');
echo $select->toJSON();
break;
default:
if (strpos($key, 'brandSelect-') === 0) {
$callType = str_replace('brandSelect-', '', $key);
$resBrands = mysql_query('SELECT Invm_InventoryNumber FROM ' . DB_TABLE2
. ' WHERE PartTypeDescription = ' . mysql_real_escape_string($callType) . " ORDER BY Invm_InventoryNumber");
$select = new SelectBox('What part number are you looking for?', 'Pick a part');
for ($i = 0; list($brand) = mysql_fetch_row($resBrands); $i++) {
$select->addItem($brand, 'result-' . $brand . '-' . $callType);
}
header('Content-type: application/json');
echo $select->toJSON();
} elseif (strpos($key, 'result-') === 0) {
list($null, $brand, $callType) = explode('-', $key);
$res = mysql_query('SELECT * FROM ' . DB_TABLE2
. ' WHERE PartTypeDescription = \'' . mysql_real_escape_string($callType) . '\'
AND Invm_InventoryNumber = \'' . mysql_real_escape_string($brand) . "'");
$markup = '';
for ($i = 0; $row = mysql_fetch_assoc($res); $i++) {
//$row = array_map('htmlspecialchars', $row); it looks like the items is already encoded
$markup .= <<<HTML
You can't escape characters inside of single quotes. For example:
$x = 'I don\'t like tomatoes';
That won't escape the quote like you think it would and will cause problems. In your code with this line:
$res = mysql_query('SELECT * FROM ' . DB_TABLE2
. ' WHERE PartTypeDescription = \'' . mysql_real_escape_string($callType) . '\'
AND Invm_InventoryNumber = \'' . mysql_real_escape_string($brand) . "'");
You need to wrap strings with escape sequences with double quotes.
$res = mysql_query('SELECT * FROM ' . DB_TABLE2
. " WHERE PartTypeDescription = \'" . mysql_real_escape_string($callType) . "\'
AND Invm_InventoryNumber = \'" . mysql_real_escape_string($brand) . "'");

Create table on master with data from slave in MySQL 5.1 and PHP 5.4

In MySQL 5.1 and PHP 5.4 I need to create temporary tables from the result of a query on a slave database. The problem is that I need the temporary table to be created on the Master (with data from the slave). It's the selection of the data for this table that carries all the overhead so I need the SELECT to happen on one of the slaves. The temporary table will be selected from for up to 2 hours, and I can't copy it to ALL the slaves (at least I don't think I can).
Here is what the code looks like:
$database->executeQuery ( "CREATE TABLE IF NOT EXISTS `" . $tableName . "` ENGINE = $engine CHARACTER SET utf8 ( " . $sql . ") " );
Again, the query in the $sql variable has to happen on the slave, while the table is created on the master.
Ok, turns out the way for me was to grab the result set in PHP from the slave, then create a SQL statement to insert it into the master.
public function createTemporaryTable ($tableName, $keyField = '', $sql = '', $engine = 'MEMORY') {
global $apdatabase;
$dbObj = new apdatabase();
$dbObj->setSqlCache(false);
$dbObj->setSqlBigResult(true);
$dbObj->setSqlCalcFoundRows(false);
$dbObj->setResultMode(MYSQLI_USE_RESULT);
$sql = $sql ? $sql : $this->getQuery();
$dbObj->executeQuery($sql);
$partsArr = array();
$foundRows = false;
$resultArr = $dbObj->getResultArray();
$dbObj->freeResultSet();
if (! count($resultArr)) {
return;
}
/*
* Set up the statement we will use to create the table definition
*/
$firstRow = $resultArr[0];
$fields = '';
$fieldDefinitionStr = '';
foreach ($firstRow as $field => $data) {
if ($fields != "") {
$fields .= ",";
$fieldDefinitionStr .= ",";
}
$fields .= $field;
$fieldDefinitionStr .= "`" . $field . "` VARCHAR (1024)";
}
parent::executeQuery("DROP TABLE IF EXISTS `" . $tableName . "`");
parent::executeQuery("CREATE TABLE `" . $tableName . "` ( " . $fieldDefinitionStr . ") ENGINE = $engine CHARACTER SET utf8");
/*
* Set up the sql to insert the remaining rows into our new table
*/
$sql = "INSERT IGNORE INTO `$tableName` ($fields) ";
$partsArr = array();
foreach ($resultArr as $row) {
$foundRows = true;
$rowSql = "(";
foreach ($row as $field) {
if ($rowSql != "(") {
$rowSql .= ",";
}
$rowSql .= "'" . $field . "'";
}
$rowSql .= ") ";
$partsArr[] = $rowSql;
}
parent::executeQuery($sql . "VALUES " . implode(', ', $partsArr));
if ($keyField) {
parent::executeQuery(" ALTER TABLE `" . $tableName . "` ADD KEY (`" . $keyField . "`) ");
}
}

Categories