php function returns no result - php

I wrote a simple php function in an attempt to learn php and functions within php.
The goal of the function is to upload a new user to a db
Here is my function
function upload_user($pId, $pName, $pEmail, $pPhone ){
$sql = "INSERT INTO users (member_id, name, email, phone) VALUES ('$pId', '$pName', '$pEmail', '$pPhone')";
mysql_query($sql);
}
Here Is my Form
<form name="register" method="post">
<input type="text" value="name" name="name">
<input type="text" value="email" name="email">
<input type="text" value="phone" name="phone">
<input type="submit" name="submit" value="register" />
</form>
if(isset($_POST['submit'])){
$id = rand(100, 10000);
$name = $_POST['name'];
$email= $_POST['email'];
$phone = $_POST['phone'];
upload_user($id,$name,$email,$phone);
}
I know I am connecting successfully to the db since I did a test to echo out if the connection is successful or not. I also have php errors switched onini_set('error_reporting', E_ALL); but it gives me no warnings or errors
My Problem
Nothing happens with the above function, i.e. the result is just blank. If anyone can point out to me what I am doing wrong it will be really appreciated.

I think most likely that the function doen't know about the database connection so you need to either pass the db connection object as a parameter to the function or use the global identifier inside the function.
function upload_user($dbconn, $pId, $pName, $pEmail, $pPhone ){
$sql = "INSERT INTO `users` (`member_id`, `name`, `email`, `phone`) VALUES ('$pId', '$pName', '$pEmail', '$pPhone')";
mysql_query($sql,$dbconn);
}
function upload_user($pId, $pName, $pEmail, $pPhone ){
global $dbconn;
$sql = "INSERT INTO `users` (`member_id`, `name`, `email`, `phone`) VALUES ('$pId', '$pName', '$pEmail', '$pPhone')";
mysql_query($sql,$dbconn);
}
Neither of these will return a value - what you return from the function is up to you , if indeed you even want to return a value. You could use the response from the query ( true or false ) as the return:
function upload_user($pId, $pName, $pEmail, $pPhone ){
global $dbconn;
$sql = "INSERT INTO `users` (`member_id`, `name`, `email`, `phone`) VALUES ('$pId', '$pName', '$pEmail', '$pPhone')";
return mysql_query($sql,$dbconn);
}
if(isset($_POST['submit'])){
$id = rand(100, 10000);
$name = $_POST['name'];
$email= $_POST['email'];
$phone = $_POST['phone'];
/* using ternary notation to echo something based on return value of function */
echo upload_user($id,$name,$email,$phone) ? 'Success' : 'Sorry, it failed';
}
You should be aware that certain words, in mysql and other rdbms, have special significance - so it is better to always ( imo ) to encase the field names in backticks. Also worth noting is that the mysql_* suite of functions are deprecated and it s advised to use either mysqli or pdo ~ and where you use user supplied content in your code ( form submission data generally or querystrings ) you should use prepared statements to guard against sql injection.

mysql accepts a link_identifier
link_identifier : The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. reference
So you should pass a connection parameter as noted in other answers. After every connection made, you should close the connection so that you don't run into too manny connections server errors.

Related

PHP + MySQLi Query post null row

dear Stackoverflow users, I start learning PHP and MySQLi. And now I have some issues. On every page reload in DB added 1 full empty row, every cell is null. Can someone give me advice about issue? Code below:
PHP before html tag:
<?php
$mysqli = new mysqli("", "", "", "");
$mysqli->set_charset('utf8');
$name = $mysqli->real_escape_string($_POST['name']);
$email = $mysqli->real_escape_string($_POST['email']);
$link = $mysqli->real_escape_string($_POST['link']);
$query = "INSERT INTO demos (name, email, link) VALUES ('$name', '$email', '$link')";
$mysqli->query($query);
$mysqli->close();
?>
HTML inside body tag:
<form action="" method="post">
<input type="text" name="name" maxlength="20" required />
<input type="text" name="email" required />
<input type="text" name="link" required />
<input type="submit" value="Send" />
</form>
You should first check if your form is submitted by using isset or !empty.
By using isset, you can check wether or not a variable is set:
<?php
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['link'])) {
// your code
}
?>
By using !empty, you can check if a variable is set and not empty. Note however that if you are using empty you can not submit a '0' or leave a field blank.
<?php
if(!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['link'])) {
// your code
}
?>
Try using prepared statement for easier use and protection for SQL injection:
$stmt = $mysqli->prepare("INSERT INTO demos (name, email, link) VALUES(?, ?, ?)");
$stmt->bind_param("sss", $name, $email,$link);
$stmt->execute();
Read more about prepared statements: https://www.w3schools.com/php/php_mysql_prepared_statements.asp
Use var_dump to debug your code to make sure the values are not null
Add this before and after escaping the strings:
var_dump(array($name, $email, $link));
Also, switch to using prepared statements
$stmt = $mysqli->prepare("INSERT INTO demos (name, email, link) VALUES (?,?,?)");
$stmt->bind_param('sss', $name, $email, $link); // bind vars to the parameter
$stmt->execute(); // Execute statement

How to insert a new record to the table created in mysql

I created a table in mysql as'cus_info'. It has columns as 'iD' 'NAME' 'PASSWORD' 'eMAIL'. iD column is auto increment. I want to insert a new row to this table when a new customer registered. For that I wrote the following code in PHP
<?php
error_reporting(0);
require "init.php";
$name = $_POST["name"];
$password = $_POST["password"];
$email = $_POST["email"];
$sql = "INSERT INTO `cus_info` (`name`, `password`, `email`) VALUES ('".$name."', '".$password."', '".$email."');";
if(!mysql_query($con, $sql)){
echo '{"message":"Unable to save the data to the database."}';
}
?>
but always I get the message as "unable to save data to the database"
Could you please tell me where I have gone wrong?
Thanks in advanced.
Could you please tell me where I have gone wrong?
In more than one place.
To most directly answer your question, you can use mysql_error() to print the error you're getting from mysql. To even more directly answer it, you have swapped the order of the parameters and you don't need the semicolon to be included in the query. (See example code here.)
You shouldn't be using PHP's "mysql_*" functions, which were deprecated in PHP5.5 and even removed in PHP7. You also should not be passing user input from a form directly into a MySQL database without any cleaning.
First show your $con and then put error_reporting(1) to check if other error occurs.
And finnaly copy and replace in your code.
$sql = "INSERT INTO `cus_info` (`name`, `password`, `email`) VALUES ('".$name."', '".$password."', '".$email."')";
Try This
<?php
error_reporting(0);
require "init.php";
if(isset($_REQUEST["save"]))
{
$name = $_POST["name"];
$password = $_POST["password"];
$email = $_POST["email"];
$sql = mysql_query("INSERT INTO `cus_info` (`name`,`password`,`email`) VALUES ('$name','$password','$email')");
$values=mysql_insert_id();
if($values!='')
{
echo '{"message":"Successfully save the data to the database."}';
}
else
{
echo '{"message":"Unable to save the data to the database."}';
}
}
?>

Entries to the database automatically after reload the web site

( Sorry for my bad english )
I am new to PHP. I have two input fields. One for the username and one for the comment. My problem is when I Reloaded my page that simply blank entries I posted my table. Why is that?
Existing Code :
$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');
if(!db){
exit ("Verbindungsfehler:" . mysqli_connect_error());
}
$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
Seeing that your code is coming from a POST form, you can use a conditional statement around it.
For example, in your HTML form:
<input type="submit" name="submit" value="Submit" />
then use:
if(isset($_POST['submit'])){
$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');
if(!db){
exit ("Verbindungsfehler:" . mysqli_connect_error());
}
$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
}
another thing is to make sure that fields are not left empty, using empty() I.e.:
if(empty($_POST['username'])){
echo "Enter a username.";
exit;
}
also isset(). I.e.:
if(isset($_POST['username'])){
// do something
}
You can also use a header("Location: http://www.example.com/page.php");
but make sure there is nothing else above your PHP, echo, HTML, etc.
In regards to your present code:
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements, it's much safer.

Prepared statement not populating DB

I'm trying to make my first prepared statement work, but so far I'm unsuccesful. I hope you're able to help me out. I have an index.html with a simple form that parses it's data to insert.php. However, the data is not being written into my DB. Here's what I've got:
insert.php
if (isset($_POST['submit'])) {
$mysqli = new mysqli("hosts","user","pass","db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO mail_platform (first_name, last_name, email, preference_exchange, preference_news) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param('sssii', $first_name, $last_name, $email, $preference_exchange, $preference_news);
$first_name = isset($_POST['first_name'])
? $mysqli->real_escape_string($_POST['first_name'])
: '';
$last_name = isset($_POST['last_name'])
? $mysqli->real_escape_string($_POST['last_name'])
: '';
$email = isset($_POST['email'])
? $mysqli->real_escape_string($_POST['email'])
: '';
$preference_exchange = isset($_POST['preference_exchange'])
? $mysqli->real_escape_string($_POST['preference_exchange'])
: '';
$preference_news = isset($_POST['preference_news'])
? $mysqli->real_escape_string($_POST['preference_news'])
: '';
$stmt->execute();
$stmt->close();
}
echo "Thank you for signing up!";
?>
index.html
<form method="post" action="insert.php">
First name: <input type="text" name="first_name"><br>
Last name: <input type="text" name="last_name"><br>
E-mail: <input type="text" name="email"><br>
Please choose what kind of e-mails you would like to receive:<br>
News from my exchange: <input type="checkbox" name="preference_exchange" value="true"> <br>
Generel news: <input type="checkbox" name="preference_news" value="true"><br>
<input type="submit" value="Subscribe">
</form>
And here's my MySQL:
CREATE TABLE `mail_platform` (
`ID` int(20) unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(60) CHARACTER SET utf8 NOT NULL,
`last_name` varchar(60) CHARACTER SET utf8 NOT NULL,
`email` varchar(100) CHARACTER SET utf8 NOT NULL,
`registration_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`preference_exchange` tinyint(1) NOT NULL DEFAULT '0',
`preference_news` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`)
)
Thanks in advance!
First, break yourself of the habit of using mysqli_real_escape_string(). The best part of using query parameters is that it's not necessary to do escaping. In fact, you should not, because you'll end up with literal backslash characters in the strings stored in your database.
Second, you should always check the return status of prepare() and execute(). If any error occur in parsing or execution, these functions return false. Check for this and then if that has happened, you should look at the error returned.
The reason it's important to check for errors is that if the statement fails, you won't know it or the reason why unless you examine the error.
Also if you use PHP 5.3, you can use the ?: shortcut to make this code a little more brief.
$stmt = $mysqli->prepare("INSERT INTO mail_platform
(first_name, last_name, email, preference_exchange, preference_news)
VALUES (?, ?, ?, ?, ?)");
if ($stmt === false) {
trigger_error($mysqli->error, E_USER_ERROR);
}
$stmt->bind_param('sssii', $first_name, $last_name, $email,
$preference_exchange, $preference_news);
$first_name = $_POST['first_name'] ?: '';
$last_name = $_POST['last_name'] ?: '';
$email = $_POST['email'] ?: '';
$preference_exchange = $_POST['preference_exchange'] ?: '';
$preference_news = $_POST['preference_news'] ?: '';
if ($stmt->execute() === false) {
trigger_error($stmt->error, E_USER_ERROR);
}
Notice that an error on prepare() returns its message in $mysqli->error, but an error on execute() returns its message in $stmt->error;
Re your comment:
I just tested it myself with PHP 5.3.15 and MySQL 5.6.12. It worked perfectly. So I'm not sure what to suggest as a reason it fails in your case. Are you saying it doesn't return any error, but the row just never shows up in your table?
If you added another line for $stmt->execute() without adding error handling for that, you're back to the problem of not knowing whether it succeeded. In other words, it sounds like you did the following:
$stmt->execute(); // without checking if this had an error
if ($stmt->execute() === false) { // execute a second time
trigger_error($stmt->error, E_USER_ERROR);
}
You don't need to execute twice. I showed calling execute() as part of the if statement, but this is a pretty common style of coding when you want to check the return value without storing the return value in a variable. It still performs the execute.

can't update values in mysql using html and php

I am trying to make a form using html and php to update mysql database. the database updates (autoincrements) the keys, but it does not add any of the strings to the values. i have searched people with similar problems but because their codes are different than mine I cannot understand it (i am a noob with php and mysql) I think my problem is in the way that i use the html to get the values but I could be wrong
<form action=submitform.php method=GET>
Name:<input type="text" name="cuName" size=20 maxlength=20><br>
Password:<input type="password" name="password" size=20 maxlength=45><br>
Account:<input type="text" name="account" size=20 maxlength=45><br>
Phone:<input type="tel" name="phone" size=10 maxlength=10><br>
Email:<input type="text" name="email" size=20 maxlength=45><br>
<input type=submit>
</form>
and my php is
<?php
mysql_connect(localhost, myUsername, "myPassword");
mysql_select_db(myDatabaseName);
mysql_query("INSERT INTO Customer (cuName, password,
account, phone, email)
Values('$cuName', '$password', '$account',
'$phone', '$email')");
echo $cuName ." thank you for reserving!";
print ($cuName);
?>
thanks in advance for any help
Your code is relying on REGISTER_GLOBALS to be turned on; it is usually turned off for security reasons.
You should replace $cuName with $_GET['cuName'] to get the values that are sent from the form.
Additionally, you should escape any value that is going to the database otherwise you may be exposing yourself to an SQL injection vulnerability.
Cleaning up your code for both these scenarios, results in something like this:
<?php
if (!mysql_connect(localhost, myUsername, "myPassword")) {
print 'There was an error connecting to the database'.mysql_error();
exit();
}
if (!mysql_select_db(myDatabaseName)) {
print 'Could not select db. The error was: '.mysql_error();
exit();
}
$query = "INSERT INTO Customer (`cuName`, `password`, `account`,`phone`,`email`)";
$query .= "VALUES (";
$query .= "'".mysql_real_escape_string($_GET['cuName'])."','";
$query .= mysql_real_escape_string($_GET['password'])."','";
$query .= mysql_real_escape_string($_GET['phone'])."','";
$query .= mysql_real_escape_string($_GET['email'])."'";
if (!mysql_query($query)) {
print 'There was an error inserting '.$query.'. Error was '.mysql_error();
} else {
echo $_GET['cuName']." thank you for reserving!";
}
print $_GET['cuName'];
?>
I also added some error checking. You should always check results of functions that rely on external systems (such as databases) because you never know what is the status of the database (it could be down, not working, etc.) So you should always check and print any error messages.
You don't define any of your GET values anywhere. $cuName, etc are not defined.
Each value needs to be associated to the $_GET. IE,
$cuName = $_GET['cuName']
But you also need to make sure you don't insert data that hasn't been cleaned to prevent SQL injection. An example of this is:
$cuName = mysql_real_escape_string($_GET['cuName']);
So, try this:
<?php
mysql_connect(localhost, myUsername, "myPassword");
mysql_select_db(myDatabaseName);
//Define Variables
$cuName = mysql_real_escape_string($_GET['cuName']);
$password = mysql_real_escape_string($_GET['password']);
$account = mysql_real_escape_string($_GET['account']);
$phone = mysql_real_escape_string($_GET['phone']);
$email = mysql_real_escape_string($_GET['email']);
mysql_query("INSERT INTO Customer (cuName, password,
account, phone, email)
Values('$cuName', '$password', '$account',
'$phone', '$email')") or die (mysql_error());
echo $cuName ." thank you for reserving!";
print ($cuName);
?>
Better to use:
$cuname = $_GET['cuname'];
like this....
Because your form method is on "GET",and my advise is to POST data than GET.

Categories