Insert function script php - 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.

Related

getting data from a textarea into a database

i am trying to get text from a text box into my database, but it wont go through. i have tried so many things please help!! the else statement always executes, because I get the message "no submission received on my webpage", which means the first if statement definitely executes.
As FirstOne said you need to name the input "submit".
<input class="input" type="submit" name="submit" value="شارك"/>
Hello There are two problem's with your code ..
First one add name attr in your submit button because you are checking isset($_POST['submit'])
<input class="input" type="submit" name="submit" value="شارك"/>
Second Update Your $query with this
$query= "INSERT INTO hamsasubmissions (secret,popularity) VALUES ('".$_POST["newSecret"]."',0)";
first of all you didn't give the submit button a name so you must name it 'submit' to match what you wrote in your code and also your SQL query seems to be incorrect, here's a snippet with the desired changes:
<form method="post" action="post.php">
<textarea name="newSecret" id="help" class="textarea" rows="20" cols="100">
</textarea>
<input class="input" name="submit" type="submit" value="شارك"/>
</form>
<?php
if(isset($_POST['submit'])) {
// trim possible begining/ending whitespaces from the the textarea value. But you still need to escape it againt SQL injection !
$newSecret = trim($_POST['newSecret']);
if(isset($newSecret)[0]) {
include "db_connect.php";
$query= "INSERT INTO hamsasubmissions (secret,popularity) VALUES ('" . $newSecret . "', 0)";
if(!mysqli_query($mysqli,$query)){
echo "no submission received";}
else{echo "Secret submitted.";}
}
}
?>

PHP update form that updates database information only if there is an input in that particular field using PDO

I am currently working on a form that uses PHP and SQL to update information in a database. It is functioning properly and updating the information but the issue is... is that it updates everything, including fields that I didn't even put any input in which means it will only update a particular row in the database and leave the others blanks... I need it to just change information from a field with an actual input and leave it if there is no input.
Here is the PHP and SQL code:
try {
$deleteRecId = $_GET['id'];
$update_event_name = $_POST['updateName'];
$update_event_location = $_POST['updateLocation'];
$update_event_date = $_POST['updateDate'];
include 'connect.php';
if(isset($_POST["submit"])) {
// new data
$sql = "UPDATE events SET event_name='$update_event_name',
event_location='$update_event_location', event_date='$update_event_date'
WHERE event_id=$deleteRecId";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
and here if the form:
<form class="update-form" action="<?php echo $_PHP_SELF ?>" method="post">
<p id="input-headers">Event Name</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateName" value="">
</p>
<p id="input-headers">Event Location</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateLocation" value="">
</p>
<p id="input-headers">Event Date</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateDate" value="" placeholder="01/01/2000">
</p>
<input type="submit" name="submit" value="Submit" id="updateBtn">
</form>
So to sum up I need this application to only update information of a field with an actual input and if the form field has no input I need that database info to remain the same. I appreciate any help with this as I am pretty new to these concepts... thanks!
I found a really handy solution to this! Here is how I implemented it into my code.
$sql = "UPDATE events SET event_name=IF(LENGTH('$update_event_name')=0, event_name, '$update_event_name'), event_location=IF(LENGTH('$update_event_location')=0, event_location, '$update_event_location'), event_date=IF(LENGTH('$update_event_date')=0, event_date, '$update_event_date') WHERE event_id=$deleteRecId";
It basically just checks whether the string is empty or not. If it's empty it won't be updated. If it isn't empty it'll go through with the update! Very simple way to achieve this effect when creating an update form.
Using your current code structure, you can do this.
Use SQL to select * from event ID. Populate your update_event_xxx with the parameters.
If $_POST[xx] is blank, ignore. Else, update_event_xx = $_POST[xx]

Update data WHERE

I have a table called client and I am trying to update the contact number, but for only the id that is typed in. I have a form that creates two textfields for the data to be changed. My problem is im unsure on how i can only update data for only the id that is entered.
Code:
<form method="post" name="update" >
Client ID:
<br>
<input type="text" name="clientid"><br>
Contact Number:
<br>
<input type="text" name="contactno"><br>
<input type="submit" name="submit" value="Update"><br><br>
</form>
<?php
if(isset($_POST['submit'])){
$client = $_POST['clientid'];
$contact = $_POST['contactno'];
$result= $pdo->prepare ("UPDATE client SET client_contact_number='$contact' WHERE client_id='$client'");
$result->execute;
}
?>
your syntax should be:
mysqli_query($connection, $sql_query)
you're missing the $connection object in your method.
PHP docs: http://php.net/manual/en/mysqli.query.php
*Original version of this question used procedural syntax - hence my answer.

Insert Checkbox value to Database

so im trying to store values from a checkbox into my database
It works if I use a normal Textbox but as soon as I attempt it with a checkbox it doesnt work any idea? I want to have two for example checkbox1 and checkbox2 there values should be stored in my database colums for example Colum1 colum2.
Thanks in advance for anyhelp
<form name="checkbox.php" id="names" action="<?php echo JURI::current(); ?>" method="post">
<p><input type="checkbox" name="game" value="ExampleGame" />b</p>
<p><input type="checkbox" name="Age" value="ExampleAge" />b</p>
<p><input id="submit" name="submit" type="submit" value="Submit Names" /></p>
</form>
<?
if( (isset($_POST['game'])) || (isset($_POST['Age'])) ) {
//first name or last name set, continue-->
$game = $_POST['game'];
$Age= $_POST['Age'];
$db =& JFactory::getDBO();
$query = "INSERT INTO `gameTable` (`game`, `Age`)
VALUES ($game, $age);";
$db->setQuery( $query );
$db->query();
} else {
echo '<h4>One Field Is Required!</h4>';
}
?>
Try this
$query = "INSERT INTO `gameTable` (`game`, `Age`) VALUES ('".$game."','".$age."', )";
Check the values that come back from your form:
$game = $_POST['game'];
$Age= $_POST['Age'];
You should find that if the checkbox isn't selected, no value (in fact, no field) is returned.
That may be your problem.
Use some alerts for troubleshooting:
echo $_POST['game'];
echo $_POST['Age'];
echo $_POST['query'];
Even when you don't know what you are doing/doing wrong, try to troubleshoot the problem.
Alerts help alot in PHP to check if you get the values on your variables that you expect.
If you get your query string, test this directly on your database.
I resolve with this easy way:
<input type="checkbox" name="field_name" value="N" style="display: none;" checked />
On mysql database i have create a trigger
if new.field_name= '' then set new.field_name= 'S';

MYSQL Update not updating database?

I have a simple Form along side a PHP update query that simply isn't working! I know the PHP is working on the page as there are several validation checks that need to be passed before hand which are working perfectly. The form its self is inside the Colorbox Popup tool.
My HTML Form Code is:
<div id="stylized" class="myform">
<form action="#" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_id; ?>" />
<label>First Name:<span class="small">Enter your forename</span></label>
<input id="first_name" type="text" name="first_name" maxlength="50" placeholder="e.g. Joe" required autofocus/>
<div class="spacer"></div>
<input type="submit" id="update" name="update" value="Continue to Step 2!">
</form>
</div>
With the PHP Code as follows (this is above the HTML code on the page):
<?php
if($_POST['update']){
$user_i = $_POST['user_id'];
$f_name = $_POST['first_name'];
$first_name = ucfirst($f_name);
mysql_query("UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'") or die(mysql_error());
} ?>
The actual submit appears to be working, with the Popup refreshing afterwards, but the database does not update! I have triple checked the syntax and the database fields. 'user' and 'first_name' and 'user_id' is correct.
Update: Because the popup box refreshes, I cannot view the error's from the 'or die(mysql_error()) unfortunately, other wise i might have been one step closer.
Any help would be hugely appreciated.
Many thanks in advance.
When you say pop-up box, I assume you are using ajax to communicate from the form to the server, which as you stated is difficult to view submitted data. If this is the case try:
error_log(serialize($_POST));
This will force an entry in your error log with the $_POST data in serialized format, so you can check the values you are submitting are populated correctly.
You will also want to sanitize the variables you are adding to the SQL:
$sql = "UPDATE user SET first_name = " . mysql_real_escape_string($first_name) . " WHERE user_id = " . mysql_real_escape_string($user_i) . " LIMIT 1";
mysql_query($sql);
I would:
print_r($_POST); to view the POST data.
Generate the SQL from a string so it can be printed for debugging purposes, like so:
$sql = "UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'";
echo $sql;
mysql_query($sql) or die(mysql_error());
One of these techniques will likely tell you why the PHP-generated SQL doesn't update your database record.
you set your user_id field by echo $user_id; but your variable name is set to $user_i = $_POST['user_id'];
therefore your user id field is not set and your Mysql command will fail.

Categories