trying to insert values from an old mysql_query using the new PDO and can't seem to get it. Here's the old code that works with the old method:
$query = mysql_query("INSERT INTO videos VALUES ('','$title',time(),'0','$length','','$name','$cat','$reciter','$genre')");
I've tried variations of the following code taken from another question on stack, but nothing that works for me.
$query = "UPDATE people
SET price=?,
contact=?,
fname=?,
lname=?
WHERE id=? AND
username=?";
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $price);
$stmt->bindParam(2, $contact);
$stmt->bindParam(3, $fname);
$stmt->bindParam(4, $lname);
$stmt->bindParam(5, $id);
$stmt->bindParam(6, $username);
$stmt->execute();
the first value to be inserted is an auto increment value in the db. I am at a loss as to how to write that with the new PDO. Then the third is an attempt at a timestamp. All others are values that exist in the script already.
So this is more along the lines of what I'm looking for.. Its what I have now, but doesn't work.
$sql = "INSERT INTO videos (id, title, timestamp, views, length, image, vid_url, cetegory, reciter, genre)
VALUES (:id, :title, :timestamp, :views, :length, :image, :vid_url, :category, :reciter, :genre)";
$query = $DBH->prepare($sql);
$results = $query->execute(array(
":id" => '',
":title" => $title,
":timestamp" => time(),
":views" => '0',
":length" => $length,
":image" => '',
":vid_url" => $name,
":category" => $cat,
":reciter" => $reciter,
":genre" => $genre
));
If id is an autoincrement, don't pass it to your query. If you specify a value to be inserted to an autoincrement table, sql will attempt to insert that value. so don't include it in the query, let SQL do that.
Secondly, if the third field is a timestamp, set the default to
CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
SQL will update the timestamp automatically on update or insert (if you only want it on insert just put CURRENT_TIMESTAMP. then you also can drop that row.
You can also drop the images row if you aren't inserting anything there either, no point to put something in the query if you're not using it!
Also, the key PDO looks for doesn't have the colon (:) so if your item is :title, the array key will be just 'title'. So, your code should look something like:
$sql = "INSERT INTO videos ( title, views, length,, vid_url, cetegory, reciter, genre)
VALUES (:title, :views, :length, :vid_url, :category, :reciter, :genre)";
$query = $DBH->prepare($sql);
$results = $query->execute(array(
"title" => $title,
"views" => '0',
"length" => $length,
"vid_url" => $name,
"category" => $cat,
"reciter" => $reciter,
"genre" => $genre
));
Related
I have a database set up and there are 2 different columns and I want to insert values into one of those two columns dynamically based on an ID that is passed in from $_GET. I have the bindParam variable part working, but I'm not sure how to use a variable in the INSERT INTO portion of the statement.
One column is called product1_vote and the other is product2_vote. I am getting the 1 or 2 from $_GET and I want to pass that into the prepare call to determine which column to update.
$productID = $_GET['id'];
$stmt = $pdo->prepare('INSERT INTO products (id, title, product1_vote)
VALUES(:id, :title, :product1_vote);
$id = $pdo->lastInsertId();
$title = 'Test';
$date = date('m/d/Y h:i:s', time());
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':title', $title, PDO::PARAM_STR);
$stmt->bindParam(':product1_vote', $date, PDO::PARAM_STR);
How would I go about changing the INSERT INTO part to work dynamically instead of the current hardcoded product1_vote.
Something like this to give you an idea of what I'm after:
$stmt = $pdo->prepare('INSERT INTO products (id, title, product.$productID._vote)
VALUES(:id, :title, :product.$productID._vote);
$id = $pdo->lastInsertId();
$title = 'Test';
$date = date('m/d/Y h:i:s', time());
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':title', $title, PDO::PARAM_STR);
$stmt->bindParam(':product.$productID._vote', $date, PDO::PARAM_STR);
You can't parameterise a column name, but also, to guard against SQL injection you don't want to allow direct user input into the query without validation.
A common solution to this is to make a "whitelist" of allowed values and ensure that the user-provided value matches one of them before including it in the query.
For example:
$productID = $_GET['id'];
$voteIDs = ["1", "2"];
if (!in_array($productID, $voteIDs)) {
echo "invalid input value";
die();
};
$stmt = $pdo->prepare('INSERT INTO products (id, title, product'.$productID.'_vote)
VALUES(:id, :title, :product1_vote);
P.S. It's possible this has arisen because your database could be better normalised. If you have multiple votes per product, consider storing them in a separate "productVotes" table with a foreign key back to the products table. Then you wouldn't need to vary the column names in your query.
I'm getting the error "SQLSTATE[HY093]: Invalid parameter number" when I try to run the below function:
function add_persist($db, $user_id) {
$hash = md5("per11".$user_id."sist11".time());
$future = time()+(60*60*24*14);
$sql = "INSERT INTO persist (user_id, hash, expire) VALUES (:user_id, :hash, :expire) ON DUPLICATE KEY UPDATE hash=:hash";
$stm = $db->prepare($sql);
$stm->execute(array(":user_id" => $user_id, ":hash" => $hash, ":expire" => $future));
return $hash;
}
I feel like it's something simple that I'm just not catching. Any ideas?
Try:
$sql = "INSERT INTO persist (user_id, hash, expire)
VALUES (:user_id, :hash, :expire)
ON DUPLICATE KEY UPDATE hash=:hash2";
and
$stm->execute(
array(":user_id" => $user_id,
":hash" => $hash,
":expire" => $future,
":hash2" => $hash)
);
Excerpt from the documentation (http://php.net/manual/en/pdo.prepare.php):
You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute(). You cannot use a named parameter marker of the same name twice in a prepared statement. You cannot bind multiple values to a single named parameter in, for example, the IN() clause of an SQL statement.
This is one limitation to using PDO. PDO simply acknowledges the number of parameters in the query and the execution and throws an error on any mismatch. If you need to use parameter repetition in your queries, you have to go about it using a workaround
$sql = "insert into persist(user_id, hash, expire) values
(:user_id, :hash, :value) on duplicate key update
hash = :hash2";
$stm->execute(array(':user_id' => $user_id, ':hash' => $hash, ':hash2' => $hash,
':expire' => $expire));
You can refer to this for a more elaborate workaround - https://stackoverflow.com/a/7604080/1957346
I know this is an old question, however I think it's worth noting that a more appropriate solution would be to avoid clunky workarounds in PHP by leveraging SQL appropriately:
INSERT INTO `persist` (`user_id`, `hash`, `expire`)
VALUES (:user_id, :hash, :expire)
ON DUPLICATE KEY UPDATE `hash`=VALUES(`hash`)
This way, you only need to send the value once.
$stmt = $con->prepare("INSERT INTO items(Name, Description, Price, Country_Made, Status, Add_Date) VALUES( :zname, :zdesc, :zprice, :zcountry, zstatus, now())");
$stmt-> execute(array(
"zname" => $name,
"zdesc" => $desc,
"zprice" => $price,
"zcountry" => $country,
"zstatus" => $status
));
I'm getting the error "SQLSTATE[HY093]: Invalid parameter number" when I try to run the below function:
function add_persist($db, $user_id) {
$hash = md5("per11".$user_id."sist11".time());
$future = time()+(60*60*24*14);
$sql = "INSERT INTO persist (user_id, hash, expire) VALUES (:user_id, :hash, :expire) ON DUPLICATE KEY UPDATE hash=:hash";
$stm = $db->prepare($sql);
$stm->execute(array(":user_id" => $user_id, ":hash" => $hash, ":expire" => $future));
return $hash;
}
I feel like it's something simple that I'm just not catching. Any ideas?
Try:
$sql = "INSERT INTO persist (user_id, hash, expire)
VALUES (:user_id, :hash, :expire)
ON DUPLICATE KEY UPDATE hash=:hash2";
and
$stm->execute(
array(":user_id" => $user_id,
":hash" => $hash,
":expire" => $future,
":hash2" => $hash)
);
Excerpt from the documentation (http://php.net/manual/en/pdo.prepare.php):
You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute(). You cannot use a named parameter marker of the same name twice in a prepared statement. You cannot bind multiple values to a single named parameter in, for example, the IN() clause of an SQL statement.
This is one limitation to using PDO. PDO simply acknowledges the number of parameters in the query and the execution and throws an error on any mismatch. If you need to use parameter repetition in your queries, you have to go about it using a workaround
$sql = "insert into persist(user_id, hash, expire) values
(:user_id, :hash, :value) on duplicate key update
hash = :hash2";
$stm->execute(array(':user_id' => $user_id, ':hash' => $hash, ':hash2' => $hash,
':expire' => $expire));
You can refer to this for a more elaborate workaround - https://stackoverflow.com/a/7604080/1957346
I know this is an old question, however I think it's worth noting that a more appropriate solution would be to avoid clunky workarounds in PHP by leveraging SQL appropriately:
INSERT INTO `persist` (`user_id`, `hash`, `expire`)
VALUES (:user_id, :hash, :expire)
ON DUPLICATE KEY UPDATE `hash`=VALUES(`hash`)
This way, you only need to send the value once.
$stmt = $con->prepare("INSERT INTO items(Name, Description, Price, Country_Made, Status, Add_Date) VALUES( :zname, :zdesc, :zprice, :zcountry, zstatus, now())");
$stmt-> execute(array(
"zname" => $name,
"zdesc" => $desc,
"zprice" => $price,
"zcountry" => $country,
"zstatus" => $status
));
Database Structure:
Encoding into JSON:
I have some JSON encoded anime info stored on a text file using this code:
$info = array(
'mal_id' => $id,
'image' => $src,
'title' => $title,
'alt_title_eng' => $alt_eng,
'alt_title_syn' => $alt_syn,
'type' => $type,
'status' => $status,
'episodes' => $ep,
'genres' => $genres,
'rank' => $rank,
'synopsis' => $syno,
'modified' => date("Y-m-d H:i:s"),
'user' => 'system'
);
file_put_contents("scrap/anime-$id.txt", json_encode($info));
The contents of the text file is:
{"mal_id":18679,"image":"http:\/\/localhost\/images\/anime\/5\/54379.jpg","title":"Kill la Kill","alt_title_eng":" KILL la KILL","alt_title_syn":" KLK","type":" TV","status":" Currently Airing","episodes":25,"genres":"Action, Comedy, School","rank":421,"synopsis":"The story is set on a high school that the student council president Satsuki Kiryuuin rules by force....","user":"system"}
Decoding JSON and inserting into database
I'm trying to json_decode the contents and insert the values in mysql. The code I made without success is this:
$id= '18679';
$TABLE_PREFIX = 'exp_';
$dbh = new PDO('mysql:host='.$dbhost.';dbname='.$database.';charset=utf8', $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$JSON = json_decode(file_get_contents("scrap/anime-$id.txt"));
$stmt = $dbh->prepare("INSERT INTO {$TABLE_PREFIX}animedb
(mal_id, image, title, alt_title_eng, alt_title_syn, type, status, episodes, genres, rank, synopsis, modified, user)
values(:mal_id, :image, :title, :alt_title_eng, :alt_title_syn, :type, :status, :episodes, :genres, :rank, :synopsis, :modified, :user)
on duplicate key update title= :title, image= :image, alt_title_eng= :alt_title_eng, alt_title_syn= :alt_title_syn, status= :status, episodes= :episodes, genres= :genres, rank= :rank, synopsis= :synopsis, modified= :modified, user= :user");
$user = 'system';
$modified = 'NOW()';
$stmt->bindParam(':mal_id', $id);
$stmt->bindParam(':image', $JSON->image, PDO::PARAM_STR);
$stmt->bindParam(':title', $JSON->title, PDO::PARAM_STR);
$stmt->bindParam(':alt_title_eng', $JSON->alt_title_eng, PDO::PARAM_STR);
$stmt->bindParam(':alt_title_syn', $JSON->alt_title_syn, PDO::PARAM_STR);
$stmt->bindParam(':type', $JSON->type, PDO::PARAM_STR);
$stmt->bindParam(':status', $JSON->status, PDO::PARAM_STR);
$stmt->bindParam(':episodes', $JSON->episodes);
$stmt->bindParam(':genres', $JSON->genres, PDO::PARAM_STR);
$stmt->bindParam(':rank', $JSON->rank);
$stmt->bindParam(':synopsis', $JSON->synopsis, PDO::PARAM_STR);
$stmt->bindParam(':modified', $modified, PDO::PARAM_STR);
$stmt->bindParam(':user', $user, PDO::PARAM_STR);
$stmt->execute() ;
Problem:
Using try/catch, I'm only getting this error:
SQLSTATE[HY093]: Invalid parameter number
I've searched for solutions for this error message, but couldn't find the right solution for my problem.
Is your SQL query has been tested ? Otherwise, try
... on duplicate key update title= values(title), ...
instead of
... on duplicate key update title= :title, ...
I'm getting the error "SQLSTATE[HY093]: Invalid parameter number" when I try to run the below function:
function add_persist($db, $user_id) {
$hash = md5("per11".$user_id."sist11".time());
$future = time()+(60*60*24*14);
$sql = "INSERT INTO persist (user_id, hash, expire) VALUES (:user_id, :hash, :expire) ON DUPLICATE KEY UPDATE hash=:hash";
$stm = $db->prepare($sql);
$stm->execute(array(":user_id" => $user_id, ":hash" => $hash, ":expire" => $future));
return $hash;
}
I feel like it's something simple that I'm just not catching. Any ideas?
Try:
$sql = "INSERT INTO persist (user_id, hash, expire)
VALUES (:user_id, :hash, :expire)
ON DUPLICATE KEY UPDATE hash=:hash2";
and
$stm->execute(
array(":user_id" => $user_id,
":hash" => $hash,
":expire" => $future,
":hash2" => $hash)
);
Excerpt from the documentation (http://php.net/manual/en/pdo.prepare.php):
You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute(). You cannot use a named parameter marker of the same name twice in a prepared statement. You cannot bind multiple values to a single named parameter in, for example, the IN() clause of an SQL statement.
This is one limitation to using PDO. PDO simply acknowledges the number of parameters in the query and the execution and throws an error on any mismatch. If you need to use parameter repetition in your queries, you have to go about it using a workaround
$sql = "insert into persist(user_id, hash, expire) values
(:user_id, :hash, :value) on duplicate key update
hash = :hash2";
$stm->execute(array(':user_id' => $user_id, ':hash' => $hash, ':hash2' => $hash,
':expire' => $expire));
You can refer to this for a more elaborate workaround - https://stackoverflow.com/a/7604080/1957346
I know this is an old question, however I think it's worth noting that a more appropriate solution would be to avoid clunky workarounds in PHP by leveraging SQL appropriately:
INSERT INTO `persist` (`user_id`, `hash`, `expire`)
VALUES (:user_id, :hash, :expire)
ON DUPLICATE KEY UPDATE `hash`=VALUES(`hash`)
This way, you only need to send the value once.
$stmt = $con->prepare("INSERT INTO items(Name, Description, Price, Country_Made, Status, Add_Date) VALUES( :zname, :zdesc, :zprice, :zcountry, zstatus, now())");
$stmt-> execute(array(
"zname" => $name,
"zdesc" => $desc,
"zprice" => $price,
"zcountry" => $country,
"zstatus" => $status
));