Blank Page on mysqli_query();? [duplicate] - php

This question already has answers here:
Parse errors are not displayed
(8 answers)
Closed 8 years ago.
I am making a basic song recommendation site, and I have a form set up that leads to a page with this exact code on it:
<?php
ini_set('display_errors',1);
ob_start();
session_start();
$host = "localhost";
$user = "root";
$pass = "MYPASS";
$db = "tts";
$conn = mysqli_connect($host, $user, $pass, $db);
$song = $_POST['song'];
$artist = $_POST['artist'];
$album = $_POST['album'];
$linkitunes = $_POST['linkitunes'];
$artwork = $_POST['artwork'];
$song = stripslashes($song);
$artist = stripslashes($artist);
$album = stripslashes($album);
$linkitunes = stripslashes($linkitunes);
$artwork = stripslashes($artwork);
$sql = "INSERT INTO recommendation (user_id, song, artist, album, linkitunes, artwork, rating)";
$sql = $sql . "VALUES ($_SESSION['id'], '$song', '$artist', '$album', '$linkitunes', '$artwork', '$rating');";
print "Hello.";
$result = mysqli_query($sql) or die("Fail");
ob_flush();
?>
It always shows the "Hello." string until I add in the $sql value. I am thinking there is something wrong with the code syntax, but not sure. Have tried very many variations. Just in case, I have added the form code as well:
<form action="recommend-action.php" method="POST">
<div id="noP" align="center">
<h2>Make a new Recommendation</h2>
<p>Please search for your song before you recommend it.</p>
</div>
<div align="center">
<input required name="song" type="text" placeholder="Song" maxlength="50"></input>
<input required name="artist" type="text" placeholder="Artist" maxlength="50"></input>
<input name="album" type="text" placeholder="Album" maxlength="50"></input>
<input name="artwork" type="url" placeholder="Artwork" maxlength="500"></input>
<input name="linkitunes" type="url" placeholder="Link in iTunes" maxlength="500"></input>
<input id="submit" type="submit" value="Recommend"></input>
</div>

you should execute this...
$result = mysqli_query($con,$sql); or die("Fail");

You DO NOT have any line in PHP that gets converted to HTML... How will it display anything on screen. Write this at the end of your code.
echo "<br> Inserted Successfully";
The syntax of mysqli_query is wrong.
Use the following one.
$result=mysqli_query($conn,$sql) or die ("Fail");
Other possible Checks:
First Check your username and password and check if the connection to the database is successful by using this piece of code.
if (!$conn) {
die('Could not connect to MySQL: ' . mysql_error());
}
Use session_start() as the first line of your code or else your sessions will not work. This is not needed but may cause you a problem in future.

I did some modifications to your code, try this:
<?php
ini_set('display_errors',1);
ob_start();
session_start();
$host = "localhost";
$user = "root";
$pass = "MYPASS";
$db = "tts";
$conn = mysqli_connect($host, $user, $pass, $db);
$song = $_POST['song'];
$artist = $_POST['artist'];
$album = $_POST['album'];
$linkitunes = $_POST['linkitunes'];
$artwork = $_POST['artwork'];
$song = stripslashes($song);
$artist = stripslashes($artist);
$album = stripslashes($album);
$linkitunes = stripslashes($linkitunes);
$artwork = stripslashes($artwork);
$sql = "INSERT INTO recommendation (user_id, song, artist, album, linkitunes, artwork, rating)";
$sql = $sql . "VALUES (".$_SESSION['id'].", '$song', '$artist', '$album', '$linkitunes', '$artwork', '$rating');";
print "Hello.";
$result = mysqli_query($conn,$sql) or die("Fail");
ob_flush();
?>

Related

How to let the user delete a profile using php?

I currently have a website where the user can add profiles of people they know on a contacts page. I'm now trying to also let them delete specific profiles but I can't get it to work. Here's what I have so far.
Version 2.0 after feedback (now working):
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">
profile = <input type = "text" name = "profile" required />
<input type = "submit" />
</form>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "registration";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$prepped = $conn->prepare ('DELETE FROM users WHERE id = ?');
$prepped->bind_param ('i', $_POST["profile"]);
if ($prepped->execute()) {
// success
} else {
// failure
}
var_dump($_POST);
?>
The query you're executing is literally looking for an id "profile" in the database. Presumably the ID column is numeric so it can't possibly contain any rows with an id of "profile".
You need to pass the ID you want to delete in as a parameter to your query
$prepped = $conn->prepare ('DELETE FROM uses WHERE id = ?'); // The "?" is a placeholder that MySQL will replace with the specified parameter
$prepped->bind_param ('i', $_POST["profile"]); // 'i' indicates we're expecting an integer. See PHP docs for other options
if ($prepped->execute()) {
// The query executed without any errors (though you should also check how many rows were affected at this point to determine if anything was actually deleted)
} else {
// Failure
}
Additionally your form markup is incorrect and therefore probably not posting to the correct location.
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">
Profile = <input type = "text" name = "profile" required />
<input type = "submit" />
</form>
Your query should look more like:
$query = sprintf("DELETE FROM uses WHERE id = '%s'", $profile);
or without sprintf():
$query = "DELETE FROM uses WHERE id = '" . $profile . "'";
EDIT after comments
$profile is a variable holding the string with the name / id / whatever you use to profile the user. From your form, you should define it in this way:
$profile = $conn->real_escape_string($_POST["profile"]);
of course before the query.
form action should be <?php echo $_SERVER['PHP_SELF']; ?>
see your code also.. what you are doing is passing the unknown $sql variable in if statement if ($conn->query($sql) === TRUE)
you have to pass $query variable defined above in this statement
Kindly replace your code with this code.. hope it will work for you :) goodluck
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">
Profile = <input type = "text" name = "profile" required />
<input type = "submit" />
</form>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "registration";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
///////////NEW CODE///////////
$profile_id = mysql_real_escape_string($_POST['profile']);
$query = "DELETE FROM users WHERE id= '".$profile_id."'";
if ($conn->query($query) === TRUE) {
echo "Profile deleted successfully";
} else {
echo "Error deleting profile: " . $conn->error;
}
//////////////////////////////
?>

Program is not inserting into the database

My program doesn't insert into the database, tried various means, I'm new to php and tried to test myself with this but I'm finding it difficult to get. i think the problem is at the connection to the database but I'm not getting it
<!DOCTYPE html>
<html>
<head>
<title>LIST</title>
</head>
<body>
<h1> TODO LIST </h1>
<?php
if(isset($_POST["submit"])){
$servername = "localhost";
$username = "root";
$password = "";
try {
//create a database conneection
$conn = mysqli_connect("localhost", "root", "");
if(!$conn){
die("Database connection failed: ". mysql_error());
}
$sql = "INSERT INTO tasks (task, date, time) VALUES (:task, :date, :time)";
$query = $conn->prepare($sql);
$query->execute(array(':task'=>$task,
':date'=>$date,':time'=>$time));
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
?>
<form action = "todolist.php" method = "post">
Task: <input type="text" name="task" id="task"><br/>
Date: <input type="date" name="date" id="date"><br/>
Time: <input type="time" name="time" id="time"><br/>
<input type = "submit" value = "submit" name="submit">
</form>
</body>
</html>
You are not select any database.
Try something like this.
$conn = mysqli_connect("localhost", "root", "", "Yourdatabasename");
Are you connected to your database? You do not select any bdd and the logs are the right ones?
Maybe try:
$conn = mysqli_connect("localhost", "root", "", "databasename");
At first, see if you are connected to your database
I am using this way in one of my project. Create a connect.php file and create connection like this:
<?php
$conn = mysqli_connect("localhost", "root", "", "Yourdatabasename");
?>
Now in index.php file check if the submit button is pressed:
<?php
if(isset($_POST["submit"]))
{
// include connection file
include("connect.php");
// get values
$subject = mysqli_real_escape_string($con, $_POST["subject"]);
$comment = mysqli_real_escape_string($con, $_POST["comment"]);
// Insert in database
$query = "INSERT INTO comments(comment_subject, comment_text)VALUES ('$subject', '$comment')";
mysqli_query($con, $query);
}
?>

php search works as seperate page, but not on same page

I'm working on a project where I can use multiple forms on an html page to search and update tables from a mysql database. I have created a basic html form that will run a search on a separate php file. When I try to integrate that same php script into that same html it finds no results. Any help would be appreciated.
basic html
<html>
<body>
<form name="search" method="post" action="searchresults.php">
<input name="search" type="text" size="40" maxlength="50" />
<input type="submit" name="Submit" value="Search" />
</form>
</body>
</html>
search php
<?php
$database = "dbname";
$username = "name";
$password = "pass";
$host = "host";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error){
die("Failed:" . $conn->connect_error);
}
echo"Successful";
$query = $_POST['search'];
$query = htmlspecialchars($query);
$raw_results = mysqli_query($conn,"SELECT * FROM beers WHERE name LIKE '%".$query."%'");
if(mysqli_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysqli_fetch_array($raw_results)){
echo "<p><h3>".$results['Name']."</h3>".$results['Brewery']."</p>";
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>
This works separated, but if I copy the same php script and insert it into the main html it connects but finds no results. Tried using _GET instead of _POST removed the action field and Ive searched all over for similar issues. If I scale everything completely down it gives me a parse error for $query = htmlspecialchars($query); , any thoughts?
Apply if (isset($query)) {...}. Only when search name is valid can you gain results.
<?php
$query = $_POST['search'];
// Apply validation.
if (isset($query)) {
$query = htmlspecialchars($query);
echo"Successful";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Failed:" . $conn->connect_error);
}
$raw_results = mysqli_query($conn, "SELECT * FROM beers WHERE name LIKE '%" . $query . "%'");
if (mysqli_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while ($results = mysqli_fetch_array($raw_results)) {
echo "<p><h3>" . $results['Name'] . "</h3>" . $results['Brewery'] . "</p>";
}
} else { // if there is no matching rows do following
echo "No results";
}
}
?>

PHP fails to post to MySQL Database

I have a formText.php file that contains a form with the following code form code:
<form action="insert.php" method="post">
<p>
<label for="theNames">Name:</label>
<input type="text" name="theName" id="theName">
</p>
<p>
<label for="theCitys">City:</label>
<input type="text" name="theCity" id="theCity">
</p>
<p>
<label for="theAges">Are you over eighteen?(Y/N)</label>
<input type="text" name="theAge" id="theAge">
</p>
<p>
<label for="theDates">Date:</label>
<input type="text" name="theDate" id="theDate">
</p>
<input type="submit" value="Submit">
</form>
Then I have an insert.php file with the following script:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root","phpteste");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security (EDITED)
$theName = mysqli_real_escape_string($link, $_POST['theName']);
$theCity = mysqli_real_escape_string($link, $_POST['theCity']);
$theAge = mysqli_real_escape_string($link, $_POST['theAge']);
$theDate = mysqli_real_escape_string($link, date("Y-m-d h:i:s",$_POST['theDate']));
// attempt insert query execution
$sql = "INSERT INTO tabelateste (id, name, city, overeighteen, date) VALUES (NULL, '$theName', '$theCity', '$theAge', '$theDate')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
My database is called phpteste and my table name is tabelateste.
What am I doing wrong here?
Whenever I click Submit nothing comes up and nothing gets added to the database.
Your post data name fields are wrong. SO you need to change below line:
// Escape user inputs for security
$theName = mysqli_real_escape_string($link, $_POST['theName']);
$theCity = mysqli_real_escape_string($link, $_POST['theCity']);
$theAge = mysqli_real_escape_string($link, $_POST['theAge']);
$theDate = mysqli_real_escape_string($link, date("Y-m-d h:i:s",$_POST['theDate']));
You need to change date to signup_date as per your database table structure.
$sql = "INSERT INTO tabelateste (name, city, overeighteen, signup_date) VALUES ('$theName', '$theCity', '$theAge', '$theDate')";
$sql = "INSERT INTO tabelateste (`name`, `city`, `overeighteen`, `date`) VALUES ('$theName', '$theCity', '$theAge', '$theDate')";
Use this code
I just tested your code (copied and pasted) and it works perfectly under my server configuration (Windows 10 - PHP 5.6) . My best guess is that you have a typo in either the table name or the MySQL configuration.
If you copied this code from another site. Please check that you created the database and the table , and that the MySQL configuration is correct.
A good to check for this kind of mistakes so is to read the PHP error logs
Try it like this maybe
if(isset($_POST['submit']) && !empty($_POST) ){
$theName = $_POST['theName'];
$theCity = $_POST['theCity'];
$theAge = $_POST['theAge'];
$theDate = $_POST['theDate'];
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "phpteste";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tabelateste (name, city, overeighteen, date)
VALUES ('$theName ', '$theCity ', '$theAge ', '$theDate ')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

Issue passing form data to php variable. Variable seems empty

I'm a noob at PHP/MySQL. I've been looking around a lot but I can't figure out what's going wrong. Purpose of the script: update the value of item 1 and item 2 in the database of user with userID entered in txtUser.
I get my script working when I use a "fixed" value near userId in my query. However, when I try to use a variable ($player), it doesn't work. Seems like my variable is empty...
HTML:
<body>
<form id="form1" action="http://www.something.com/TestScript1.php" method="post" enctype="application/x-www-form-urlencoded">
<div>
<button type="submit" id="submit" value="Submit" title="SAVE">SAVE</button>
</div>
<div>
<input id="txtUser" name="txtUser" type="text" />
<input id="txtItem1" name="txtItem1" type="text" />
<input id="txtItem2" name="txtItem2" type="text" />
</div>
</form>
</body>
PHP :
$host = "localhost";
$user = "username";
$password = "password";
$database = "database";
$player = mysqli_real_escape_string($connection,$_POST['txtUser']);
$connection = mysqli_connect($host,$user,$password,$database) or die ("connection to server failed");
mysqli_select_db($connection,$database) or die ("couldn’t select database");
$item1 = mysqli_real_escape_string($connection,$_POST['txtItem1']);
$item2 = mysqli_real_escape_string($connection,$_POST['txtItem2']);
$query = "UPDATE table SET item1=$item1, item2=$item2 WHERE userId=$player";
$result = mysqli_query($connection,$query)
or die ("couldn’t execute update query: ".mysqli_error($connection));
echo "<h4>Data saved in the database</h4>";
mysqli_close($connection);
?>
Please put this line
$player = mysqli_real_escape_string($connection,$_POST['txtUser']);
After $connection
$connection = mysqli_connect($host,$user,$password,$database) or die ("connection to server failed");
Like
$connection = mysqli_connect($host,$user,$password,$database) or die ("connection to server failed");
$player = mysqli_real_escape_string($connection,$_POST['txtUser']);
Because you using $connection variable in mysqli_real_escape_string even before its initialised
$connection is not defined for line
$player = mysqli_real_escape_string($connection,$_POST['txtUser']);
please move this line after you create $connection
$connection = mysqli_connect($host,$user,$password,$database) or die ("connection to server failed");
<?php
$host = "localhost";
$user = "username";
$password = "password";
$database = "database";
$conn = mysqli_connect($host,$user,$password,$database) or die ("connection to server failed");
mysqli_select_db($conn,$database) or die ("couldn't select database");
/* The $conn object must be declared before first / any calls to mysqli_real_escape_string */
$player = mysqli_real_escape_string($conn,$_POST['txtUser']);
$item1 = mysqli_real_escape_string($conn,$_POST['txtItem1']);
$item2 = mysqli_real_escape_string($conn,$_POST['txtItem2']);
/* Values in query should be encapsulated in quotes if they are strings.. are they? */
$query = "UPDATE `table` SET `item1`='$item1', `item2`='$item2' WHERE userId='$player';";
/* Try not to reveal too many details in the event of an error, reduce the attack surface if possible! */
$result = mysqli_query($conn,$query) or die ("update failed: ");
echo "<h4>Data saved in the database</h4>";
mysqli_close($conn);
?>

Categories