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
Related
I have a php script which accepts a couple of parameters and invoke a mysql update. One of the parameters is an integer. I added breaker point before the mysql update statement is executed and used var_dump. It showed int(5) but when I verified the result in the database, the value of the updated column show 2016. The column was defined as INT(11). I tried to change the column to be tinyint and the value after update became 127. Can anyone tell me what did I do wrong?
<?php
header('Location: upd_shpsts.php?shpid=87&stsdesc=abc&stsdate=02/10/2016 4:42PM&ctyid=5');
?>
function UpdShpSts($shpid, $stsdesc, $stsdate, $ctyid) {
$ctyid=intval($ctyid);
var_dump($ctyid);
$usrid = $_SESSION['usr_id'];
$pkgs = array();
$pkgs_query = mysql_query("SELECT pkgid FROM pkg WHERE shpid='$shpid'") or die(mysql_error());
while ($pkg_rows = mysql_fetch_assoc($pkgs_query)) {
$pkgs[] = array(
'pkgid' => $pkg_rows['pkgid']
);
}
if (!empty($pkgs)) {
foreach ($pkgs as $pkg) {
$pkgid = $pkg['pkgid'];
$timestamp = strtotime($stsdate);
$statusdate = date("Y-m-d H:i:s", $timestamp);
mysql_query("INSERT INTO pkgsts (pkgid, stsdesc, stsdate, ctyid, lastchgby, lastchgat) VALUES('$pkgid', '$stsdesc', '$ctyid', '$statusdate', '$usrid', now())") or die(mysql_error());
}
}
}
You switch the columns around in your update statment
"INSERT INTO
pkgsts (pkgid, stsdesc, stsdate, ctyid, lastchgby, lastchgat)
VALUES('$pkgid', '$stsdesc', '$ctyid', '$statusdate', '$usrid', now())")
Lining your query up like above makes it obvious. Switch $ctyid and $statusdate
"INSERT INTO
pkgsts (pkgid, stsdesc, stsdate, ctyid, lastchgby, lastchgat)
VALUES('$pkgid', '$stsdesc', '$statusdate', '$ctyid', '$usrid', now())")
So you were trying to insert 2016-10-02 <time> into an INT field, so MySQL did its best to turn it into an INT, and you ended up with 2016
I have a mysql table with a field called points and that value is 19. When i change the value using:
<?php
$con=mysqli_connect("blah", 'blah', 'blah', "blah");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Social_points (`points`)
VALUES
('$_POST[Jpoints]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Which read the form data from a previous page it works fine however it merely adds the value to the end of the original value for e.g. if i had 19 as original value and then entered 5 in the form it would change to 195. Any ideas
If You have to add value as new record then use INSERT query otherwise use UPDATE query.
Use the UPDATE syntax and not insert..
$sql="UPDATE Social_points set (`points`)
VALUES
('$_POST[Jpoints]')";
Try this mate
update social_points set points = convert(varchar(5),points)+'5'
This is just a wild stab in the dark:
You're using the POST method, so I guess you're calling that script via AJAX. And my next guess is, you probably do the addition of the original value and the new value with Javascript, before the form gets sent.
So what probably happens in Javascript is this:
Instead of adding both values, they are concatenated and then sent to the DB, being treated as a string (JPoints).
If i'm right, you need to cast both values to int in your Javascript.
read the data from database.
for example you add an item
take the ID of last added item and update it.
<?php
// before this you have a query for last added item.
$data['itemid'];
$_POST['newvalue'];
$data['value'];
//if the value 19 and the new value 5 this will become 195
$newvalue = trim($data['value'] . $_POST['newvalue']);
$sql->query("UPDATE tablename SET value = '.$newvalue.' WHERE itemid = '.$data['itemid'].'");
?>
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.
I know there are a lot of topics with the same title. But mostly it's the query that's been inserted in the wrong place. But I think I placed it right.
So the problem is, that I still get 0 even when the data is inserted in the db.
Does someone knows an answer where I could be wrong?
here's my code:
mysql_query('SET NAMES utf8');
$this->arr_kolommen = $arr_kolommen;
$this->arr_waardes = $arr_waardes;
$this->tabel = $tabel;
$aantal = count($this->arr_kolommen);
//$sql="INSERT INTO `tbl_photo_lijst_zoekcriteria` ( `PLZ_FOTO` , `PLZ_ZOEKCRITERIA`,`PLZ_CATEGORIE`)VALUES ('$foto', '$zoekje','$afdeling');";
$insert = "INSERT INTO ".$this->tabel." ";
$kolommen = "(";
$waardes = " VALUES(";
for($i=0;$i<$aantal;$i++)
{
$kolommen .=$this->arr_kolommen[$i].",";
$waardes .="'".$this->arr_waardes[$i]."',";
}
$kolommen = substr($kolommen,0,-1).")";
$waardes = substr($waardes,0,-1).")";
$insert .=$kolommen.$waardes;
$result = mysql_query($insert,$this->db) or die ($this->sendErrorToMail(str_replace(" ","",str_replace("\r\n","\n",$insert))."\n\n".str_replace(" ","",str_replace("\r\n","\n",mysql_error()))));
$waarde = mysql_insert_id();
Thanks a lot in advance, because I have been breaking my head for this one for almost already a whole day. (and probably it's something small and stupid)
According to the manual mysql_insert_id returns:
The ID generated for an AUTO_INCREMENT column by the previous query on
success, 0 if the previous query does not generate an AUTO_INCREMENT
value, or FALSE if no MySQL connection was established.
Since it does not give you false and not the correct number it indicates that the queried table didn't generate an auto-increment value.
There are two possibilities I can think of:
Your table doesn't have an auto_increment field
Since you doesn't provide the link to the mysql_insert_id() but using a link with mysql_query() it might not be the correct table that's queried when retrieving the last inserted id.
Solution:
Make sure it has an auto_increment field
Provide the link aswell: $waarde = mysql_insert_id($this->db);
It is possible that your INSERT query was not successful - e.g., maybe you were trying to insert duplicate data on a column whose data must be unique?
If the id is indeed set to auto increment and still get '0' as your response do a column and value count i experienced this only later on I noticed a number of my column count did not match values count.
Codeigniter has an odd behaviourd when calling mysql_insert_id(). The function returns 0 after the first call. So calling it twice will return 0.
Use a variable instead of calling the function more times:
$id = mysql_insert_id();
I am having an issue with a simple form uploading script.
On this upload script I built to upload data to a MySql database, I can't seem to get the record to insert into the database when I include this one variable.
I figured that perhaps I am overlooking some minor coding issue, and I'm working on a deadline to get this system live...
Here is the code snippit that is giving me issues.
$title=$_REQUEST['title'];
$author=$_REQUEST['author'];
$hours=$_REQUEST['hours'];
$start_d=$_REQUEST['start_d'];
$start_m=$_REQUEST['start_m'];
$start_y=$_REQUEST['start_y'];
$end_d=$_REQUEST['end_d'];
$end_m=$_REQUEST['end_m'];
$end_y=$_REQUEST['end_y'];
$certificate=$_REQUEST['certificate'];
$required=$_REQUEST['required'];
$assessment=$_REQUEST['assessment'];
$describe=$_REQUEST['description'];
$query=mysql_query("INSERT INTO `records` (title, hours, start_date_d, start_date_m, start_date_y , end_date_d, end_date_m, end_date_y , certificate, requirement, author, approved, assessment, describe) VALUES ('$title', '$hours', '$start_d', '$start_m', '$start_y', '$end_d', '$end_m', '$end_y', '$certificate', '$required', '$author', '0', '$assessment', '$describe')");
mysql_close();
The variable that is giving me issues is the one denoted as '$describe'.
My previous testing has indicated:
The form script is collecting data correctly
The form script is passing the data to the upload script correctly via method='post'
The database connection information is correct
All of the field names in the mysql query are typed correctly
Thank you in advance for your help.
Update:
echo mysql_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 ' assessment, describe) VALUES' at line 1
this awful code should be totally rewritten.
but to solve this very problem
foreach ($_REQUEST as $key => $value) $_REQUEST[$key] = mysql_real_escape_string($value);
Something like this.
Note that i've changed date fields to date format.
$_POST['start_date'] = $_POST['start_y'].'-'.$_POST['start_m'].'-'.$_POST['start_d'];
$_POST['end_date'] = $_POST['end_y'].'-'.$_POST['end_m'].'-'.$_POST['end_d'];
$_POST['approved'] = 0;
$fields = explode(" ","title author hours start_date end_date certificate required assessment describe");
$query = "INSERT INTO `records` SET ".dbSet($fields);
mysql_query($query) or trigger_error(mysql_error().$query);
function dbSet($fields) {
$q='';
foreach ($fields as $v) $q.="`$v`='".mysql_real_escape_string($_POST[$v])."', ";
return trim($q,", ");
}
Try this:
$query="INSERT INTO `records` (title, hours, start_date_d, start_date_m, start_date_y , end_date_d, end_date_m, end_date_y , certificate, requirement, author, approved, assessment, describe) VALUES ('$title', '$hours', '$start_d', '$start_m', '$start_y', '$end_d', '$end_m', '$end_y', '$certificate', '$required', '$author', '0', '$assessment', '$describe')";
var_dump($query);
And post to us :)
It turns out that "Describe" is a reserved word in MySql.
I changed the field name, and now my script works...