This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 5 years ago.
During a test to see if my database would receive a username through a form field , the code would not work unless I echo'd out error messages. Why is this? My goal is to send the username through the form field , and retrieve the list of usernames on the same page below the form field.
My html for submitting usernames ,
<section id="banner">
<div class="content">
<header>
<h2>Add Usernames Here</h2>
<form method="post">
<br><input type="text" name="user_name"><br>
<input type="submit" value="Submit">
</form>
</header>
</div>
For displaying usernames:
<section id="five" class="wrapper style2 special fade">
<div class="container">
<header>
<h2>Added Usernames</h2>
<?php require 'post.php'; ?>
</header>
</div>
</section>
And my post.php code
<?php
//connection
$url = parse_url(getenv("CLEARDB_DATABASE_URL"));
$server = $url["host"];
$username = $url["user"];
$password = $url["pass"];
$db = substr($url["path"], 1);
$conn = new mysqli($server, $username, $password, $db);
//test connection
if(!$conn)
{
echo 'not connected';
}
if(!mysqli_select_db($conn,'heroku_cd6b3866e127c21'))
{
echo 'database not selected';
}
//insert username
$user_name = $_POST['user_name'];
$sql = "INSERT INTO store (user_name) VALUES ('$user_name')";
//test query
if(!mysqli_query($conn,$sql))
{
echo 'not inserted';
}
else {
echo 'inserted';
}
//echo all usernames
mysqli_select_db($db,$conn);
$sql2 = "SELECT * FROM store";
$mydata = mysqli_query('$sql2,$conn');
while($record = mysqli_fetch_array($mydata)){
echo "<br>";
echo $record['user_name'];
}
?>
This code works until I remove the if statements , checking for the connection.
This is simple example, only one page named index.php:
<form action="index.php" method="post">
<br><input type="text" name="user_name">
<br><input type="submit" value="Submit">
</form>
<?php
$username = $_POST["user_name"];
$link = mysqli_connect("127.0.0.1", "root", "", "db12");
mysqli_query($link, "INSERT INTO users (username) values ('$username')");
echo $username;
$query = "SELECT username FROM users";
$result = mysqli_query($link, $query);
/* fetch associative array */
while ($row = mysqli_fetch_array($result)) {
echo $row['username'] . "<br>";
}
/* close connection */
mysqli_close($link);
?>
In production app always write separate page for insert, and always use prepare http://php.net/manual/en/mysqli.prepare.php
You aren't running the query anywhere else except in those if statements.
Try adding $mysqli->query($sql) underneath your declaration of $sql
You still need to call these functions:
mysqli_select_db($conn,'heroku_cd6b3866e127c21')
and
mysqli_query($conn,$sql)
Even if they are wrapped in an if statement or not you still need to select the db and send it a query. But I wouldn't want to do it like this, I would look into PDO.
http://php.net/manual/en/book.pdo.php
These methods are known for having SQLi vulnerabilities.
Edit
Also this line has an error:
$mydata = mysqli_query('$sql2,$conn');
I assume it should be:
$mydata = mysqli_query($conn,$sql2);
Related
i am a newbie in php programming and i cant figure out where i have gone wrong as my php code wont execute.
As the title says i am trying to create check boxes in my site however the values will come from the mysql database.
I have a table named “campus” in MySQL database and it has 2 coloumns called id and room.
database
[![Database][1]][1]
http://i.imgur.com/uLP6niJ.png
current output
[![Current Output][2]][2]
http://i.imgur.com/cSOYPme.png
below is my code:
<?PHP
$hostname = "localhost";
$username = "root";
$password = "root";
$databaseName = "my computer";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$s = '';
$j = 0;
if ($q = $connect->query("SELECT * FROM `campus`")) {
while ($line = $q->fetch_assoc()) {
$s.= '<input type="checkbox" name="car'.$j.'" value="'.$line['room'].'">';
}
}
echo $s;
?>
</form>
</body>
</html>
You're not closing the while loop properly. Close the while loop as follow.
<?php
$sql = "SELECT room FROM campus";
$result = mysqli_query($sql);
while ($line = mysqli_fetch_array($result, MYSQL_ASSOC)) {
?>
<input type="checkbox" name="car" value="<?php echo $line['room']?>" />
<?php
}
?>
Welcome to PHP!
An error is that you're missing the semicolon that's needed after any php function (such as echo)
<?php echo $line['room']; ?>
And there's the missing PHP tags around the closing }
A third error is that you're not telling mysqli which connection to run the query on it should have:
mysqli_query($dbCon, $sql);
Apart from that it looks good, personally I prefer to use a PDO connection but mysqli is still good, but there are a few formatting tricks that can help prevent problems.
For example it's always a good idea to use back-ticks (`)
So:
$sql = "SELECT `room` FROM `campus`";
However, for this it might be best to use the * query. Which selects everything from the column so:
$sql = "SELECT * FROM `campus`";
The reason is how you're getting the data, you're telling PHP to create an array using the results.. but you've only given it one piece of data for each row. So if you give it all of the data it just makes it a little easier to use.
Here's the full code:
<?php $dbCon = mysqli_connect("localhost", "root", "root", "my computer");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$sql = "SELECT * FROM `campus`";
$result = mysqli_query($dbCon, $sql);
while ($line = mysqli_fetch_array($result, MYSQL_ASSOC)) { ?>
<input type="checkbox" name="car" value="<?php echo $line['room']; ?>"
<?php } ?>
</form>
</body>
</html>
Also, if you're interested, here's how it'd be done in PDO:
<?php
try{
$con = new \PDO("mysql:host=" . 'localhost' . ";dbname=" . 'My Computer', 'root', 'root');
}catch(PDOException $e){
echo "Connection Failed";
die();
} ?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$result = $con->prepare("SELECT * FROM `campus`")
$result->execute();
while ($row = $result->fetch()) { ?>
<input type="checkbox" name="car" value="<?php echo $row['room']; ?>"
<?php } ?>
</form>
</body>
</html>
Still not working? Feel free to comment and I'll see what's up :)
Thanks,
P110
Try with this
<?php
$sql = "SELECT room FROM campus";
$result = mysqli_query($sql);
$campusArray = mysqli_fetch_array($result, MYSQLI_ASSOC);
foreach ($campusArray as $campus): ?>
<input type="checkbox" name="car" value="<?php echo $campus['room'];?>" />
<?php endforeach; ?>
I hope with this you can solve your problem.
alternative syntax is excellent for improving legibility (for both PHP
and HTML!) in situations where you have a mix of them.
http://ca3.php.net/manual/en/control-structures.alternative-syntax.php
This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 7 years ago.
Hello I have while adding a login user I want to check if this user is already in DB, it will display a message if not it will be added to DB:
This is the form in html:
<form name="inscription" method="post" action="03insert.php">
login: <input type="text" name="login" value=""/>
<input type="submit" name="submit" value="Inscription"/>
</form>
And this the code in PHP:
<?php
$connection = ConnectionBD();
if( isset($_POST['submit']) ){
$login = $_POST['login'];
$sql_1 = "SELECT * FROM users WHERE user_login = :login";
$query = $connection->prepare($sql_1);
$query->bindParam(':login', $login, PDO::PARAM_STR);
$query->execute();
$count = $query->rowCount();
if ($count > 0){
echo 'This login already exist';
}
else
{
$sql_2 = 'INSERT INTO users VALUES(null,"'.$login.'")';
$result = $connection->exec( $sql_2 );
if( $result > 0 ){
echo 'Registered successfully';
}else{ echo 'ERROR !<br><br>'; }
}
}
unset( $connection );
?>
I don't have error but It add the user even its exist ..Please help!!
Your first line of code, you use this:
$connection = ConnectionBD();
Why is there no new keyword or is it a standard function? If it's a class you need to instantiate it, i.e.:
$connection = new ConnectionBD();
// OR
$connection = ConnectionBD()::initFunction(); // If it's static
You won't get a thang from it as the object is not instantiated properly
Try to change your query to this:
$sql_1 = "SELECT * FROM users WHERE user_login = :login";
//just removed the single quotes '
I am working on a test login-check with PHP/HTML and MySQL. I got it working great; it successfully connects to the database, it can grab my database values and save them in a variable, etc., but I ran into one slight problem.
I'm using two PHP pages to do the check. The login.php page, which only contains the forum, and the welcome.php page, which does the database connecting. When I ran a test page to just have it echo the database info, it printed out right (testUser, testEmail#email.com, testPassword, 1/1/1900). So when I tried to run my login-authentication check, it just says 'Unknown user!' twice, even when I try the usernames 'usr', 'testUser', and 'testUser2' (I made two tables, and the second one is the same with 2 added to the end). Here's my code.
<html>
<head>
<?php
$title = ucfirst(basename($_SERVER['PHP_SELF'], ".php"));
echo "<title>$title</title>";
?>
</head>
<body>
<form name="form" accept-charset="utf-8" action="welcome.php" method="post">
<span class="header">Username</span><input type="text" name="usr" value="usr"></input><br>
<span class="header">Password</span><input type="text" name="pass" value="pass"></input>
<input type="submit">
</form>
</body>
</html>
<?php
$servername = removed;
$username = removed;
$password = removed;
$dbname = removed;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, USER, PASSWORD FROM usrdatabase";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// the given info from the form
$usrUser = $_POST["usr"];
$usrPass = $_POST["pass"];
// convert the findings to uppercase to get rid of sensitivity
if (strtoupper($usrUsr) == strtoupper($row["USER"]) && strtoupper($usrPass) == strtoupper($row["PASSWORD"])) {
echo "Welcome $usrUser!<br>Your login was successful! ?>";
}
elseif (strtoupper($usrUsr) == strtoupper($row["USER"]) && strtoupper($usrPass) != strtoupper($row["PASSWORD"])) {
echo "Login failed as $usrUser!";
}
else {
echo "Unknown user!";
}
}
} else {
echo "0 results";
}
$conn->close();
?>
This always produces a 'Unknown user!' Is there something wrong with my check? I want it to go through each user in the database to check the info with each existing user.
Change
strtoupper($usrUsr) == strtoupper($row["USER"])
To
strtoupper($usrUser) == strtoupper($row["USER"])
Fetch single user from the database by using the username since they are unique for each user.
$sql = "SELECT ID, USER, PASSWORD FROM usrdatabase WHERE USER = '" . mysqli_real_escape_string($_POST['usr']) . "' AND PASSWORD = '" . mysqli_real_escape_string($_POST['pass']) . "'";
hey i see your if else contains $usrUsr shoudn't it be $usrUser ? (forgot the e)
So as the title suggests, I am having trouble executing a MySQL query. The query works almost successfully, as all data fields are stored into my database except for one. The query itself is a commenting system for signed in users to comment on any given blog post. The issue I am having is that the variable '$post_id' is not recognized, and therefore '$comment_post_ID' is not stored in my database.
'$post_id' is defined in blogs.php, and after echoing this variable it does exist and is successfully defined. However, this variable is not passed onto commentsubmit.php, which is included in the same file where the variable is defined. Why is this happening?
Here are all the pieces of my code:
blogs.php (shows all posts from all users, or just one post if ?id is set in the url. If ?id is set, users can comment on the single post they are viewing.)
<?php
if (isset($_GET['id'])) {
$conn = mysqli_connect("localhost", "root", "mypassword", "mydbname");
if (mysqli_connect_errno($conn)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
$post_id = mysqli_real_escape_string($conn, $_GET['id']);
$blog_post = "SELECT * FROM blogs WHERE id = '$post_id'";
$blog_query = mysqli_query($conn, $blog_post);
while ($row = mysqli_fetch_array($blog_query)) {
$title = $row['title'];
$body = $row['body'];
$author = $row['author'];
$author_username = $row['author_username'];
$datetime = time_ago($row['datetime'], $granularity=2);
}
include ("./fullpageblog.php");
if (isset($_SESSION['id'])) {
include ("./blogcomment.php");
include ("./commentsubmit.php");
}
echo "$post_id";
mysqli_close($conn);
}
?>
blogcomment.php (form for users to make a comment)
<div class="row col-sm-12">
<div id="fullPageBlog">
<div id="center-border"></div>
<form action="commentsubmit.php" method="post">
<textarea maxlength="1000" id="blogComment" name="content" placeholder="Write your response..."></textarea>
<input type="submit" name="comment" value="Publish" />
</form>
<script type="text/javascript">$('#blogPost').elastic();</script>
</div>
</div>
commentsubmit.php (comment query itself)
<?php
session_start();
if (isset($_POST['comment'])) {
$conn = mysqli_connect("localhost", "root", "mypassword", "mydbname");
if (mysqli_connect_errno($conn)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
$comment_post_ID = $post_id;
$comment_author = $_SESSION['full_name'];
$comment_author_email = $_SESSION['email'];
$comment_author_username = $_SESSION['username'];
$comment_date = date("Y-m-d H:i:s");
$comment_content = mysqli_real_escape_string($conn, $_POST['content']);
$user_ID = $_SESSION['id'];
$comment_submit = "INSERT INTO comments (comment_ID, comment_post_ID, comment_author, comment_author_email, comment_author_username, comment_date, comment_content, user_ID) VALUES ('', '$comment_post_ID', '$comment_author', '$comment_author_email', '$comment_author_username', '$comment_date', '$comment_content', '$user_ID') ";
$comment_query = mysqli_query($conn, $comment_submit);
mysqli_close($conn);
header("Location: blogs.php");
die();
}
?>
You don't include/require the blogs.php script from the commentsubmit.php script, so the code in blogs.php would never be run after a POST that is made directly to commentsubmit.php unless you have some other request processing (i.e. a server-side rewrite or similar) that happens automatically on the server before the request ultimately reaches the portion of code shown in commentsubmit.php above.
<?php
$con = mysql_connect("localhost","root","password");
$con=mysql_select_db("database_name");
error_reporting(0);
session_start();
if(isset($_POST["submit"])){
$comment_author = $_POST['full_name'];
$comment_author_email = $_POST['email'];
$comment_author_username = $_POST['username'];
$sql="select * from table_name where `full_name`='"$comment_author "',`email`='"$comment_author_email "',`username`='"$comment_author_username "'";
$qur=mysql_query($sql);
$row= mysql_fetch_array($qur);
$num= mysql_num_rows($qur);
}
if($num>0){
$_SESSION["full_name"]=$full_name;
$_SESSION["email"]=$comment_author_email;
$_SESSION["username"]=$comment_author_username;
}
else{
echo"Username and Password are wrong";
}
?>
I have a table displaying the content of a MySQL table. For every row I added an 'edit button' so our users can update the content.
The 'edit button' goes to a link ?edit_entry.php?sid=4 with 4 the sid of the entry.
This works but I get a blank form.
Question 1: Is there any way to already display the content of the specific MySQL row in the text fields of the form?
Here is the edit_entry.php code:
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
// Create connection
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sid = $_GET['sid'];
$sql = "SELECT * FROM orders WHERE sid = '$sid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($sql)) {
$sid = $row['sid'];
$q1_requested_by = $row['q1_requested_by'];
$q2_productname = $row['q2_productname'];
$q3_supplier = $row['q3_supplier'];
$q4_productnumber = $row['q4_productnumber'];
$q5_quantity = $row['q5_quantity'];
$q6_price = $row['q6_price'];
$q7_budget = $row['q7_budget'];
$q8_link = $row['q8_link'];
}
?>
<form action="update_script.php" method="post">
<input type="hidden" name="sid" value="<?=$sid;?>">
Requested by: <input id="q1" type="text" style="width:400px" name="ud_q1_requested_by" value="<?=$q1_requested_by?>" required="true" tabindex="1"><br>
Product name: <input id="q2" type="text" style="width:400px" name="ud_q2_productname" value="<?=$q2_productname?>" required="true" tabindex="2"><br>
Supplier: <input id="q3" type="text" style="width:400px" name="ud_q3_supplier" value="<?=$q3_supplier?>" required="true" tabindex="3"><br>
Product number: <input id="q4" type="text" style="width:400px" name="ud_q4_productnumber" value="<?=$q4_productnumber?>" required="true" tabindex="4"><br>
Quantity: <input id="q5" type="text" style="width:400px" name="ud_q5_quantity" value="<?=$q5_quantity?>" required="true" tabindex="5"><br>
Price: <input id="q6" type="text" style="width:400px" name="ud_q6_price" value="<?=$q6_price?>" tabindex="6"><br>
Budget: <input id="q7" type="text" style="width:400px" name="ud_q7_budget" value="<?=$q7_budget?>" tabindex="7"><br>
Link: <input id="q8" type="text" style="width:400px" name="ud_q8_link" value="<?=$q8_link?>" tabindex="8"><br>
<input type="submit" name="submit" id="submit" value="Update your input!" tabindex="9" />
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
And here is update_script.php:
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
// Create connection
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sid = $_POST["sid"];
$ud_q1_requested_by = mysqli_real_escape_string($_POST["ud_q1_requested_by"]);
$ud_q2_productname = mysqli_real_escape_string($_POST["ud_q2_productname"]);
$ud_q3_supplier = mysqli_real_escape_string($_POST["ud_q3_supplier"]);
$ud_q4_productnumber = mysqli_real_escape_string($_POST["ud_q4_productnumber"]);
$ud_q5_quantity = mysqli_real_escape_string($_POST["ud_q5_quantity"]);
$ud_q6_price = mysqli_real_escape_string($_POST["ud_q6_price"]);
$ud_q7_budget = mysqli_real_escape_string($_POST["ud_q7_budget"]);
$ud_q8_link = mysqli_real_escape_string($_POST["ud_q8_link"]);
$sql= "UPDATE orders
SET q1_requested_by = '$ud_q1_requested_by', q2_productname = '$ud_q2_productname', ud_q3_supplier = '$ud_q3_supplier', ud_q4_productnumber = '$ud_q4_productnumber', ud_q5_quantity = '$ud_q5_quantity', ud_q6_price = '$ud_q6_price', ud_q7_budget = '$ud_q7_budget', ud_q8_link = '$ud_q8_link'
WHERE sid='$sid'";
$result = $conn->query($sql);
if(mysqli_affected_rows()>=1){
echo "<p>($sid) Record Updated<p>";
}else{
echo "<p>($sid) Not Updated<p>";
}
?>
There must be a problem in this last part because I get the (4) Not updated message.
Question 2: Does anyone see the problem here?
I've been trying a few things to tackle the problem but neither are working.
Thank you
mysqli_real_escape method requires the connection to be provided; this was not the case in deprecated mysqli_* methods..
see documentation at http://php.net/manual/en/mysqli.real-escape-string.php
In your case, since you are using object of mysqli:
$conn->real_escape_string($string)
Also for the record, you have a possible inject despite your attempts not to.
You should update $sid = $_POST["sid"]; to $sid = (int) $_POST["sid"]; if it is supposed to be an integer or escape it as well.
With this many variables needing to be escaped though, you should probably look at how to conduct a prepared statement. http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
You use mysqli, not mysql that is good news.
But you continue to use old techniques to pass parameter to query.
So let just try to bind parameters as it should be done with mysqli:
$sql= "UPDATE orders
SET
q1_requested_by = ? ,
q2_productname = ?,
ud_q3_supplier = ?,
ud_q4_productnumber = ?,
ud_q5_quantity = ?,
ud_q6_price = ?,
ud_q7_budget = ?,
ud_q8_link = ?
WHERE sid=? ";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ssssiddsi', $ud_q1_requested_by, $ud_q2_productname, $ud_q3_supplier, $ud_q4_productnumber, $ud_q5_quantity, $ud_q6_price, $ud_q7_budget, $ud_q8_link, $sid);
$result = $stmt->execute();
if($result && $stmt->affected_rows>0){
echo "<p>($sid) Record Updated<p>";
}else{
echo "Error:\n";
print_r($stmt->error_list);
echo "<p>($sid) Not Updated<p>";
}
I got it to work using the following code:
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sid = (int)$_POST["sid"];
$ud_q1_requested_by = $conn->real_escape_string($_POST["ud_q1_requested_by"]);
$ud_q2_productname = $conn->real_escape_string($_POST["ud_q2_productname"]);
$ud_q3_supplier = $conn->real_escape_string($_POST["ud_q3_supplier"]);
$ud_q4_productnumber = $conn->real_escape_string($_POST["ud_q4_productnumber"]);
$ud_q5_quantity = $conn->real_escape_string($_POST["ud_q5_quantity"]);
$ud_q6_price = $conn->real_escape_string($_POST["ud_q6_price"]);
$ud_q7_budget = $conn->real_escape_string($_POST["ud_q7_budget"]);
$ud_q8_link = $conn->real_escape_string($_POST["ud_q8_link"]);
$sql= "UPDATE orders
SET
q1_requested_by = '$ud_q1_requested_by',
q2_productname = '$ud_q2_productname',
q3_supplier = '$ud_q3_supplier',
q4_productnumber = '$ud_q4_productnumber',
q5_quantity = '$ud_q5_quantity',
q6_price = '$ud_q6_price',
q7_budget = '$ud_q7_budget',
q8_link = '$ud_q8_link'
WHERE sid='$sid'";
$result = $conn->query($sql);
header("Location: edit_orders.php");
?>
which is just simple query, as the original form to enter a new row of data also does. I also decided to remove the error handling at the end since it didn't seem to work with mysqli_affected_rows()>0...
It's probably not a very elegant solution, but it works. Still I'd like to learn more so if anybody would have a useful link explaining php+mysqli basics that would help me much. The links to php.net or mysql.com are for me too brief at this moment though, for me they don't explain what is going on. I'm a total novice to php and mysql and could use some more explanatory/introductary text, maybe with examples, but mostly providing me with an overview of what is going on... Thanks anyway for all the help!