Error INSERTING Array With Form Validation - php

I have three queries about form validation for a tag system using mysqli.
.what is the best practice to escape $tag_no array.
.When $tag_no array is passed from the form integers are passed as strings, so is_int will not work with $tnumber, any ideas?
.Is this the overall best practice for validating an array of tags passed from a form.
Hope this is clear and concise, any help would be much appreciated.
Thanks in advance.
$tag_no = $_GET['tno'];
$tno = mysqli_real_escape_string($link, $tag_no);
if ($tag_no != false) {
$query = "INSERT INTO `uc` (`UNO`, `BNO`) VALUES ('$uno', '$box');";
foreach ($tag_no as $tnumber) {
if (is_int($tnumber)) {
$query .= "
INSERT INTO `ut` (`UNO`, `TNO`) VALUES ('$uno', '$tnumber')";
} else {
$query .= "INSERT INTO tags (TName) VALUES ('$tagname')";
}
};
};
mysqli_multi_query($link, $query);

Even if you use mysql_multi_query() you'll have to use the ';' to separate the indivdual queries.
So change your code to:
foreach ($tag_no as $tnumber) {
if (is_int($tnumber)) {
$query .= "
INSERT INTO `ut` (`UNO`, `TNO`) VALUES ('$uno', '$tnumber');"; # <-- note the ;
} else {
$query .= "INSERT INTO tags (TName) VALUES ('$tagname');"; # <-- note the ;
}
}
Also I'm pretty sure, that this will fail:
foreach ($tag_no as $tnumber)
as $tag_no is actually a string and foreach expects an array. (You've used it with mysqli_real_escape_string().)

Related

GROUP_CONCAT inside an INSERT statement

I am not really sure if this is possible, or if there is any alternative way to do this.
The following code takes multiple input from a user and inserts them in different rows, I don't want it like that. I am looking for a way to insert them in the same row.
<?php $test=$_POST['test'];
foreach ($test as $a => $b){?>
<?php echo $test[$a];?>
<?php
if( !$error ) {
$query = "INSERT INTO test_tbl(test) VALUES('$test[$a]')";
$output = mysql_query($query);
if ($output) {
$errTyp = "success";
$errMSG = "Update Posted";
?>
I am aware there is a GROUP_CONCAT function but I can't seem to get it to work in insert statements and from researching I found out it doesn't really work with insert only with select. So is there any way of sorting this mess?
Here is my attempt on the GROUP_CONCAT (Obviously it's a big error that I receive)
$query = "INSERT INTO testing(item) VALUES(GROUP_CONCAT($test[$a]))";
PS I know this is completely against normalization standards but I am doing it since a customer requested it..
If i understood correctly you are inserting in a foreach loop, this will insert each $test[$a] seperately each time the loop runs. ALternatively you can put all $test[$a] values in an array and then insert that array in one row(which is way faster than multiple insert queries).
Here is a way to do it:
$all_test_values = array();
foreach ($test as $a => $b){
$all_test_values[] = $test[$a];
}
$comma_separated = implode(",", $all_test_values);
if( !$error ) {
$query = "INSERT INTO test_tbl(test) VALUES('$comma_separated')";
$output = mysql_query($query);
}
PS: mysql is bad use mysqli instead

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);

Unfilled form values creating empty rows in mysql via php

First time poster, long time lurker :)
I have a form setup that posts data for multiple rows in a single table with seven colums to a php function to insert it as new records in a database. The form is working great, however, if one of the rows in the form is left unfilled then the php function is creating a blank row in the database. I am attempting to figure out how to avoid this. I am certain it has nothing to do with the form itself, and rather has to do with the php. Please have a look at it. I'm totally open to suggestions.
<?php
require("header.php");
require("dbinc.php");
foreach($_POST['card'] as $row=>$cardcounted)
{
$model=$_POST['model'];
$serial=$_POST['serial'][$row];
$card=$cardcounted;
$status=$_POST['status'];
$date=$_POST['date'];
$location=$_POST['location'];
$query = mysql_query("INSERT INTO receivers (`id`, `model`, `serial`, `card`, `status`, `date`, `location`) VALUES ('null','$model','$serial','$card','$status','$date','$location')");
if(!isset($serial[$row]) || $serial[$row] == '') {
// error message here, redisplay form if desired
} else {
// no errors - process data
}
if (!$query)
{
die('Error: ' . mysql_error());
}
}
echo $row+1 . " record(s) added";
mysql_close()
?>
I added in the !isset on the serial numbers by row to check for null posts but am unsure as to how to incorporate that properly. i think im on the right track, just need that little push :)
First choice is to use JavaScript validation to find out invalid form submits, Some users may disable JavaScript, so its always recommended to do server-side validations
So write a method like
isValid($postArray) {
foreach($postArray as $key => $value) {
if ($value == "") {
return false;
}
}
return true;
}
If form field names and db column names are similar you can use
$sql = "INSERT INTO receivers ";
$keys = "(";
$values = "(";
foreach($postArray as $key => $value) {
if ($value != "") {
$keys += $key;
$values += $value;
}
}
$sql = $sql + $keys +" VALUES "+ $values;
Maybe try moving your mysql query into your else currently you insert values into the database regardless of whether you have form errors or not. Also you will need to secure anything that you are inserting into your database. Its an SQL injection field trip right now ;)

PHP foreach insert statement issue with arrays

Hey guys, i'm currently learning php and I need to do this
$connection = mysql_open();
$likes= array();
foreach($likes as $like)
{
$insert3 = "insert into ProfileInterests " .
"values ('$id', '$like', null)";
$result3 = # mysql_query ($insert3, $connection)
or showerror();
}
mysql_close($connection)
or showerror();
For some reason this does not work =/ I don't know why. $likes is an array which was a user input. I need it to insert into the table it multiple times until all of the things in the array are in.
EDIT I fixed the issue where I was closing it in my foreach loop. mysql_open is my own function btw.
Any ideas?
For one $likes is an empty array in your example, I am assuming you fix that in the code you run.
The second is you close the MySQL connection the first the time the loop would run, which would prevent subsequent MySQL queries from running.
there's no such function as mysql_open
you may need mysql_connect
also $likes variable is empty. so no foreach iterations will execute.
You close the connection within the foreach loop.
Here is the proper formatted code to insert data...You can use this.
// DATABASE CONNECTION
$conn=mysql_connect(HOST,USER,PASS);
$link=mysql_select_db(DATABASE_NAME,$conn);
// function to insert data ..here $tableName is name of table and $valuesArray array of user input
function insertData($tableName,$valuesArray) {
$sqlInsert="";
$sqlValues="";
$arrayKeys = array_keys($valuesArray);
for($i=0;$i < count($arrayKeys);$i++)
{
$sqlInsert .= $arrayKeys[$i].",";
$sqlValues .= '"'.$valuesArray[$arrayKeys[$i]].'",';
}
if($sqlInsert != "")
{
$sqlInsert = substr($sqlInsert,0,strlen($sqlInsert)-1);
$sqlValues = substr($sqlValues,0,strlen($sqlValues)-1);
}
$sSql = "INSERT INTO $tableName ($sqlInsert) VALUES ($sqlValues)";
$inser_general_result=mysql_query($sSql) or die(mysql_error());
$lastID=mysql_insert_id();
$_false="0";
$_true="1";
if(mysql_affected_rows()=='0')
{
return $_false;
}
else
{
return $lastID;
}
}
// End Of Function
While many PHP newbies (myself included) begin working with databases from good ole' mysql_connect/query/etc., I can't help suggest that you look into PDO, PHP Data Objects. Depending on your prior knowledge and programming background, there may be a steeper learning curve. However, it's much more powerful, extensible, etc.; I use PDO in all my production code database wheelings-and-dealings now.

MySQL or PHP syntax oversight when trying to perform conditional update

I think this is an escaping issue or something. When I execute the query and populate all variables, everything is peachy and all row is updated properly in the DB.
I looked on StackOverflow to get me rolling with these dynamic/contructed on the fly queries and I'm at the end of my rope.
My stuff looks like this:
$sql="UPDATE users SET ";
if (!empty($fname)) { "fname = '$fname', ";}
if (!empty($lname)) { "lname = '$lname', ";}
if (!empty($location)) { "location = '$location', ";}
if (!empty($url)) { "url = '$url', ";}
"WHERE id = '$id' LIMIT 1";
When I break the query to insert the "IFs" I keep getting the following: Error: 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 '' at line 1
I ECHO'd the query and for some odd reason it's nto complete and the variables are coming in before the query start like so
fname = 'Rob', lname = 'Smith', location = 'Jersey City, NJ', url = 'http://somesite.com', UPDATE users SET Error: 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 '' at line 1
Sorry if I am not clear. I will clarify where needed. I am new at all this. Thank you!
You're not allowed to have a comma after the last thing you SET.
One easy solution is this:
$set = array();
if (!empty($fname)) { $set[] = "fname = '$fname'";}
if (!empty($lname)) { $set[] = "lname = '$lname'";}
if (!empty($location)) { $set[] = "location = '$location'";}
if (!empty($url)) { $set[] = "url = '$url'";}
if(!empty($set)) {
$sql = "UPDATE users SET ";
$sql .= implode(', ', $set)
$sql .= " WHERE id = '$id' LIMIT 1";
}
Oh, and make sure the variables you're shoving in the query are SQL safe; otherwise you've got a SQL injection issue.
Remember in these programming languages, each statement (text ending with a ;) is much like a complete sentence. You need a subject-object-verb for it to make sense. I can't just say
doggy;
I have to say
feed the doggy;
Similarly, I can't just say
"fname = '$fname', "
when I mean "Append this string to the query I started earlier". I have to be explicit:
$sql .= "fname = '$fname', ";
I'm saying "Append this text to $sql". Its a complete sentence.
better to put all your SETs into an array and implode them into a string. That way you can be sure there are no dangling commas. Something like:
if (!empty($fname)) $sets[]="fname = '$fname' ";
if (!empty($lname)) sets[]= "lname = '$lname' ";
if (!empty($location)) sets[]= "location = '$location' ";
if (!empty($url)) sets[]= "url = '$url' ";
$setstring= implode(',',$sets);
if($setstring) {
$query="UPDATE users SET $sets WHERE id = '$id' LIMIT 1";
//run query, etc.
}
Not really a direct answer but for dynamic queries i suggest using PDO. That way you can specify optional parameters more secure, elegant and easier.
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>
If your queries become larger, the way you are doing things now will be pretty complicated to maintain.
echo out your query and take a look at the commas in your SET caluse. Do you have too many? Not enough? I think you'll find that you have one extra comma. You'll probably want to use the implode() function to build up your SET clause. This will insert the appropriate number of commas in the appropriate places.
I see two problems, there is no space before WHERE which means it could turn out "url=http://www.stackoverflow.com"WHERE" and maybe cause a problem.
Also, there is a comma at the end of every SET clause, the last one in the list should not have a comma.

Categories