Problems with "mysqli_insert_id" - mysql

need a little help with adding product to database. error reported on "mysqli_insert_id" line Here is my code:
// Add this product into the database now
$sql = mysqli_query($myConnection,"INSERT INTO products (product_name, price, details, category, subcategory, date_added)
VALUES('$product_name','$price','$details','$category','$subcategory',now())") or die (mysql_error());
$pid = mysqli_insert_id($sql);
// Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../inventory_images/$newname");
header("location: inventory_list.php");
exit();
Here is the Error it produces:
Warning: mysqli_insert_id() expects parameter 1 to be mysqli, boolean given in /.....line 45
"Funny thing is that it still inserts the text into database & it shows up on my site but I still get the Error if I add another product.
my table does have Auto_Increment set on id
Any help would be greatly appreciated. Ralph

Check the documentation for mysqli_insert_id():
mixed mysqli_insert_id ( mysqli $link )
The argument to the function should be your $myConnection resource, not the $sql result from your INSERT statement.
When you run an INSERT statement, mysqli_query() returns TRUE on success or FALSE on failure.
So you're passing the boolean value TRUE instead of a connection resource.

Related

pdo binding parameters in loop

I have following sql statement:
$sql = "UPDATE houses SET title=:title ";
which I dynamically edit according to object "location", which could have several paramaters (some of them could be null, thefore they are omitted)
//are there any location parameters which need to be added to query?
if (isset($house->location)){
//go through them and add them to query
foreach ($house->location as $key=>$locationParameter) {
$sql.=','.$key.'=:'.$key;
}
//finish query
$sql.=" WHERE id=:id";
$stmt = $db->prepare($sql);
//bind all defined location parameters to query
foreach ($house->location as $key=>$locationParameter) {
$stmt->bindParam($key, $locationParameter);
}
} else {
//there are none location parameters, so prepare just the original query with title and id
$sql.=" WHERE id=:id";
$stmt = $db->prepare($sql);
}
//and finally bind the required parameters
$stmt->bindParam("title", $house->title);
$stmt->bindParam("id", $id);
$stmt->execute();
When I echoed the query (echo $sql) it looked just as I want and also all binded parameters were right, BUT when I run the query all database columns for location parameters are updated just with the last value from location object, for example:
$house->location->lat is 25.5
$house->location->lon is 28.755
$house->location->city is munich
After execution of query with this object, the columns in DB for lat, lon, and city are all filled with "munich".
Could you tell me, what am I doing wrong?
+var_dump($sql) ->
string 'UPDATE houses SET title=:title,lat=:lat,lon=:lon,city=:city WHERE id=:id'
without reading entire question though, just caught my eye
the columns in DB for lat, lon, and city are all filled with "munich".
quoting from PDO tag wiki:
If you don't know if you need bindValue() or bindParam(), go for the former. bindValue() is less ambiguous and has lesser side effects.
most likely a cause.

Mysql delete query won't work on lamp stack

I am doing a project work on php. During my work every single query work smoothly. But when I want to delete any object using it won't delete ...
Here's my php code
<?php
//delete item
if(isset($_GET['deletecat'])){
$id_to_delete = $_GET['deletecat'];
$sql = mysql_query("DELETE FROM `category` WHERE `Category_id`=$id_to_delete LIMIT 1") or die('Error: Could not delete.');
}
else{
header('location: category.php');
exit();
}
?>
and after that I only get the error message.
GET value is OK. And on my phpmyadmin this SQL running OK. But there's a pop up message appear when I want to delete any object. what can I do now?
there's a few layers where you could be having issues: with the db connection, the query, or the data which you are sending.
also, you are not filtering for " and ' marks so you could be in trouble there, and you're not ensuring that your id is a number so your sql could also be failing there.
but, you can figure that out with a few adjustments to your code.... you can insert some diagnostics into your code to see what mysql is reporting the error as and get a better idea of how to fix it.
note that it is [generally recommended][1] to use mysqli extension instead of mysql extension, but irregardless, here's sample code with the extension you are currently using
hope this helps!
<?php
if ( isset($_GET['deletecat'])) {
#dbh -> database resource.
$dbh = mysql_connect()
#mysql_connect returns false if it fails. capture error and echo to output.
if (!$dbh) {
die("Could not connect to database server: ".mysql_error()."\n");
#if using mysqli use mysql_connect_error() instead
}
#never trust input. use an escape function.
$id_to_delete = mysql_real_escape_string($_GET['deletecat'],$dbh);
#force $id_to_delete to be treated as a number, or make it safer in your sql.
#i used the latter method below.
$sql = "DELETE FROM `category` WHERE `Category_id` = '$id_to_delete' LIMIT 1");
#mysql_query returns false on failure
$result = mysql_query($sql,$dbh);
#on failure catch the error and display the exact contents of 'deletecat' in a web-friendly way.
if (!$result) {
$error=mysql_error($dbh);
die ("Error: Could not delete '"
.htmlentities(print_r($_GET['deletecat'],true)).". Error: $error\n"
);
}
#if we did not trigger die() above we are ok.
header('location: category.php');
exit();
}
?>
:
[1]: see warning at http://php.net/manual/en/function.mysql-connect.php
You should escape the GET variable first to avoid any SQl injection attacks as already said by deceze. Then, you should understand that the message given by phpmyadmin is a confirmation if you need to execute the delete query. you can use mysql_real_escape_string($value) to escape but as php vendor says, this function will be removed very soon and is currently deprecated.
bye..

"Unknown column in 'field list'", but column does exist

DROP TABLE IF EXISTS `transactions`;
CREATE TABLE `transactions` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`purchase_date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `transactions` (`purchase_date`) VALUES (NULL)
I've isolated my problem in this code. When I run it, I get the error:
[ERROR in query 3] Unknown column 'purchase_date' in 'field list'
Anyone an idea?
There is an unprintable character 30 (RecordSeparator) inserted between purchase_date and the ' in the INSERT statement. Just remove the text ('purchase_date') and rewrite it by hand it should be fine.
Nery niche solution when I got this error.
I had a BEFORE INSERT trigger on my table that did something with
NEW.`field_mysql_doesnt_think_exists`
and if I didn't pass that field to an insert statement then I would get
[ERROR in query 3] Unknown column 'field_mysql_doesnt_think_exists' in 'field list'
I just spent the better part of a day figuring this out. My problem was the same: invisible characters kiboshing the query and returning the "unknown column" error.
I solved it by wading back into Windows and removing the garbage using NotePad++.
How did the garbage get in there in the first place? I think it was because I made the mistake of copying some long complex queries into LibreOffice Writer (my functional specs document) instead of just bookmarking them in phpMyAdmin or saving them in a text editor. Pasting them from LibreOffice into the query window is where (I think) the garbage originated.
Once there, it persisted like Malaria. I couldn't even get rid of it by hand-retyping the whole query -- I had to put it into NotePad++ (Encoding menu) and show ANSI and the UTF8 combos and then remove the garbage by hand.
Once that was done, the query worked.
This can also happen if you paste a column name when building the table structure. Same error - but the unprintable/invisible characters are in the table structure, not the query.
I have had the same issue this morning and I didn't find my answer.
But I found my problem when I changed the single quotes around my query to double quotes. Something so small and an oversight can cause a real headache.
Unknown column x in "field list" - Code below wrapped in single quotes - Non working.
$likepost='INSERT INTO reaction(reaction_num,userreaction_id,timereacted,
streamitem_id,comment_posted_on)
VALUES ($reaction,$target,NOW(),$streamid,$comment_id)';
Code below wrapped in double quotes. working
$likepost="INSERT INTO reaction(reaction_num,userreaction_id,timereacted,
streamitem_id,comment_posted_on)
VALUES ($reaction,$target,NOW(),$streamid,$comment_id)";
This might not help anyone else, but adding this "just in case" it helps someone.
I receive large datasets as Excel CSV files and use a (WIL) script to convert the .csv file into an importable .sql file.
I had an error in my conversion script whereby these two lines did not reference the same table name (I had hard-coded the first location and forgot to update it):
* "INSERT INTO `old_table_name` (`cid`, `date`, etc etc"
* "CREATE TABLE IF NOT EXISTS `":_dbName:"` (etc etc "
I just changed the first line to also get the table name from the variable, and voila!
* "INSERT INTO `":_dbName:"` (`cid`, `date`, etc etc"
So check those two lines in your import SQL file.
Same error in a different scenario:
This also happens when you miss # symbol for a variable.
SET #myVar1=1; SELECT #myVar1; -- GOOD, correctly prints: 1
SET #myVar1=1; SELECT myVar1; -- BAD, prints: Unknown column 'myVar1' in 'field list'
when you want to work with mysql using a function like this:
function insert($table, $info_array){
// implode keys as columns by [`,`] glue string
$columns = implode("`,`", array_keys($info_array));
// implode values as sql ready values by [','] glue string
$values = implode("','", array_values($info_array));
// make query(careful about [`] for columns name and ['] for values)
$sql = "INSERT INTO ".$table." (`".$columns."`) VALUES ('".$values."');";
return $sql;
}
you should be careful about [ ` ] for table columns names and [ ' ] or [ " ] for values.
for example, I used above function this way:
try{
$db_insert_sample_user = $connection->query(insert(TABLE_PREFIX."users", [
"username" => "my_name_2",
"password" => md5("how457fty")
]));
echo '<pre>';
print_r($db_insert_sample_user);
echo '</pre>';
}catch (PDOException $exc){
echo '<pre>';
print_r($exc);
echo '</pre>';
}
the query string is this:
INSERT INTO php_pdo_users (`username`,`password`) VALUES ('my_name_2','ee04708d313adf4ff8ba321acf3eb568');
and the result was like : (for two users)
PHPMyAdmin Result
if you want functions based on prepared statements, test this : (placeholders, params and values, don't need [ ' ] or [ " ] at all!!!)
function insert_prepared(PDO $connection, $table, $info_array){
// columns
$columns = implode("`,`", array_keys($info_array));
// placeholders
$place_holders = [];
for ( $i = 0; count(array_keys($info_array)) > $i; $i++){
$place_holders[] = '?';
}
// convert placeholders to query string
$place_holders_str = implode(",", $place_holders);
$prepared_stmt = "INSERT INTO ".$table." (`".$columns."`) VALUES (".$place_holders_str.");";
// prepare statement
$stmt = $connection->prepare($prepared_stmt);
// values
$values = array_values($info_array);
// bind all params to values
for($i = 0; count($values) > $i; $i++){
$stmt->bindParam($i + 1, $values[$i]);
}
// execute and return results
return $stmt->execute();
}
after code execution this way :
try {
$db_insert_sample_user = insert_prepared(
$connection,
TABLE_PREFIX . "users",
[
"username" => "my_name_4",
"password" => md5( "HelloDolly#__3" )
]
);
} catch ( PDOException $exc ) {
echo "Failed : " . $exc->getMessage();
}
results is :
Results with insert_prepared function
I was using a mysql procedure and in the procedure parameter I used phone with an extra space instead of phone with no extra space, due to this when ever I called the function. It just throw error no such column as phone . Until I miraculously spotted it and corrected it using phpMyAdmin, Error went off.
I had this same PYMYSQL error in my Python program when I found this answer.
I probably violated a Pandas rule when I created a new dataframe ...
This created same the error above: A phantom column
inddata = dat[['ind_id','iso3c','date','data']]
dat.to_sql(name='inddata', con=engine, if_exists='append', index=False, chunksize=200)
This fixed the error:
dat2 = dat[['ind_id','iso3c','date','data']]
inddata = dat2.copy()
dat.to_sql(name='inddata', con=engine, if_exists='append', index=False, chunksize=200)
Look at the name of the table you are handling

mysql last url id always comes out to 0

$urlid = mysql_query("SELECT URL_Id FROM url ORDER BY URL_Id DESC LIMIT 1");
foreach($textnode as $key => $value) {
$value = stripslashes($value);
$value = mysql_real_escape_string($value, $con);
mysql_query("INSERT INTO paragraphs (paragraphs, URL_Id)
VALUES ('$value', '$urlid')");
}
has been returning 0 for the URL_Id column. Any suggestions ? It should be returning 1.
mysql_query function retrieving only resource object. then you need to go with looping and retrieve actual data by mysql_fetch_array() function.
i.e:
while($rowFeach = mysql_fetch_array($urlid));
print_r($rowFeach);
try this.
Thanks.
mysql_query returns a resource to the query results, not the actual selected values.
Please recheck the docs and examples in there.
(Side-note: That select could get expensive depending on the database type, and if your code has any threading, directly or indirectly (e.g. run from a web server with multiple processes), you'll get unexpected duplicate url ids).
mysql_query always returns a resource. Use either sql_fecth_assoc or mysql_fecth_array to get the values in the resource.

How could a query fail to insert data into mysql that is retrieved from WEB?

I need to insert some data into mysql. I am not sure if I need to check the inputs OR format/strip them before they could be inserted into database fields as results returned from web may contain characters that mysql do not accept(I think). I have trouble with inserting tweets into mysql table. The type of field is varchar. This is insert statement in php script:
$json = $_POST['msg_top'];
$msg = json_decode($json);
foreach($msg->entry as $status)
{
$t = $status->content;
$query = "INSERT INTO msg2(id,msg,msg_id,depth) VALUES ('','$t','ID','3')";
mysql_query($query);
if(!mysql_query($query, $dbh))
{die('error:' .mysql_error());}
}
Yes, it's very important to escape all values before using them in an SQL command.
$json = $_POST['msg_top'];
$msg = json_decode($json);
foreach($msg->entry as $status) {
$t = mysql_real_escape_string($status->content);
$query = "INSERT INTO msg2(id,msg,msg_id,depth) VALUES ('','$t','ID','3')";
mysql_query($query);
if( !mysql_query($query, $dbh) ) {
die('error:' .mysql_error());
}
}
Also, other possible issues with your query:
If the id field is auto_increment'ing, you don't need it in the field or value list.
I may be missing something, but why are you using the string 'ID' for the msg_id field?
As for help troubleshooting this, I'd recommend just appending all of the $query strings to a log file for later inspection. Then, if problems aren't readily apparent, you can just manually try to run the command on the database (ie: maybe via PhpMyAdmin) and check out any error codes from there.