show COLUMNS FROM ma_table with séparator - php

I want to have the fields names separated with ',' .
This query
show COLUMNS FROM ma_table;
Returns raw unseparated values
$sql = "show COLUMNS from ma_table ";
$req = mysql_query($sql) or die('Erreur<br>'.$sql.'<br>'.mysql_error());
while ($rslt = mysql_fetch_assoc($req)) {
$fields=$rslt['Field'];
}
mysql_close();

All you need to do is concatenate a comma onto $fields as you process round the while loop.
You also need to use the .= string concatenation operator in the loop so you are adding each new Field to the string and not overwriting it each time.
$fields = '';
while ($rslt = mysql_fetch_assoc($req)) {
$fields .= $rslt['Field'] . ',';
}
echo rtrim($fields, ',');
I am afraid I must also add
Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here

Related

Looping an entire form into a MySQL db row?

I'm hoping someone can give me a suggestion on a challenge I am facing. I am not sure that I'm able to do this the way I envision, so looking for advice from those more experienced.
I have a database table with around 20 columns. It's a lot of columns and unfortunately I cannot change that. The goal is to take a form submission and insert it into this table. So what I have is, the field names are identical to the column names in the database.
To try and keep the code cleaner, I would like to just pull the entire form (key and value) in, instead of doing the traditional $varWhatever = $_POST['whatever']; 20 times. Using something like this: foreach ($_POST as $key => $value)
Now my question is, if at all possible, how can I run that foreach loop in a way that will let me put the keys and values into a single SQL statement?
"INSERT INTO table_name (Loop all keys here) VALUES (Loop related values here)"
Is this even possible, or should I just go back to the more traditional way I mentioned above?
One way I am thinking is, before starting the loop, I could create the empty row and grab it's ID, then within the loop, I could run an update query on the row matching the ID. Sounds sloppy though.
Here is a solution I came up with. You first have to define an array of field names that acts as a whitelist of expected inputs. Then you just loop through that array to build a parameters array to bind the submitted values. And implode the array with a comma when building the query.
$fields = array('field1','field2','field3');
$binds = array();
foreach ($fields as $field) {
$binds[":$field"] = $_POST[$field];
}
$sql = "INSERT INTO table_name (" . implode(',',$fields) . ") VALUES (" . implode(',',array_keys($binds)) . ")";
$db->prepare($sql);
$db->execute($binds);
This assumes you are using PDO.
Yes, you can loop for all keys (eg. do an array_keys), but I don't recommend blindly taking any submission parameter and putting it into a SQL query.
Instead, I would keep a list of all valid columns of the form and work with that, remembering that each value needs sanitization, too.
For example:
<?php
$columns = array('column1', 'column2', 'column3', …);
foreach ($columns as $column) {
if (!isset($_POST[$column])) {
die("No data for column $column\n");
}
}
if (!check_csrf($_POST['csrt_token'])) { … }
# (setup database connection)
$SQL = "INSERT INTO table_name (" . implode(", ", $columns) . ") VALUES (";
foreach ($column as $column) {
$SQL .= "'" . $mysqli->real_escape_string($_POST[$column]) . "',";
}
$SQL[strlen($SQL)-1] = ')';
$mysqli->query($SQL);

mysqli_query returns false because values contain space charcter

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)

Dynamic query building from POST data in PHP

I have large tables in my database and instead of specifying each column name I am trying to build the query dynamically.
I am trying to do an update in the 'motherboard' table based on the POST data received. The $data object i receive has more fields than the table has. (I added some fields for some flags.)
Hence, I am retrieving the record I'm about to update and by comparing each of it's columns with my $data object fields I am constructing the UPDATE query.
I'm new to php, therefore I don't know the syntax well.
This is the code:
<?php
$data = json_decode($_POST["data"], true);
$id = $data["ID"];
include_once 'dbconnect.php';
$query = sprintf("SELECT * FROM `motherboard` WHERE ID = " . $id . ";");
$result = mysqli_query($con, $query);
$existingData = mysqli_fetch_assoc($result);
include_once 'dbclose.php';
$statement = "";
$statement = "UPDATE motherboard SET ";
$flag = false;
foreach ($existingData as $key => $value) {
if ($existingData->$key != $data->$key) {
$statement .= $key . " = " . $data->$key . " , ";
$flag = true;
}
}
if ($flag)
$statement = substr($statement, 0, strrchr($statement, ',') - 1);
$statement .= " WHERE ID = " . $id . ";";
echo $statement;
?>
My main problem is in the foreach loop. I don't know how can I compare and then use for building the query the $existingData and $data variables.
How can I achieve this?
Don't use this approach please, if you want a SOLID application that will outrun the ages, use specific column names and not some junkish foreach loop that builds your SQL for you. If you want to evade the writting of SQL, use an ORM, there are ton's that exist out there and most of them are bundled with a framework right off the start making it simpler to learn the ropes!
Examples of simple to learn frameworks: (But not necessarely weak frameworks)
Cake PHP
Laravel
Good luck
You need to change some code ...
$result = mysqli_query($con, $query);
$existingData = mysqli_fetch_assoc($result);
Now your $existingData is an array you can loop though;
Honestly I would recommend you take advantage of a framework with an ORM or just a standalone ORM. I suggest Laravel or CodeIgniter (if you are new to programming in general then CodeIgniter will be the easiest).
Next, why is your POST data JSON encoded? Why not just POST all the form variables? I would recommend that way instead to simplify it (even from JS).
Finally, you have to make sure you sanitize your inputs. You can use mysqli_real_escape_string(). I am assuming you will use the MySQLi DB interface. (Ref: http://php.net/manual/en/mysqlinfo.api.choosing.php)
Actually one last note: Laravel is, in my opinion, the future of PHP frameworks. It is beautiful, lightweight, and powerful. I HIGHLY recommend that you learn it. Ref: http://laravel.com/
I managed to get it working. Now I'm constructing my queries based on the difference between the existing data and the updates from the user. The foreach loop now looks like this:
foreach ($existingData as $key => $value) {
if ($existingData[$key] != $data[$key]) {
$statement .= $key . " = \"" . $data[$key] . "\" , ";
$flag = true;
}
}
This is the part that was interesting for me. The rest of the code should be updated according to the latest API.

Creating a dynamic MySQL query from URL paramaters

I am really trying to wrap my head around this and failing miserably. What I want to do it build a MySQL query based on the URL parameters passed by the URL. I am trying to create a re usable dynamic script that can do what it needs to do based on the URL parameter.
This is what I have come up with, and it appears that it does what it is supposed to do (no errors or anything) but nothing actually gets inserted in the database. I know somewhere I have made a dumb mistake (or thought something out wrong) so hopefully one of you guys can point me in the right direction.
Thanks!
//List all possible variables you can expect the script to receive.
$expectedVars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
$fields = array('uName','uEmail','uScore','uAge','uDate');
// Make sure some fields are actually populated....
foreach ($expectedVars as $Var)
{
if (!empty($_GET[$Var]))
{
$fields[] = sprintf("'%s' = '%s'", $Var, mysql_real_escape_string($_GET[$Var]));
}
}
if (count($fields) > 0)
{
// Construct the WHERE Clause
$whereClause = "VALUES " . implode(",",$fields);
//Create the SQL query itself
$sql = ("INSERT INTO $mysql_table ($fields) . $whereClause ");
echo "1"; //It worked
mysql_close($con);
}
else
{
// Return 0 if query failed.
echo "0";
}
?>
You missed mysql_query($sql):
if(!mysql_query($sql)){
//die(mysql_error());
}
Please consider to use PDO or My SQLi using parametrize query because mysl_* function depreciated.
Your SQL is all wrong. You're using the field = value syntax for an INSERT, then you're concatenating an array as if it were a string ($fields), and you're missing a couple of parentheses around the values.
a couple of things: i've found for php <-> mysql its important to see what's going into mysql and experiement directly with those queries in phpmyadmin when i get stuck.
1 - in my code I output mysql_error() when the query fails or when a debug flag is set. this usually explains the sql issue in a way that can point me to a misspelled field name etc...
2 - this way i can feed that mysql query directly into phpmyadmin and tweak it until it gives me the results i want. (while i'm there i can also use explain to see if i need to optimize the table)
specifics in your code. unlike C languages sprintf is implied. here's how i'd write your code:
// List all possible variables you can expect the script to receive.
$expectedvars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
// $fields = array('uName','uEmail','uScore','uAge','uDate');
$fields = array();
// Set only the variables that were populated ...
foreach ($expectedvars as $var) {
if (!empty($_GET[$var])) {
$name = "u" + ucwords($var); // convert var into mysql field names
$fields[] = "{$name} = " . mysql_real_escape_string($_GET[$var]);
}
}
// only set those fields which are passed in, let the rest use the mysql default
if (count($fields) > 0) {
// Create the SQL query itself
$sql = "INSERT INTO {$mysql_table} SET " . implode("," , $fields);
$ret = mysql_query($sql);
if (!$ret) {
var_dump('query_failed: ', $sql, $ret);
echo "0"; // Query failed
} else {
echo "1"; // It worked
}
} else {
// Return 0 if nothing to do
echo "0";
}
mysql_close($con);

Mysql_query UPDATE

I could swear that I had this working last week, but now I get errors.
In PHP I have a large CSV file that I run through a foreach loop and in this loop I have a created a variable that adds an UPDATE line to itself, like this:
foreach ($csv->data as $value){
$updater .= "UPDATE tblProduktData SET xtra = 2 WHERE id = '$value[1]';";
}
mysql_query("$updater") or die(mysql_error());
The CSV file contains over 3000 lines so having the mysql_query() inside the loop obviously makes the process slow and is not recommendable.
Can anyone tell me if I'm missing something or just doing it wrong?
We will temporarily ignore the fact that you are using a PHP extension mysql_ that has been deprecated ( Scheduled for removal from the language) for a number of years now.
For some reason you are adding to the sql query each time through the loop by using the .= syntax. I assume you thought you could run more than one query at a time using the mysql_ extension, but you cannot.
So try this :-
foreach ($csv->data as $value){
$updater = "UPDATE tblProduktData SET xtra = 2 WHERE id = '$value[1]'";
mysql_query($updater) or die(mysql_error());
}
This is in fact a perfect candidate for using mysqli_ or PDO prepared statements.
The mysqli_ extension manual
The PDO manual
Try this:
$id = "0"; // initialze the ids to update with a non-existing value
// fetch all the ids into a variable
foreach ($csv->data as $value){
$id .= "," . $value[1]
}
$updater .= "UPDATE tblProduktData SET xtra = 2 WHERE id in (".$id.") ;";
mysql_query("$updater") or die(mysql_error());

Categories