Cant get PHP PDO to send to DB [duplicate] - php

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 6 years ago.
I can't get this code to set the input in form to my database, and I can't figure out why. Is there any that can help me figure you why?
I'm trying to use the form to get input from user.
<form action="" method="post">
Etternavn:<br>
<input type="text" name="etternavn" id="etternavn" placeholder="Etternavn"><br>
Fornavn:<br>
<input type="text" name="fornavn" id="fornavn" placeholder="Fornavn"><br>
Klasse:<br>
<input type="text" name="klasse" id="klasse" placeholder="Klasse"><br>
Mobil:<br>
<input type="text" name="mobli" id="mobil" placeholder="Mobil"><br>
Nettside:<br>
<input type="text" name="www" id="www" placeholder="Nettside"><br>
Epost:<br>
<input type="email" name="epost" id="epost" placeholder="Epost">
<input type="submit" name="submit" value="Submit">
</form>
Here I'm running the PHP PDO to get hold in the database and try to put the user input in to the database but I can't see why it doesn't work. I don't get any messages that tell me that anything is wrong.
<?php
if (isset($_POST["submit"])){
$host = "kark.hin.no";
$dbname = "stud_v16_klemetsen";
$username = "v16_klemetsen";
$password = "**********";
try {
$dbh = new PDO("mysql:host=$host;dbname=$dbname",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$q = $dbh->prepare("INSERT INTO studenter(etternavn,fornavn,klasse,mobil,www,epost)
VALUES (:etternavn, :fornavn, :klasse, :mobil, :www, :epost");
$q->bindParam(':etternavn',$_POST['etternavn'],PDO::PARAM_STR);
$q->bindParam(':fornavn',$_POST['fornavn'],PDO::PARAM_STR);
$q->bindParam(':klasse',$_POST['klasse'],PDO::PARAM_STR);
$q->bindParam(':mobil',$_POST['mobil'],PDO::PARAM_STR);
$q->bindParam(':adr',$_POST['www'],PDO::PARAM_STR);
$q->bindParam(':epost',$_POST['epost'],PDO::PARAM_STR);
$q->execute();
$q->execute();
echo "succssfull";
}
catch (PDOException $e){
echo "ERROR" . $e->getMessage();
}
$dbh = null;
}
?>

$q->bindParam(':adr',$_POST['www'],PDO::PARAM_STR);
This line does not match with your SQL
"INSERT INTO studenter(etternavn,fornavn,klasse,mobil,www,epost)
VALUES (:etternavn, :fornavn, :klasse, :mobil, :www, :epost"
Your bind parameter must be :www

Also, you're missing an end closing bracket ) in your SQL query, it should be:
$sql = "INSERT INTO studenter(etternavn,fornavn,klasse,mobil,www,epost)
VALUES (:etternavn, :fornavn, :klasse, :mobil, :www, :epost)";
$q = $dbh->prepare($sql);

Related

Insert function script php

i just learned about this new insert script into my database to avoid mysql injections.. but of some reason it doesn't work... My charts name is messages and then i got id and message as the text i want to come to the database...
Here is my new code:
<?php
$meddelanden = $_POST['message'];
$namn = $_SESSION['user'];
include ("connect.php");
$sql = $con->prepare('INSERT INTO messages (message,namn) VALUES (?,?)');
$sql->bind_param("ss",$meddelanden,$namn);
$sql->execute();
$sql->close();
$con->close();
?>
<form action = "meddelanden.php" id = "fromen2" method = "post">
<input type="text" name="message" id = "type" autocomplete="off"
placeholder="type your chat message">
<input type="submit" name="submit" value="Send">
</form>
Please explain what im doing wrong, i wont approve the answer if you just say what i should do instead! Thanks for any help!
You should replace si with s since you are binding only one string in it and no integers ( if $meddelanden is not an integer). Use this instead
$sql->bind_param("s",$meddelanden);
S is string, I is integer. By putting SI you are stating two variables are being passed.

Issue with inserting value into a database

what is the issue with this code , I'm using a form to insert some values into a database , i have a controller setup like that. when i submit the form , the value was not posted in the database, but if i remove all others fields and left only 2 fields in the form and post it ,it works so there's something that i miss,been trying to resolve for more than 6 hours .please some help :
//database insertion
if (isset($_POST['VideoTITLE']))
if (isset($_POST['ByArtist']))
if (isset($_POST['GroupName']))
if (isset($_POST['URL']))
if (isset($_POST['VideoDate']))
{
try
{
$sql = 'INSERT INTO videoclip SET
VideoTITLE = :VideoTITLE,
ByArtist = :ByArtist,
GroupName = :GroupName,
URL = :URL,
VideoDate = CURDATE()
';
$s = $pdo -> prepare($sql);
$s -> bindValue(':VideoTITLE',$_POST['VideoTITLE']);
$s -> bindValue(':ByArtist',$_POST['ByArtist']);
$s -> bindValue(':GroupName',$_POST['GroupName']);
$s -> bindValue(':URL',$_POST['URL']);
$s -> execute();
}
catch(PDOException $e)
{
$error = 'error adding submitted data' . $e-> getMessage();
include 'error.html.php';
exit();
}
header('Location:.');
exit();
}
here's my html form setup:
<form action="?" method="post" class="form-horizontal">
<legend>Song Info</legend>
<fieldset>
<label>Song Title </label>
<input type="text" id="VideoTITLE" name="VideoTITLE" placeholder="song name…">
<label>Artist </label>
<input type="text" id="ByArtist" name="ByArtist" placeholder="artist name…">
<label>Musical Group</label>
<input type="text" id="GroupName" name="GroupName" placeholder="Type something…">
<label>Poster link</label>
<input type="text" id="URL" name="URL" placeholder="Type something…">
</fieldset><br>
<input type="submit" class="btn btn-success" value="Post video">
</form>
Its a couple of problems, maybe more:
You have isset($_POST['VideoDate']) in your if condition which will always be false since VideoDate is not in your form. You should take this out since you seem to want to set it using CURDATE() in your insert script.
your insert statement is incorrect. mysql inserts typically look like INSERT INTO TABLE_NAME (COL1, COL2) values('VALUE1', 'VALUE2'); so you should change your insert code to look like
$sql = 'INSERT INTO videoclip (VideoTITLE, ByArtist, GroupName, URL, VideoDate) values (:VideoTITLE, :ByArtist, :GroupName, :URL, CURDATE())';
Your syntax is incorrect for INSERT. It should be something like:
$sql = 'INSERT INTO videoclip (VideoTITLE, ByArtist, GroupName, URL, VideoDate)
VALUES (:VideoTITLE, :ByArtist, :GroupName, :URL, CURDATE())';
In addition, $_POST['VideoDate'] is not valid as you do not have it in your form.
You're doing the if statements wrong.
if (isset($_POST['VideoTITLE']) && isset($_POST['ByArtist']) && isset($_POST['GroupName'])
&& isset($_POST['URL']) && isset($_POST['VideoDate'])) {
....
}
This is basic programming stuff, so you might want to get a good introductory book to programming or PHP.

PHP update on database failing - no errors [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 6 years ago.
I'm trying to update my database entries with this form:
<form method="post" action="inc/update.php">
<?php foreach ($links as $row) {
?>
<div class="btn_admin">
<p>
<label>Titulo</label>
<input type="text" name="title[]" value="<?php echo $row["desc"] ?>">
</p>
<p>
<label>Url</label>
<input type="text" name="url[]" value="<?php echo $row["url"] ?>">
<input type="hidden" name="id[]" value="<?php echo $row["id"] ?>" />
</p>
</div>
<?php }
?>
<input type="submit" name="submit" value="Update Links" />
</form>
On my update.php file:
if ($_SERVER["REQUEST_METHOD"] == "POST"
&& $_POST["submit"] == "Update Links") {
include_once 'db.php';
$db = new PDO(DB_INFO, DB_USER, DB_PASS);
foreach($_POST['id'] as $id ) {
$title=$_POST["title"][$id-1];
$url=$_POST["url"][$id-1];
$sql = "UPATE index_links
SET desc=?, url=?
WHERE id=?";
$stmt = $db->prepare($sql);
$stmt->execute(array($title, $url, $id-1));
$stmt->closeCursor();
}
}
I've looped through $title and $url and everything is being 'grabbed' correctly, but the query is failing somehow with no errors.
I have even tried messing with erroneous query syntax (like in the query in the example above - "UPATE"), no errors whatsoever... and yes, the foreach loop is being accessed.
This seems like such intro level stuff, but I'm looking at this for an hour or so no and mind=blown... there are other queries (not UPDATE ones) on my project which are working fine.
In your case, the query probably fails because desc is a reserved word in mySQL.
PDO can be very secretive about its error messages by default. See this question on how to change that.

Saving to MySQL database via html forms

I am making a php page that retrieves data from a database table and putting it in a table for the user to see via MySQLi commands.
I was wondering how I should approach the reverse situation. I want the user to be able to enter in information into textboxes and the click a button at the bottom of the page called 'save' which will prompt the user "are you sure" before saving to the database. If the user clicks 'yes', then the new entry is inserted into the database.
I have the following code to create the labels and textboxes:
<FORM>
ID: <input type="text" name="id"><br />
NM: <input type="text" name="nm"><br />
Company: <input type="text" name="company"><br />
Address: <input type="text" name="address"><br />
City: <input type="text" name="city"><br />
Zip: <input type="text" name="zip"><br />
State: <input type="text" name="state"><br />
Phone: <input type="text" name="phone"><br />
Website: <input type="text" name="web_site"><br />
</FORM>
However, when it comes to the 'save' button, I can implement the button just fine, but how would I go about saving the information entered into the database?
My initial thought process was to find the values that the user entered. I'm new to PHP and WEB dev in general, but I need to know how to get the value of the text in the textbox. Would I have to sift all the values through via the PHP Post method?
Once I have the information the user wants to enter, I was thinking maybe MySQLi has an insert function, which I found here, http://php.net/manual/en/mysqli.insert-id.php. Then it's just a quick insert and it's in the database after the user gives the 'yes' at the prompt.
Do I have the right idea in mind? Is there a more efficient way to do this?
Any help is greatly appreciated. I've looked around for problems and solutions similar to the ones related to my scenario but there were none. =(
Thanks!
EDIT:
Here is the code I have on the agentprocess.php that the action form sends the information to:
<?php
$agent_nm = $_POST['nm']; // gather all the variables
$company = $_POST['company'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$state = $_POST['state'];
$phone = $_POST['phone'];
$web_site = $_POST['web_site'];
$batch_id = $_POST['batch_id']; // added batch id
//connect
$conn = new mysqli('local', 'admin', 'pass', 'DB');
if(mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
//generate the query (doesn't add id because id is autoincremented)
$query = "INSERT INTO t_agent VALUES (NULL, " . $agent_nm . ", " . $company . ", " . $address . ", " . $city . ", " . $zip . ", " . $state . ", " . $phone . ", " . $web_site . ", " . $batch_id . ")";
//insert and close.
mysqli_query($conn, $query);
mysqli_close($conn);
Despite the code here, I've queried the table and the new entry is not there. Am I missing something here?
Thanks in advance!
Very simple example, added the label tag to the labels for your input and put it inside of a form.
<form method="post" action="process.php" id="myForm" name="myForm" >
<label for="ID">ID</label>: <input type="text" name="ID" /><br />
<label for="nm">NM:</label> <input type="text" name="nm"><br />
<label for="company">Company:</label> <input type="text" name="company"><br />
<label for="address">Address:</label> <input type="text" name="address"><br />
<label for="city">City</label>: <input type="text" name="city"><br />
<label for="zip">Zip</label>: <input type="text" name="zip"><br />
<label for="state">State</label>: <input type="text" name="state"><br />
<label for="phone">Phone</label>: <input type="text" name="phone"><br />
<label for="web_site">Website</label>: <input type="text" name="web_site"><br />
<input type="submit" name="submit" />// this is your submit button
</form>
On the process.php page
//get your inputs from the form
$ID = $_POST['ID'];
//do the same for each of the text inputs
Then you can use mysqli as you described to insert the values into your database, feel free to comment if you need any help with the mysqli part of the question, I didn't include it here since you had the link posted in the original question.
you need to use forms. yes, using the name attributes in your elements, you sift through $_POST(eg. $_POST['company']) for the values you want to store into the DB. here's an example. Use MYSQLi statements instead of mysql as in the eg.
this is simple yet a little complex task for web development beginers.
So I am going to give you an full example of what you need to do...
To do the SAVE button check the fastest way is to use javascript confirm dialog and if confirmed to submit form with javascript also.
The Mysql insert part is easy, you need to check if there is data that you submited via form in $_REQUSET (this works better than $_POST or $_GET because it catchs it both.) and then to connect to db and do an insert query...
Everything is explained in this example:
http://pastebin.com/thNmsXvn
But please use some template engine like Smarty because doing php, javascript and html in one file without template is awful and long term will give you only problems.
I think that I was very clear in the example I put on pastebin but if you have some questions feel free to ask...
Just to add, I have removed ID from HTML form because the best solution for managing ID's in MySQL is auto increment option, you configure that when you create table and set it to a specific field. Most usually it is ID, and it must be an integer.
You should use PDO functions for PHP/MySQL
id field should be autoincrement
<?php
$host= "xxx";
$username="xxx";
$password="xxx";
$database="xxx ";
// Gets data from URL parameters
$name = $_POST['nm'];
//Repeate for all other parameters
// Opens a connection to a MySQL server
try {
// DBH means "DB Handle"
// MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$database", $username, $password);
}
catch(PDOException $e) {
echo $e->getMessage();
}
// STH means "Statement Handle"
$STH = $DBH->prepare("INSERT INTO mytable ( id, nm,company,address,city,zip,state,phone,web_site ) values ( NULL,:nm,:company,:address,:city,:zip,:state,:phone,:web_site)");
$STH->bindParam(':name', $name);
//Repeate for all other parameters
$STH->execute();
//# close the connection
$DBH = null;
?>

How do I update multiple tables using prepared statements with mySQLi?

I have a form with two fields with the name attribute of 'photo_title' and 'photographer_name', and a hidden field named 'photo_id'. When the user pushes the submit button, i want it to update two separate tables in the database. I can get it to update a single table, but as soon as I try to leftjoin the second table, it doesn't like it.
I think there may be something wrong with my query string or the binding. How can I update two separate values in two separate tables in my Mysql database while still using prepared statements?
Here's the PHP:
if (array_key_exists('update', $_POST)) {
$sql = 'UPDATE photos SET photos.photo_title = ?, photographers.photographer_name = ?
LEFT JOIN photographers ON photos.photographer_id = photographers.photographer_id
WHERE photo_id = ?';
$stmt = $conn->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_param('ssi', $_POST['photo_title'], $_POST['photographer_name'], $_POST['photo_id']);
$done = $stmt->execute();
}
}
Here's the form:
<form id="form1" name="form1" method="post" action="">
<input name="photo_title" type="text" value=""/>
<textarea name="photographer_name"></textarea>
<input type="submit" name="update" value="Update entry" />
<input name="photo_id" type="hidden" value="<?php echo $photo_id ?>"/>
</form>
Here's an answer so folks who read this question see it, instead of finding it in your comment above. I'll mark this CW so I don't get any points for it.
UPDATE photos LEFT JOIN photographers
ON photos.photographer_id = photographers.photographer_id
SET photos.photo_title = ?, photographers.photographer_name = ?
WHERE photos.photo_id = ?
FWIW, the documentation for MySQL's UPDATE syntax is illustrative.
I was working on something similar. Here is a few things that I did. Hope it helps
if (isset($_POST['update'])) {
$id=intval($_GET['photo_id']);
$photo_title=$_POST['photo_title'];
$photographer_name=$_POST['photographer_name'];
$sql = "update photos p, photographers pg set p.photo_title=:photo_title, pg.photographer_name=:photographer_name where p.photographer_id=$id and pg.photographer_id=$id";
$query = $dbh->prepare($sql);
$query->bindParam(':photo_title',$photo_title,PDO::PARAM_STR);
$query->bindParam(':photographer_name',$photographer_name,PDO::PARAM_STR);
$query->execute();
}
You can even add your photo_id to the form action in case you want to use the id on a different page.
<form id="form1" name="form1" method="post" action="index.php?id=<?php echo $photo_id;?>">
<input name="photo_title" type="text" value=""/>
<textarea name="photographer_name"></textarea>
<input type="submit" name="update" value="Update entry" />
</form>
I have a file I created that connects to the database that I named config that has the following codes. Include it with this code where your form is at the top so you don't get errors executing the code above.
<?php
// DB credentials.
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','photographer');
// Establish database connection.
try{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,
DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
catch (PDOException $e){
exit("Error: " . $e->getMessage());}
?>

Categories