Using PHP to insert data into a MySQL Database [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to create a self-submitting page that will create a form for a user to fill out. The information will be stored in a MySQL database. The form seems to be working, but I can't insert the information from the form into a database for some reason. Here's what I have:
<!DOCTYPE html>
<html>
<head>
<title>MySQL Test</title>
</head>
<body>
<h1>MySQL Test</h1>
<?php
if($_SERVER["REQUEST_METHOD"] == "GET") {
?>
<form action="" method="post">
<input type="text" name="name" placeholder="Name" /><br />
<input type="submit" value="Send" />
</form>
<?php
} else if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$server = new PDO("mysql:dbname=test;host=localhost", "root", "root");
$server->execute("INSERT INTO test ('name') VALUES $name;");
}
?>
</body>
</html>
What should I change?

your insert should look as follows:
$name = $_POST["name"];
$server = new PDO("mysql:dbname=test;host=localhost", "root", "root");
$stmt = $server->prepare("INSERT INTO test (name) VALUES (:name)");
$stmt->bindParam(':name', $name);
$stmt->execute();

Please do your insert like this:
$name = "john";
$query = "INSERT INTO test(col) VALUES(:name);";
$statement = $server->prepare($query);
$statement->execute(array(":name" => $name));
This is called using prepared statements, it's very easy and will avoid sql-injection. You can execute multiple variables on multiple cols on your query by separating with commas after each ":col" => $colVal, but that's not needed here, just a tip.
You can do it for updates aswell.
Remember to check if your being-inserted value is empty or not.

Related

mysqli_query SELECT LIKE function not working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Im getting query error, im using the like LIKE sql function to search for the name submitted by the user.
But msqli_query is giving an error if i remove the LIKE function it works but doesn't works with the LIKE function
<!DOCTYPE html>
<html>
<head>
<title>Search Users</title>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"method="GET">
Name: <input type="text" name="name"></input>
<input type="submit" name="searchusers" value="Submit"></input> </br>
</body>
</html>
<?php require('connect.php');
$name = #$_GET['name'];
if ($_SERVER["REQUEST_METHOD"] == "GET")
{
$select123 ="SELECT username FROM users WHERE username LIKE ='%".$name."%'";
$check = mysqli_query($conn, $select123) or die("query error");
mysqli_num_rows($check) or die("Couldnt not find the Specified username");
}
?>
Please help
Remove = near keyword like :
$select123 ="SELECT username FROM users WHERE username LIKE '%".$name."%'";

Database connection successful but not able to insert data into database using php [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have been struggling for about a week now and still have not got any results. I have read the following questions:
Unable to insert form data in MySQL database
Connection to database seems successful but INSERT INTO sends no data
PHP MySQL not inserting into database
https://askubuntu.com/questions/435746/unable-to-send-data-to-mysql-database-it-is-not-taking-by-my-php-code
I tried everything suggested in the above questions' answers. After reviewing my code, if you still think that the above questions' solution relates then please do tell.
My code -
connect.php -
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice_user";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
echo "Connection failed: " . $con->connect_error;
}
else {
echo "Success";
}
//Insert data into database
$sql = "INSERT INTO simple_login (name,email) VALUES('{$mysqli->real_escape_string($_POST['name'])}','{$mysqli->real_escape_string($_POST['email'])}')";
$insert = $mysqli->query($sql);
if(!$insert)
{
echo $mysqli->error;
}
$mysqli->close();
register.html -
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="connect.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
As usual I am getting a "Successful" message for connection. Also it is not outputting any error message(if I have not appropriately tried to output insertion error in the given code, please do tell in the comments).
Thank you in anticipation.
I'll post this here, we all make mistakes so don't worry! As suggested your $mysqli function is undefined, you've stored your mysqli instance as the $con variable, so you should refer any mysqli functions on that.
Examine http://php.net/manual/en/mysqli.query.php for more information!

I have tried EVERYTHING.. My form wont post to database.. [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have tried rewrite the code, i have looked on previously succesful codings i have made and i really cant find the problem.. i am going crazy.
I am trying to post some data from a form to a database.
The database i setup correctly as far as i can tell, but something is making the script fail every time.
IMAGE OF DATABASE: http://imgur.com/F93A9ot
(sry for the language being in danish.)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php
// defining database information
define("HOSTNAME", "localhost");
define("MYSQLUSER", "admin");
define("MYSQLPASS", "admin");
define("MYSQLDB", "lynx");
// establishing database connection
if(isset($_POST['submit'])){
$connection = new mysqli(HOSTNAME, MYSQLUSER, MYSQLPASS, MYSQLDB);
$name = mysqli_real_escape_string($connection, $_POST['name']);
$price = mysqli_real_escape_string($connection, $_POST['price']);
$desc = mysqli_real_escape_string($connection, $_POST['desc']);
$insert = "INSERT into products (id, name, price, desc) VALUES (NULL, '$name', '$price', '$desc')";
if($connection->query($insert)) {
echo "Succes";
} else {
echo "Something went wrong";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="name">
<input type="text" name="price">
<input type="text" name="desc">
<input type="submit" name="submit">
</form>
</body>
</html>
Can you see what i am doing wrong?
products (id, name, price, desc)
Tried reading the manual as well? desc is a reserved word.
If you didnt have this useless piece of code
else {
echo "Something went wrong";
}
and had
else {
echo $connection-error;
}
You would find that out yourself
desc is reverse keyword of mysql you can use it using backtick
$insert = "INSERT into products (`id`, `name`, `price`, `desc`) VALUES (NULL, '$name', '$price', '$desc')";
This is with your field 'desc' . this is not allowed by MYSQL because it is reserved. So please rename it. It will solve your issue.

Data Not getting saved in Mysql database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying this code but data is not getting saved and it is throwing an error
<?php
include 'core/int.php';
include 'includes/overall/header.php';
if(!empty($_POST)){
$add_status = $insert->add_status($user_data['user_id']);
}
?>
<form action = "" method = "POST">
<ul>
<li>
<input name = "question_time" type = "hidden" value = "<?php echo time()?>" />
</li>
<li>
<h2>Post your Question <?php echo $user_data['username'];?></h2>
<textarea name = "question"></textarea>
</li>
<li>
<p><input type = "submit" value = "submit"></p>
</li>
</ul>
</form>
and the function is defined like this :
function add_status($user_id){
mysql_query("INSERT into `post` (user_id, status_time, status_content) VALUES($user_id, '$_POST[question_time]', '$_POST[question]')");
}
It is throwing and error that
Undefined variable: insert in C:\wamp\www\zr\sheet.php on line 7
Call to a member function add_status() on a non-object in C:\wamp\www\zr\sheet.php on line 7
Line 7 is "$add_status = $insert->add_status($user_data['user_id']);"
I am a new learner in PHP and MYSQL
Thanks in advance..
I would do it like this:
function add_status($id, $status_time, $status_content)
{
$db = //your db connection
$query = $mysqli_query('INSERT into table WHERE user_id, status_time, status_content VALUES (?, ?, ?)');
$db->bind_param('i,i,s' $id, $status_time, $status_content);
$db->execute();
}
and then call it as
if(isset($_POST['submit']))
{
$questionTime = $_POST['question_time'];
$question = $_POST['question'];
$allFields = $questionTime . $question;
if (!empty($allFields)) {
$insert->add_status($user_data['user_id'], $questionTime, $question);
}
}
Remember, always use prepared statements and NEVER use mysql_ functions.
first of all, you should extract using POST. This is the ideal way..

PHP/MySQL to PDO? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm very new to PHP/Mysql and I naturally have a few questions. I was following a youtube tutorial on creating a simple dynamic website that pulls data content from a MySQL database then displays the content on a single PHP index page. I followed this tutorial to the point where I was using PHP/MySQL to connect to the DB, run a query, fetch the query using a fetch_assoc array. but nothing would display in the body of the page. During the trouble shooting process I was advised that I should be using PDO instead of the older MySQL methods. Can someone decipher my current "older" MySQL code and translate it into the proper PDO coding approach so that I can learn to grasp PDO, since it is the future I should start to understand it now :)
index.php:
<?php
// Setup document:
include('config/setup.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title><?php echo $page_title; ?> - test site</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div class="wrap_overall">
<div class="header">
<?php include('template/header.php'); ?>
</div>
<div class="nav_main">
<?php include('template/nav_main.php'); ?>
</div>
<div class="content">
<?php //include('content/'.$pg.'.php');
// the database connection, our query
$q = "SELECT * FROM pages WHERE page = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
if (!$r) {
die('Invalid query: ' . mysql_error());
}
$page = mysqli_fetch_assoc($r);
echo '<h1>'.$page['title'].'</h1>';
echo '<div class="content_body">'.$page['body'].'</div>';
?>
</div>
<div class="footer">
<?php include('template/footer.php'); ?>
</div>
</div>
</body>
</html>
setup.php:
<?php ## Setup Document
// host(or location of the database), username, password, database name
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "localhost";
$username = "atomcmsadmin";
$password = "uniCi2i";
$dbname = "Atom_CMS";
//Connecting to your database
$dbc = mysqli_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysqli_select_db($dbname);
//include('functions/sandbox.php');
if ($_GET ['page'] == '') {
$pg = 'home';}
else {
$pg = $_GET ['page']; }
$page_title = get_page_title($dbc, $pg);
?>
sandbox.php
<?php
// Sandbox Functions
function get_page ($dbc, $pg) {
// the database connection, our query
$q = "SELECT title FROM pages WHERE type = 1, page = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
$page = mysqli_fetch_assoc($r);
echo '<h1>'.$page['title'].'</h1>';
echo '<div class="content">'.$page['body'].'</div>';
}
function get_page_title ($dbc, $pg) {
$q = "SELECT title FROM pages WHERE type = 1, page = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
$page = mysqli_fetch_assoc($r);
return $page['title'];
}
?>
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
all you need to change is setting up the connection, check out the tutorial for the syntax
interacting with the database is still mostly the same
I think no one will do the job for you. But I can help you help yourself:
From your code, you'll need to learn these PDO methods:
PDO::__construct()
You'll replace mysqli_connect() and mysqli_select_db() with that.
PDO::prepare(), PDOStatement::bindValue() and PDOStatement::execute()
You'll replace mysqli_query() with them.
PDOStatement::fetch()
You'll replace mysqli_fetch_assoc() with that.
PDO::errorCode() and PDO::errorInfo()
You might want to use one of them or both to cover errors.
Also take a look at PDO book on the PHP manual. You'll learn all the stuff more easier than you think! Good luck!

Categories