php to MySQL not working and not sure why - php

Its a really simple script, or at least it should be. I am kinda not sure around pHp so Im not sure where I am going wrong.
This page is called from a submit button on a form, all it is supposed to do is capture the name, email address and date of submission and add it to my database.
I can connect to the database without issue but cannot add to the database.
For some reason, everytime I load this page I also get a blank screen. pHp / SQL doesnt look like it has friendly bug reporting.
Here is the code with obvious info take outs.
<html>
<head>
</head>
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "123";
$db_name = "emailtest";
$conn = #mysql_connect($db_host,$db_username,$db_pass,$db_name);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
} else {
echo "Good connection ";
}
if(!empty($_REQUEST['name']))
{
$name = $_REQUEST['name'];
echo "hello, $name ";
if(!empty($_REQUEST['email']))
{
$email = $_REQUEST['email'];
}
else
{
$email = NULL;
}
if($email)
{
if ($conn->query($sql) === TRUE)
{
$dateTime = date("Y/m/d");
$sql = "INSERT INTO Newsletter_signup (name, email, sign_up_date) VALUES('$name','$email','$dateTime')";
echo "Record updated successfully <br/>";
echo "The email address, $email , has been added to the newsletter.";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
else
{
echo 'Please go back and insert an email address.';
}
?>
<body id="body">
// body style stuff
</body>
</html>

because you define $sql after the $conn->query($sql) and $sql is empty.

You're mixing up MySQL and MySQLi
mysqli_connect returns an instance for mysqli.
Your script should throw an error for trying to call a method on a non-object, because mysql_connect returns a resource.
You should enable error reporting at first (See: this SO question + answer)
The second thing is what #LTasty said: You use $sql, which is not defined at the point you want to execute the query.
When you changed these things, you should have a look at prepared statements, because your script is vulnerable against SQL injection.

Thanks all. I would like to say that you all gave credit to the answer.
For people learning from my mistakes here is the code that now works.
I will only put up the php side code.
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "123";
$db_name = "emailtest";
$conn = new mysqli($db_host,$db_username,$db_pass,$db_name);
$dateTime = date("Y/m/d");
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
} else {
echo "Good connection ";
}
if(!empty($_REQUEST['name']))
{
$name = $_REQUEST['name'];
echo "hello, $name ";
}
if(!empty($_REQUEST['email']))
{
$email = $_REQUEST['email'];
}
else
{
$email = NULL;
}
if($email)
{
$sql = "INSERT INTO Newsletter_signup (name, email, sign_up_date) VALUES('$name','$email','$dateTime')";
if ($conn->query($sql) === TRUE)
{
echo "Record updated successfully <br/>";
echo "The email address, $email , has been added to the newsletter.";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
else
{
echo 'Please go back and insert an email address.';
}
?>
I havent included the error reporting that can be activiated via pHp into my script yet, but thanks for the link I will include it now.

Related

"Can't use function return value in write context" when using mysqli_num_rows()

I've been working on adding users to my database and I tried to do something to check if login is already occupied. If it's not, PHP should add the user to database, else give alert that login is already used. Here's my code:
<?php
$servername = 'localhost';
$username = 'wiktor';
$password = 'wiktor';
$database = 'something';
$login = $_POST['login'];
$passwd = $_POST['pass'];
$name = $_POST['name'];
$surname = $_POST['sur'];
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Error " . $conn->connect_error);
} else {
echo "Connect success <br>";
}
$check = "select login from users where login = '$login'";
$test = $conn->query($check);
if(mysqli_num_rows($test) = 0){
$sql = "insert into users
values (null,'$login','$passwd','$name','$surname')";
if ($conn->query($sql) === TRUE) {
echo "Success";
} else {
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
echo "The login is already in use!";
}
$conn->close();
?>
I'm getting "Can't use function return value in write context" on line
if(mysqli_num_rows($test) = 0)
which checks if there are any records with that login.
I used something similar before and it worked perfectly so what could be the problem now?
Write this
if(mysqli_num_rows($test) == 0)
Instead of,
if(mysqli_num_rows($test) = 0)

User information not getting into MYSQL db

m making this user signup form and linking the user email name and password tot he table in mysql DB, but it's not showing any row in mySQl DB.
Here is the code:
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$query_input = mysql_query($connect,"INSERT INTO user_basic_info(username,email,password)VALUES('$username','$email','$password')");
if($query_input){
echo "done and dope";
}
else{
echo "no";
}
}
You have a error in your mysql_query function
$query_input = mysql_query("INSERT INTO user_basic_info(username,email,password) VALUES('$username','$email','$password')",$connect);
see http://php.net/manual/en/function.mysql-query.php
BTW please use mysqli
mysqli_query("INSERT INTO user_basic_info(username,email,password)VALUES('$username','‌​$email','$password')‌​",$connect);
Firstly you should try to use MySQLi or PDO (tutorial here)
$connect = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$query_input = mysqli_query($connect,"INSERT INTO user_basic_info(username,email,password)VALUES('$username','$email','$password')");
if($query_input){
echo "done and dope";
}
else{
echo "no";
}
//close db connection
mysqli_close($connect);
}

database updating using php

well i just made a form in HTML witch accepts user inputs and a mysql database to store them, now in the php file everything goes well no errors but the problem is the data never displays in the database, here is the php file:
<?php
if(isset($_POST["submitacc"])){
$servernm = "localhost";
$serverusrnm = "root";
$serverpass = "2003";
$db = "blue";
$conn = new mysqli($servernm, $serverusrnm, $serverpass, $db);
if($conn ->connect_error){
die("connection failed".$conn->connect_error);
}
$fnm = $_POST["fnm"];
$lnm = $_POST["lnm"];
$mail = $_POST["mail"];
$pass = $_POST["pass"];
$age = $_POST["age"];
$gender = $_POST["gender"];
if(isset($_POST["gender"])&&$_POST["gender"]=="male"){
$gender = "male";
}else {
$gender = "female";
}
$mysql="update createacc set fnm = '$fnm', lnm = '$lnm', mail = '$mail', passwod = '$pass', age = '$age', gender = '$gender' ";
if($conn->query($mysql)== true){
echo "record updated";
}else {
echo "error updating record".$conn->error;
}
$conn->close();
}
?>
Use mysqli_query() instead of query(). Also use WHERE clause in your $mysql variable. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!
Example:
if(mysqli_query($conn , $mysql)){
echo "Records were updated successfully.";
} else {
echo "ERROR: Could not able to execute $mysql. " . mysqli_error($conn);
}

PHP syntax error for storing data into mysql db

I have resolved the issue. The following code now works perfectly.
Thank you all.
Please the relevant section of dbcontroller.php file as follows:
<?php
class DBController {
function runQuery2($query) {
$result = mysql_query($query);
return $result;
}
}
In addition, I have amended my original MySQL statements in my main html/php file to look like this:
<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["submit"])) {
if ($db_handle->runQuery2("INSERT INTO cquestionstable
(postid, ccode, nick, queries) VALUES ( 1,'cc-001', 'james', 'what
could be the problem?')") === TRUE) {
echo "New record created successfully";
} else {
echo "Error in posting question, pls try again." . "<br>";
}
?>
Thanks n cheers.
Your Code:
<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["submit"])) {
$sql = "INSERT INTO cquestionstable (postid, ccode, nick, queries) VALUES ( 1,'cc-001', 'james', 'what could be the problem?')";
if ($db_handle->runQuery($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $**sql . "<br>" . $db_handle->error;
}
}
?>
I see the errors already.
First if (!empty($_POST["submit"])) { should be if (isset($_POST["submit"])) {
Then you used if ($db_handle->runQuery($sql) === TRUE) { which should actually be if ($conn->query($sql) === TRUE) {
Then in your echo you used $**sql which should be $sql
Then i did not know what dbcontroller.php was but the final code should be
<?php
// session_start(); You do not need this when inserting into database
include "dbcontroller.php";
if (isset($_POST["submit"])) {
$sql = "INSERT INTO cquestionstable (postid, ccode, nick, queries) VALUES (1, 'cc-001', 'james', 'what could be the problem?')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $connn->error;
}
}
?>
dbcontroller.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
If you still do not understand why it is not working please look at w3Schools
Hope this is the answer you we're looking for.

Delete Page PHP MYSQL

Hey guys I have created A delete page, It does not work when I just submit the form and the URL is http://localhost/delete-session.php but once I change the URL to http://localhost/delete-session.php?id=1 it works, What am I missing In my code to make it work?
<h1>Delete Page</h1>
<h3>Enter the booking number of the session you would like to delete!</h3>
<form action ="delete-session.php" method="post">
Booking ID:(Refer To Database):<input type="text" name="booking">
This is the php
if(isset($_GET['booking'])){
$id=$_GET['booking'];
if(!is_numeric($id)){
echo "sorry, there appears to have been an error.";
exit;
}
} else {
echo "sorry, there appears to have been an error.";
exit;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "olympics";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$id=$_GET['id'];
if(!is_numeric($id)){
echo "Sorry, there is an error";
exit;
}
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="DELETE from olympiics where booking='$id'";
echo $sql;
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
I'm going to take a crack at this.
I'm guessing it's because when you go to http://localhost/delete-session.php?id=1 you're passing the id=1 via GET, so when you retrieve the GET input from in your code it succeeds with $id=1, but in your HTML your form is send via POST.
As a fix try using $id=$_POST['booking'];
Bench test your code.
It starts getting $id=$_GET['booking']; which does not exist because you have set the method="post" in your <form> tag.
So use $id=$_POST['booking'];
Then later on it does $id=$_GET['id']; overwriting the value you already attempted to get from above.
This would explain why it requires the extra id paramter on http://localhost/delete-session.php?id=1 as using the querystring to send data will send the id parameter in the $_GET['id'] array, and I dont see why you would want to do this anyway as it has been done at the top of your code by getting this id value from $id=$_POST['booking']
It also makes code so much easier to read and more importantly debug if you adopt an indentation standard in your script like below.
Try this out for size, without adding the id=1 to the querystring
if(isset($_POST['booking'])){
$id=$_POST['booking'];
if(!is_numeric($id)){
echo "sorry, there appears to have been an error. Booking must be numeric";
exit;
}
} else {
echo "sorry, there appears to have been an error.";
exit;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "olympics";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="DELETE from olympiics where booking='$id'";
$res = mysqli_query($conn, $sql);
if ($res !== FALSE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
As you are using the mysqli extension, you should also be using parameterized queries to prevent SQL Injection.
if(isset($_POST['booking'])){
$id=$_POST['booking'];
if(!is_numeric($id)){
echo "sorry, there appears to have been an error. Booking must be numeric";
exit;
}
} else {
echo "sorry, there appears to have been an error.";
exit;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "olympics";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="DELETE from olympiics where booking=?";
$stmt = mysqli_prepare($conn, $sql);
if ( $stmt === FALSE ) {
echo mysqli_error($conn);
exit;
}
mysqli_stmt_bind_param($stmt, 'i', $id);
$res = mysqli_stmt_execute($stmt);
if ($res !== FALSE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Change form method to get, or use $_REQUEST instead of $_GET

Categories