MySQL PHP pdo insert value is not working - php

I have a table with
id - integer AUTO INCREMENT
productid varchar
photo varchar
I use pdo for mysql connection
the code below is giving my an error please any help
$photo = $_POST['photo'];
$product = $_SESSION['prd'];
$todo = $dblink->query("INSERT INTO productphotos VALUES (NULL, '".$product."', '".$photo."'") or die ("Erorr");
Best Reagrds
Thank You

Save yourself the trouble of concatenating values into your SQL and use a prepared statement
$stmt = $dblink->prepare('INSERT INTO productphotos VALUES (NULL, ?, ?)');
$stmt->execute([$product, $photo]);

if(isset($_POST['photo'], $_SESSION['prd'])){
//data
$photo = $_POST['photo'];
$product = $_SESSION['prd'];
$query = "INSERT INTO productphotos VALUES (NULL, :product, :photo)"
$stmt = $dblink->prepare($query);;
$stmt->bindValue(':product', $product, PDO::PARAM_STR);
$stmt->bindValue(':photo', $photo, PDO::PARAM_STR);
$stmt->execute();
}
And you should really make sure you set your connection to throw errors
$dblink->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Related

$mysqli->prepare with SQL Transactions

I am pretty new to SQL Transactions and tried to execute following statement which did unfortunately not work...
$stmt = $mysqli->prepare("
BEGIN;
INSERT INTO groups (group_name, group_desc, user_id_fk) VALUES ("'.$groupName.'","'.$groupDesc.'","'.$user_id.'");
INSERT INTO group_users (group_id_fk, user_id_fk) VALUES (LAST_INSERT_ID(), "'.$username.'");
COMMIT;
") or trigger_error($mysqli->error, E_USER_ERROR);
$stmt->execute();
$stmt->close();
Is this even possible what I am trying here or is it completely wrong?
I appreciate every response, thank you!
You are using prepare() wrong way. There is absolutely no point in using prepare() if you are adding variables directly in the query.
This is how your queries have to be executed:
$mysqli->query("BEGIN");
$sql = "INSERT INTO groups (group_name, group_desc, user_id_fk) VALUES (?,?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ssi",$groupName,$groupDesc,$user_id);
$stmt->execute();
$sql = "INSERT INTO group_users (group_id_fk, user_id_fk) VALUES (LAST_INSERT_ID(), ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$username);
$stmt->execute();
$mysqli->query("COMMIT");

Data not inserting into database to a table

I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help
You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php
Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.

I can't input the data into my table using prepared statements

I can't input the data into my MySQL table using this script:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
session_start();
include '../scripts/test_ses.php';
include 'connection.php';
$date = date("Y-m-d");
/* Set our params */
$id = $_POST['id'];
$status = $_POST['status'];
$active = 1;
$sql = "INSERT INTO TBL_Holiday (Status, Active, DateOfChange) VALUES (?, ?, ?) WHERE idRequest =$id";
$stmt = $conn->prepare($sql);
/* Bind our params */
$stmt->bind_param('iisi', $status, $active, $date, $id);
/* Execute the prepared Statement */
$stmt->execute();
/* Close the statement */
$stmt->close();
?>
The data of the variables $id, $status is set by a form is there any way to display the php error of the script by alerting it on the form page over ajax ?
remove the $id and WHERE they are used for update or delete a row, in your case insert use below query
$sql = "INSERT INTO TBL_Holiday
(Status, Active, DateOfChange) VALUES
(?, ?, ?)";
or if you wanted to update you need to use below query
$sql = "UPDATE TBL_Holiday SET
Status= ?,
Active= ?,
DateOfChange= ?
WHERE idRequest = ?";
/* Bind our params */
$stmt->bind_param('iisi', $status, $active, $date, $id);
by having its id.. make the update operation..
$sql = "UPDATE TBL_Holiday SET Status='$status', Active='$active', DateOfChange='$date' WHERE idRequest =$id";
otherwise.. make insert by ..
$sql = "INSERT INTO TBL_Holiday (Status, Active, DateOfChange) VALUES ('$status', '$active', '$date')";
Instead of using insert you need to use Update query if you need to use condition while. So your condition will be something like this,
$sql = "UPDATE TBL_Holiday SET Status= ?,Active= ?,DateOfChange=? WHERE idRequest =$id";
You're mixing an INSERT statement with an UPDATE statement
An insert statement is on the form:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3,...);
Where you're creating a new record which is not associated with any other existing rows using a where clause, i.e. you're suppose to skip that part.
Meanwhile an update statement is on the form:
UPDATE table_name
SET column1=value1, column2=value2,...
WHERE some_column=some_value;
Where you do indeed wish to associate your update with some specific row by using a where clause, to indicate which row is to be updated.
Not my favorite sources but you can take a look at insert and update.
This is the working code:
<?php
/* Set our params */
$date = date("Y-m-d");
$id = $_POST['id'];
$status = $_POST['status'];
$active = 1;
/*Create executed SQL*/
$sql = "UPDATE TBL_Holiday SET
Status= ?,
Active =?,
DateOfChange =?
WHERE idRequest = ?";
/*Prepare SQL connection*/
$stmt = $conn->prepare($sql);
/* Bind our params */
$stmt->bind_param('iisi', $status, $active, $date, $id);
/* Execute the prepared Statement */
$stmt->execute();
/* Close the statement */
$stmt->close();
?>

using bindParam with PDO

I've been scratching my head over this code for a couple of hours....
Doesn't make sense to me why it doesn't work
$isCorrect =($question->correct_answer == $body->answer) ? 1:0;
// the values are all there.......
// echo $body->question . "\n"; //335
// echo $body->user . "\n"; //51324123
// echo $question->day . "\n"; //0
// echo $isCorrect . "\n"; //0
//but still the below part fails.
$db = getConnection();
$sql = "INSERT INTO `answers` (`id`, `question_id`, `user`, `day`, `is_correct`) VALUES (NULL, ':question', ':user', ':day', :is_correct)";
$stmt = $db->prepare($sql);
$stmt->bindParam(":question_id", $body->question);
$stmt->bindParam(":user", $body->user);
$stmt->bindParam(":day", $question->day, PDO::PARAM_INT);
$stmt->bindParam(":is_correct", $isCorrect, PDO::PARAM_INT);
$stmt->execute();
gives this error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
I'm counting 4 tokens... what am I missing? Obviously I'm doing something wrong.
Try it like this:
$sql = "INSERT INTO `answers` (`id`, `question_id`, `user`, `day`, `is_correct`)
VALUES
--The :variable shouldn't be surrounded by ''--
(NULL, :question, :user, :day, :is_correct)";
$stmt = $db->prepare($sql);
//The values used in $sql should be the same here, so not :question_id but :question
$stmt->bindParam(":question", $body->question);
$stmt->bindParam(":user", $body->user);
$stmt->bindParam(":day", $question->day, PDO::PARAM_INT);
$stmt->bindParam(":is_correct", $isCorrect, PDO::PARAM_INT);
just don't use bindParam with PDO
as well as named parameters. it will save you a ton of headaches
$db = getConnection();
$sql = "INSERT INTO `answers` VALUES (NULL, ?,?,?,?)";
$data = [$body->question,$body->user,$question->day,$isCorrect];
$stmt = $db->prepare($sql)->execute($data);
change :
$stmt->bindParam(":question_id", $body->question);
to:
$stmt->bindParam(":question", $body->question);
You have use in query :question but binding with wrong key(:question_id).
$stmt->bindParam(":question_id", $body->question);
should be
$stmt->bindParam(":question", $body->question);
This is just a little typo.

mysql_insert_id, does not return the last inserted id when i place it in a function

mysql_insert_id does not return the last inserted id when i place it inside a function.
im kinda confused why it does not.
here is my code:
function addAlbum($artist,$album,$year,$genre) {
$connection = mysql_connect(HOST,USER,PASS);
$sql = 'INSERT INTO `'.TABLE_ARTIST.'` (artistName) VALUES ("'.$artist.'")';
$resultArtist = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_ALBUMS.'` (albumName) VALUES ("'.$album.'")';
$resultAlbums = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_GENRE.'` (musicGenre) VALUES ("'.$genre.'")';
$resultGenre = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_YEAR.'` (albumYear) VALUES ("'.$year.'")';
$resultYear = mysql_query($sql);
$lastId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_LINK.'` (albumsId,artistId,genreId,yearId) VALUES ("'.$lastId.'","'.$lastId.'","'.$lastId.'","'.$lastId.'")';
$resultLink = mysql_query($sql);
if(!$resultArtist && $resultAlbums && $resultGenre && $resultYear && $resultLink){
echo mysql_error();
}
}
thanks in advance
adam
You are calling mysql_insert_id() once after four separate INSERTs, and using that ID four times for albumsId, artistId, genreId and yearId. That doesn't seem right.
You should also check that your tables are using AUTO_INCREMENT fields. If not, mysql_insert_id() will not return the insert ID. See the docs:
http://www.php.net/manual/en/function.mysql-insert-id.php
I highly recommend that you use prepared statements with mysqli::prepare, perhaps via PDO. It's ultimately simpler and safer. Here's an untested example:
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
$stmt_artist = $dbh->prepare(
'INSERT INTO `table_artist` (artistName) VALUES (?)'
);
$stmt_albums = $dbh->prepare(
'INSERT INTO `table_albums` (albumName) VALUES (?)'
);
$stmt_genre = $dbh->prepare(
'INSERT INTO `table_genre` (musicGenre) VALUES (?)'
);
$stmt_year = $dbh->prepare(
'INSERT INTO `table_year` (albumYear) VALUES (?)'
);
$stmt_link = $dbh->prepare(
'INSERT INTO `table_link` (albumsId, artistId, genreId, yearId) '.
'VALUES (?, ?, ?, ?)'
);
$stmt_albums->execute(array( $artist ));
$artist_id = $dbh->lastInsertId();
$stmt_albums->execute(array( $album ));
$album_id = $dbh->lastInsertId();
$stmt_genre->execute(array( $genre ));
$genre_id = $dbh->lastInsertId();
$stmt_year->execute(array( $year ));
$year_id = $dbh->lastInsertId();
$stmt_link->execute(array( $artist_id, $album_id, $genre_id, $year_id ));
You need to call it separately for each insert, and store the result of each call separately. Like this:
$sql = 'INSERT INTO `'.TABLE_ARTIST.'` (artistName) VALUES ("'.$artist.'")';
$resultArtist = mysql_query($sql);
$lastArtistId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_ALBUMS.'` (albumName) VALUES ("'.$album.'")';
$resultAlbums = mysql_query($sql);
$lastAlbumId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_GENRE.'` (musicGenre) VALUES ("'.$genre.'")';
$resultGenre = mysql_query($sql);
$lastGenreId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_YEAR.'` (albumYear) VALUES ("'.$year.'")';
$resultYear = mysql_query($sql);
$lastYearId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_LINK.'` (albumsId,artistId,genreId,yearId) VALUES ("'.$lastAlbumId.'","'.$lastArtistId.'","'.$lastGenreId.'","'.$lastYearId.'")';
Also, it only works if each of tables you're inserting into has AUTO_INCREMENT enabled.
Did you ever try to debug your code?
With echo() (for showing your SQL queries) or var_dump() (for checking the results of e. g. mysql_insert_id(), mysql_query()).
Also check mysql_error().
Furthermore be sure to set the resource identifier in your mysql_*() functions. It's possible to have more than just one open MySQL resource - so be sure to identify the resource.
For example:
$result = mysql_query($SQL, $connection);
$lastInsertID = mysql_insert_id($connection);
And - it's very important to know that mysql_insert_id() just works with tables which have an AUTO_INCREMENT-field.
And what's also interesting with your code: you call mysql_insert_id solely after the last of 5 queries. Is this really wanted? So you only receive the ID of your last INSERT query.

Categories