MySQL PHP - Missing character after forward slash - php

I have a php script that inserts data from an Android app into a MySQL DB. Some of the submitted values are set to "N/A" text when submitted. I have confirmed that the values sent from the Android device are indeed "N/A". All of the "N/A" text values are saved correctly to my MySQL DB except for at two fields/columns. The values appear as "N/" in these two fields/columns instead of "N/A". I am using mysql_real_escape_string() on the entered data.
The data is sent as a JSON object string to the PHP script:
$q = json_decode(stripslashes($_POST['questionnaire']), true);
This is a section of the php script where the values are inserted into MySQL DB. It is the values at q3_7 and q4_3 that are truncated from "N/A" to "N/":
$query_insert = "INSERT INTO people (q_id, first_name, surname, gender, age, race, q2_7, q2_8, q2_9, q2_10, q2_11, q2_11_1, q3_1, q3_2, q3_3, q3_4, q3_5,
q3_6, q3_7, q3_8, q3_9, q3_10, q3_11_1, q3_11_2, q3_11_3, q3_12, q3_13, q4_1, q4_2, q4_3, q4_4, q4_5, q5_1, q5_2, q5_3) VALUES";
$values = "";
$count = 0;
foreach ($q[people] as $entry) {
$values .= "('".mysql_real_escape_string($q[qID])."', '".mysql_real_escape_string($entry[firstName])."', '".mysql_real_escape_string($entry[surname])."',
'".mysql_real_escape_string($entry[gender])."', '".mysql_real_escape_string($entry[age])."', '".mysql_real_escape_string($entry[race])."',
'".mysql_real_escape_string($entry[q2_7])."', '".mysql_real_escape_string($entry[q2_8])."', '".mysql_real_escape_string($entry[q2_9])."',
'".mysql_real_escape_string($entry[q2_10])."', '".mysql_real_escape_string($entry[q2_11])."', '".mysql_real_escape_string($entry[q2_11_1])."',
'".mysql_real_escape_string($entry[q3_1])."', '".mysql_real_escape_string($entry[q3_2])."', '".mysql_real_escape_string($entry[q3_3])."',
'".mysql_real_escape_string($entry[q3_4])."', '".mysql_real_escape_string($entry[q3_5])."', $first_map_insert_id + $count*2,
'".mysql_real_escape_string($entry[q3_7])."', '".mysql_real_escape_string($entry[q3_8])."', '".mysql_real_escape_string($entry[q3_9])."',
'".mysql_real_escape_string($entry[q3_10])."', '".mysql_real_escape_string($entry[q3_11_1])."', '".mysql_real_escape_string($entry[q3_11_2])."',
'".mysql_real_escape_string($entry[q3_11_3])."', '".mysql_real_escape_string($entry[q3_12])."', '".mysql_real_escape_string($entry[q3_13])."',
'".mysql_real_escape_string($entry[q4_1])."', $first_map_insert_id + $count*2 + 1, '".mysql_real_escape_string($entry[q4_3])."',
'".mysql_real_escape_string($entry[q4_4])."', '".mysql_real_escape_string($entry[q4_5])."', '".mysql_real_escape_string($entry[q5_1])."',
'".mysql_real_escape_string($entry[q5_2])."', '".mysql_real_escape_string($entry[q5_3])."'),";
$count++;
}
$query_insert = $query_insert . substr($values, 0, -1) . ";";
$result = mysql_query($query_insert) or errorReport("Error in query: $query_insert. ".mysql_error());
As mentioned the "N/A" text values are only truncated to "N/" at two of the fields. The rest of the values for the other fields are saved correctly as "N/A". Any ideas or help would be appreciated.

Input length must not exceed database table column length.
Maybe these two fields is shorter, on database table?

The only way I could think of it is the length of that column/fields are short which leads to the truncation.
E.g. your N/A has length 3 so you field must be at least of length three.

Related

Column count doesn't match value count at row 1 using Variables

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.

Import a "|" delimited text file into MySQL DB using PHP?

I'm trying to load a text file locally into a MySQL database using PHP. The data file looks like:
Device Name|DE:VI:CE:MAC:AD:DR:ES:SS|1376493754086|1376493754086
There are many lines of data formatted exactly as above.
I'm trying to load this data into a pre-established table like this:
$file = #fopen("LOCAL_data_file.txt","r");
$values = '';
while(!feof($file))
{
$con=mysqli_connect("127.0.0.1","root","password","my_db");
if(mysqli_connect_errno()){
echo "Error connecting to my_db: " . mysqli_connect_error();
}
$buffer = fgets($file, 4096);
list($a,$b,$c,$d)=explode("|",$buffer);
/*echo $a;
echo $b;
echo $c;
echo $d;*/
$ins="INSERT INTO 'tablet3' (Name, Address, StartTime, EndTime) VALUES
($a,$b,$c,$d)";
mysqli_query($con,$ins);
}
The data gets read from the file fine, because If I decomment the echoes of the list variables, it echos all of the data in the table. If I don't run the insert query, the table gets created with proper columns of "Name | Address | StartTime | Endtime" but with the insert query, the code returns a table with null data. I simply cannot figure out what I'm doing wrong.
I recreated it and this is the query I got to work
This is assuming the database structure of:
Name(varchar or text) Address(varchar or text) StartTime(int) EndTime(int)
Query:
$ins="INSERT INTO `tablet3` (Name, Address, StartTime, EndTime) VALUES
('$a','$b',$c,$d)";
Take note of the quotes around $a and $b. Also the tick marks around tablet3.
P.S. You don't really need anything around a table name.

Error putting data into database

I have the following php code:
foreach($html->find('dl[class=movie-info]') as $info) {
for($i = 0; $i <= 20; $i++) {
$contenido = $info->find('dt',$i)->plaintext;
if($contenido == 'Año'){
$year = utf8_encode($info->find('dd',$i)->plaintext);}}}
(the code has more if functions)
And a mysql table where I put the content of the variables....
The problem is with the $year content, I need to fill it in a smallint(5) unsigned.
When I use
$con = mysqli_connect("localhost","root","tdguchiha","phpbb3");
mysqli_query($con,"INSERT INTO pablo (forum_id, calidad, titulo, caratula, sinopsis, pais, director, reparto, genero) VALUES ('$forum_id', '$calidad', '$titulo', '$img', '$sinopsis', '$pais', '$director', '$reparto', '$genero')");
mysqli_close($con);
All the content is inserted, but when i try to insert $year into año with type smallint(5) unsigned nothing happens, no row is created...
how can I convert $year to a number (it must be a number) to fill it in that column? or I need to change the column type?
PD: I am learning right now to "play" with mysql
thanks
There is no difference in mysql between a number and a string when doing queries. Make sure you include the column name in the list of all the columns:
mysqli_query($con,"INSERT INTO pablo (forum_id, calidad, titulo, caratula, sinopsis, pais, director, reparto, genero, year) VALUES ('$forum_id', '$calidad', '$titulo', '$img', '$sinopsis', '$pais', '$director', '$reparto', '$genero', '$year')");
^notice year the column ^now the actual value
Just replace year in the column section with the name of your mysql column.
Perhaps try casting it to an integer instead of using utf8_encode:
$year = intval($info->find('dd',$i)->plaintext);
Or, in addition to it:
$year = intval(utf8_encode($info->find('dd',$i)->plaintext));
Can you give us an example of the data?
EDIT: Damien is right, intval() shouldn't make a difference.
Try echoing out the contents instead, and making sure it's an actual number in the string to do some debugging:
if($contenido == 'Año'){
$year = utf8_encode($info->find('dd',$i)->plaintext);
echo $year.'<br />';}}}
Before posting a question to StackOverflow, identify any error-codes / error-messages and post them with your question:
/* check connection */
if ( mysqli_connect_errno() ) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
And:
if ( ! mysqli_query( $link, "SELECT ..." )) {
printf("Errorcode: %d\n", mysqli_errno($link));
}
More on the PHP doc site.
I think your problem is with value type and data you are trying to insert:
A smallint is between -32768 and 32767 signed, or 0 and 65535 unsigned.
The (5) represents the display width of the field - if you will try to put 90000 you will be rejected.
In your case it should not be a problem (years value I assume) but show us the data you are trying to insert.
I guess that you are parsing some content using simple_html_dom - make sure all data retrieved is
as you expect before inserting it to DB.
Also: Try changing the type to int(5) and now tell us....
It will be easier to see the query you use (with the year) and a sample of data.
For error loging and display use:
$execute = mysqli_query($con,"INSERT INTO pablo ( ....your query..... ")
or
printf("Errormessage: %s\n", mysqli_error($con));
Have Fun

PHP Implode not working with mysql_query

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.

PHP form to MSSQL 2005 with auto ID generation via (alter table add)

Can someone please help? I do get connection to db and can retrieve data and "post", the only break point is ContactID record which is primary and required. I believe it has to do something with my Alter table line, I just do not know where.
Here is the scenario:
Form is written in php.
Form is posting data to MSSQL 2005
ContactID can not be null and need to be assigned automatically.
On submit I receive the exception: String or binary data would be
truncated. The statement had been terminated.
Here is the php code:
if(isset($_GET['action']))
{
if($_GET['action'] == 'add')
{
// this is where inserting data beggins
$insertSql = "INSERT INTO sys.CONTACT (LASTNAME, FIRSTNAME, EMAIL)
VALUES (?,?,?)";
$params = array(("Alter table sys.CONTACT add ProgramID int IDENTITY(9000001,1) NOT NULL, CONTACTID AS ('CCRMS'+CONVERT(varchar(7),ProgramID,(0)))"),
&$_POST['lastName'],
&$_POST['firstName'],
&$_POST['emailAddress']);
$stmt = sqlsrv_query($conn, $insertSql, $params);
if($stmt === false)
{/*Handle the case of a duplicte e-mail address.*/
$errors = sqlsrv_errors();
if($errors[0]['code'] == 2601)
{
echo "The e-mail address you entered has already been used.</br>";
}
/*Die if other errors occurred.*/
else
{
die(print_r($errors, true));
}
}
else
{
echo "Registration complete.</br>";
}
}}
Your exception is:
String or binary data would be truncated. The statement had been terminated.
It appears your ALTER string is actually being placed into the LASTNAME column. SQL Server is telling you that your long string has been truncated to the length of the LASTNAME column.
You're basically supplying 4 string values to the array. The first 3 are being accepted as args to the statement. One or more doesn't fit the length of the column it's trying to be fit into on the table.
Check back on the varchar() definitions of those columns. Are they smaller than the strings that are being supplied?
Use this instead:
$params = array(&$_POST['lastName'],
&$_POST['firstName'],
&$_POST['emailAddress']);

Categories