for some odd reason php statement work fine when i only have on item in the array but everytime i add a second one i get an error "Column count doesn't match value count at row 1" I clearly have the correct column count. please help
$form_array=implode(",",array("james","brown"));
$db_array=implode(",",array('firstname','lastname'));
$query="INSERT INTO application ($db_array)
Value('$array')";
$dbquery=mysql_query($query);
if(!$dbquery){
echo mysql_error();
}
Your values are not quoted correctly. (and you're using $array instead of $form_array).
Note $form_array after imploding = 'james,brown'.
Putting that (and $db_array) into your query string, you end up with:
$query = "INSERT INTO application (firstname, lastname) VALUE ('james,brown');
Notice "james" and "brown" are quoted together in a single string - hence column count not matching value count.
You really should use a query string escaping function on your inputs - e.g. mysql_real_escape_string:
Wrote this off the top of my head so might have a minor syntax error somewhere, but the below example should push you in the right direction:
$form_array = implode(',', array_map('mysql_real_escape_string', array('james', 'brown')));
$db_array = implode(',', array('firstname','lastname'));
$query = "INSERT INTO application ($db_array) VALUES ($form_array)";
Note you should also take some more precautions if your $db_array is provided by user input in some way.
Related
I'm running a PDO query, something like:
$inputArr = array(val1, val2, val3, ...);
$qMarks = str_repeat('?,', count($inputArr) - 1) . '?';
$stmt = $db->prepare("SELECT id, name, type, level
FROM table
WHERE name IN ($qMarks)");
$stmt->execute($inputArr);
... parse the rows that have been returned
And this works exactly as expected, no hang-ups or anything.
My problem is that I need to know which value from $inputArr was used to get each row returned.
I've tried
WHERE name IN ($qMarks) AS inputVal
and
WHERE name IN ($qMarks AS inputVal)
but those crash the query.
How can I determine which input array value was used to return each row in the output?
EDIT 1
Yes, I understand that the input search value would be name, for this particular case, but the query above is only for demonstration purposes of how I am putting the search values into the query.
The actual is much more complex, and returns any name value with is close (but not always identical).
The AS keyword is not going to work as you expect it. It's mainly used for aliasing subqueries. You can't (to my knowledge) use it in a WHERE clause.
The scenario you've outlined should have the 'name' in $row['name']. If it was a different variable that you wanted to see, you'd simply add it in your SELECT clause.
Great question, and simple answer:
The WHERE name IN $qMarks)"); part of your code is only obtaining the values in your database that are matching your array, so what you can do is see which values of name are present in the row you fetched. For example:
$rows_fetched = $stmt->fetchAll(PDO::FETCHASSOC);
$inputArray = array();
foreach($rows_fetched as $value)
{
$inputArray[] = $value['name'];
}
print_r($inputArray);//printing the results
Now you have the array $inputArray with all the values used to return each row in the output. Let me know if that worked for you!
I have read most of the questions here and read the php manual in regards to the problem of converting an sql result to a string, however none of them is working for me. The examples given I understand, however they are echoing the sql results, I do not want the result to be echoed, I just want it to be stored in a variable so I can immediately insert it into a next sql table.
This is my code:
$cnt_fips = mysqli_query($con, "SELECT cc_fips FROM location2 WHERE location_name = '$cnt'");
$row = mysqli_fetch_assoc($cnt_fips);
These are the codes I have used to convert to string but failed with
$myStr = !is_array($row) ? trim(addslashes($row)):'';
and
$myStr = (string)$row;
and
$myStr = print_r($row,true);
and also
$myStr = (string)$row;
And insert into the table below
$query2 = mysqli_query($con, "INSERT INTO location3 VALUES ('','$myStr')");
$row is always an array with column names as the keys, use:
$myStr = $row['cc_fips'];
Also, I'm pretty sure you can do that all in one insert with a sub-select (though maybe not if a row with $cnt doesn't exist). If so, maybe someone will post it.
Following is my code showing some error in mysql query:
<?php
$con=mysql_connect('localhost','root','');
$str=$_GET["message"];
$stor=explode(" ",$str);// converting message into array
mysql_select_db('words',$con);
for($j=0;$j<=30; $j++)
{
mysql_query($con,"UPDATE blacklist SET $stor=1 where $stor=0");//if column name=element in array then make it as 1 in database
}
mysql_close($con);
?>
Your code is vulnerable to SQL Injection. Read up on prepared statements and use PDO/MySQLi.
$stor is an array object and cant be used directly in the query. If you want to use it, try using
IN('.implode(",", $stor).')
the code above does the following:
implode() - takes an array and turns it into a comma separated string.
IN() - compares the given comma separated values and returns true if at least one of them exists.
Example (implode):
implode(",", array(1,2,3)) IS EQUAL TO "1,2,3"
Example (IN):
TestID IN (1,2,3) IS SAME AS (TestID = 1 OR TestID = 2 OR TestID = 3)
You're probably getting a mysql error because your query ends up looking like this
UPDATE blacklist SET Array=1 where Array=0;
If you're just echoing out a full array, you get Array instead, you'll need to specify an array element ($stor[1] for example).
What you'll want to do is replace your for loop with a foreach so that you can just throw out the elements one at a time.
Also, your arguments are backwards.
foreach($stor as $word)
{
mysql_query("UPDATE blacklist SET $word=1 where $word=0", $con);
}
I have some data in PHP arrays/variables ready to insert into a PostgreSQL table via an INSERT statement.
For a simple example say I have the following information:
$name= 'someName';
$time = array(1,2,3);
$elevation = array(100,200,300);
(In my real application these are double precision and potentially 1,000+ values)
I also have my postgresql table with columns "name","time","elevation"
I want to insert these in a single INSERT statement, and have been given multiple different ways to do this.
Loop and insert one data point (row) at a time.
Use unnest() on the arrays and do a single insert (fastest)
My question is can I pass a single variable name, and the un-nested arrays and have name repeated every row (ever array element), or do I need to construct a repeated array for name the equivalent count() as the other arrays?
An example statement:
*cr_query is a custom PHP pg_query wrapper we use
cr_query($conn,"INSERT INTO sometable (name,time,elevation) VALUES ({$name},{unnest($time)},{unnest($elevation)}););
This would insert into sometable:
ID name time elevation
1 someName 1 100
2 someName 2 200
3 someName 3 300
Am I correct here or do I need to do something else?
EDIT:
Lets say I also have another variable "surface". Surface can be a double value or can be NULL. So I want to insert into the table to look like so:
ID name time elevation surface
1 someName 1 100 50
2 someName 2 200 NULL
3 someName 3 300 100
In PHP, using the method perscribed by klin below an array for surface in the unnest statement would become unnest(array[50,,100]); This throws an error like so:
(Error from my real data)
ERROR: syntax error at or near "," LINE 3: ...-6,5.75E-6,5.75E-6,5.75E-6,5.75E-6]),unnest(array[,,,,,,,,,]... ^
EDIT 2:
Now that all of the "encoding" is working a new problem has popped up. Say the example column "surface" above is type double precision.
Say I am inserting an array, but for this set all of the data is null.
The essential piece is:
unnest(array[null,null,null,null,null,null,null,null,null,null])
However, this array is of type string. Add a single value to it and it becomes the type of that numeric value, but I need to be able to handle this.
My question is: How do I insert an unnested array of all null values into a double precision column? (I tried to cast ::double precision) but it's not possible.
Assuming your cr_query() function is not doing any magic things, your code is going to raise postgres syntax error. You can use unnest but you must prepare proper query text.
Try your code:
$name= 'someName';
$time = array(1,2,3);
$elevation = array(100,200,300);
echo "INSERT INTO sometable (name,time,elevation) VALUES ".
"({$name},{unnest($time)},{unnest($elevation)})"
echo: INSERT INTO sometable (name,time,elevation) VALUES (someName,{unnest(Array)},{unnest(Array)})
Obviously it is not what we want to send to postgres. How to repair this?
$name= 'someName';
$time = array(1,2,3);
$elevation = array(100,200,300);
$timestr = 'array['. implode(',', $time). ']';
$elevstr = 'array['. implode(',', $elevation). ']';
echo "INSERT INTO sometable (name,time,elevation) ".
"VALUES ('$name',unnest($timestr),unnest($elevstr));"
echo: INSERT INTO sometable (name,time,elevation) VALUES ('someName',unnest(array[1,2,3]),unnest(array[100,200,300]));
I think this is correct query. Note that I enclosed text variable '$name' in single quotes.
If you have nulls in your arrays you have to replace all empty strings to 'null' in prepared text for query.
Probably the simplest way to do it is to use str_replace().
As the conversion is getting more complicated it is handy to write a function (say "pgstr()") for that purpose.
function pgstr($array) {
$str =
str_replace('[,', '[null,',
str_replace(',]', ',null]',
'array['. implode(',', $array). ']'));
while (strpos($str, ',,') > 0) $str = str_replace(',,', ',null,', $str);
return $str;
}
$name= 'someName';
$time = array(1,2,3,4);
$elevation = array(100,null,300,null);
$surface = array(null,null,3.24,null);
$timestr = pgstr($time);
$elevstr = pgstr($elevation);
$surfstr = pgstr($surface);
echo
"INSERT INTO sometable (name,time,elevation,surface) ".
"VALUES ('$name',unnest($timestr),unnest($elevstr),unnest($surfstr));";
So I have two arrays, $gDatabaseKeyNames (list of column names) and $gDatabaseKeyValues (a list of variable names containing values from a script). The variable names are generated dynamically so I keep track of them for an insert.
Rather than listing all of the columns and value variables, I tried this
$cols = implode(", ", array_values($gDatabaseKeyNames));
$vals = implode(", ", array_values($gDatabaseKeyValues));
$query = "INSERT INTO pings (survey_id, $cols) VALUES ('$surveyID', $vals)";
mysql_query ($query) or die(mysql_error());
But none of my actual values show up in the database (they are inserted as 0s - all my columns are numeric).
If I echo $query, I see this, which is the correct formatting:
INSERT INTO pings (survey_id, latitude, longitude, pingTimestamp) VALUES ('15', '$Dlatitude', '$Dlongitude', FROM_UNIXTIME('$DtimeStamp'))
However, if I change $query to
$query = INSERT INTO pings (survey_id, latitude, longitude, pingTimestamp) VALUES ('$surveyID', '$Dlatitude', '$Dlongitude', FROM_UNIXTIME('$DtimeStamp'));
It works perfectly!
Why isn't PHP interpreting the variables in the implode? How can I fix this?
I suspect that $cols has the literal value '$Dlatitude', '$Dlongitude', etc.... PHP does not "double-interpolate" strings. It'll replace $cols with its values, but will NOT replace $Dlatitude with that variable's value. In other words, you're literally inserting some strings-that-look-like-PHP-variable-names into your numeric fields.
What is in the $gDatabaseKeyValues/Names arrays?
It's probably caused because of string/number problems. You should consider changing the database engine (Consider PDO) and use prepared statements to bind the parameters to your query the right way.