PHP syntax error for storing data into mysql db - php

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.

Related

how to read API data and insert it into MYSQL with php

So I am trying to get conversion rates from an API and I get the following data:
https://api.exchangeratesapi.io/history?start_at=2017-01-01&end_at=2018-09-01&symbols=EUR&base=GBP
How can I loop over the data and insert date & conversion rate into MYSQL DB.
Any help is greatly appreciated.
I am currently standing here:
$host="localhost";
$user="conversion";
$pass="password";
$db="areporting";
$connect= new mysqli($host,$user,$pass,$db) or die("ERROR:could not connect
to the database!!!");
$string = file_get_contents("https://api.exchangeratesapi.io/history?start_at=2017-01-01&end_at=2018-09-01&symbols=EUR&base=GBP");
$json = json_decode($string, true);
var_dump($json);
here a screenshot of the Data I get:
You can use foreach on json result :
<?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);
}
$string = file_get_contents("https://api.exchangeratesapi.io/history?start_at=2017-01-01&end_at=2018-09-01&symbols=EUR&base=GBP");
$json = json_decode($string, true);
foreach($json['rates'] as $date =>$conversion){
$sql = "INSERT INTO Mytable (id, date, conversion)
VALUES ( '$date', ".$conversion['EUR'].")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully"."<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."<br>";
}
}
$conn->close();
?>
Thanks for all the Tips, here I have my working solution:
foreach($json['rates'] as $date => $conversion){
$timestamp = strtotime($date);
$sql = "INSERT INTO m_fx_rate_temp
(`base`, `counter`, `fxRate`, `date`) VALUES ('gbp', 'eur', ".$conversion['EUR'].", Date_format(FROM_UNIXTIME($timestamp), '%Y-%m-%d'))";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully"."<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."<br>";
}
}

PHP SQL Why does this give me an error without details

Hi I'm trying to insert data in my database. But I keep on getting the same error for example:
Error: INSERT INTO users (username, password) VALUES ('fff', '$2y$10$YUd1AErIj4RGRnjkFkYlkOn.s9OV62sq8.HVGO2jeE8dSthpgp6ey');
without any details which is very frustrating. I'm new to PHP and SQL so it's not the best written code ever and I know I should use prepared statements.
<?php
require_once '../connection/connection.php';
/**
* Created by PhpStorm.
* User: ezrab
* Date: 3/14/2018
* Time: 5:40 PM
*/
$username = $_POST['username'];
$password = $_POST['password'];
//var_dump($hashed_password);
if (isset($_POST['submit'])) {
if (!empty($username) || !empty($password)) {
if (preg_match('/^[A-Za-z]?[A-Za-z ]*$/', $username) || preg_match('/^[A-Za-z]?[A-Za-z ]*$/', $password)) {
$hashPwd = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$hashPwd');";
if ($conn->query($sql) === TRUE) {
echo "Worked!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "You can't use certain characters.";
}
} else {
echo "You have to fill in all fields.";
}
} else {
echo "THOU SHALL NOT PASS!";
}
$conn->close();
EDIT: Added my connection.php file for more information.
<?php
$servername = "-----";
$username = "-----";
$password = "------";
$dbname = "------";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
EDIT:
Take
$conn->close();
out of connection.php and problem should be solved
You were opening and then immediately closing the connection before a query could be made

Why is my PHP / SQL generating duplicate database entries?

I'm quite new to PHP and an absolute beginner when it comes to SQL. I'm just learning the basics and I can't get my head around why my code is generating a duplicate entry every time the form is submitted, e.g.
Name: Joe Blogs Email: info#email.co.uk
Name: Joe Blogs Email: info#email.co.uk
The database has a table called user and two columns, name and email.
My index file looks like this, it has a simple form for name and email, and inserts the data on submit:
<form method="post" action="insert.php">
<input name="name" type="text">
<input name="email" type="email">
<input type="submit" value="Submit Form">
</form>
<?php
$servername = "localhost";
$username = "DB_USER";
$password = "PASSWORD";
$dbname = "DB_NAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sqlout = "SELECT name, email FROM user";
$result = $conn->query($sqlout);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<b>Name:</b> " . $row["name"]. " <b>Email:</b> " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<form method="post" action="wipe.php">
<input type="submit" value="Wipe ALL Data">
</form>
This insert.php file is called when the form is submitted:
<?php
$servername = "localhost";
$username = "DB_USER";
$password = "PASSWORD";
$dbname = "DB_NAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user ( name, email ) VALUES ( '{$conn->real_escape_string($_POST['name'])}', '{$conn->real_escape_string($_POST['email'])}' )";
$insert = $conn->query($sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Back
I've probably made some basic mistakes but I'm not sure why it is adding duplicates. Is it something to do with connecting twice to the database in each file? Is there a better way to connect only once? Or is it caused by the form submission itself?
Because you call query twice:
$insert = $conn->query($sql);
if ($conn->query($sql) === TRUE) {
You should rewrite is as
$insert = $conn->query($sql);
if ($insert === TRUE) {
Also, you should really be using prepared statements.
Your code Call $conn->query twice
$insert = $conn->query($sql);// first time
if ($conn->query($sql) === TRUE) {// second time
if ($insert === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You need change:
$sql = "INSERT INTO user ( name, email ) VALUES ( '{$conn->real_escape_string($_POST['name'])}', '{$conn->real_escape_string($_POST['email'])}' )";
$insert = $conn->query($sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
to
$sql = "INSERT INTO user ( name, email ) VALUES ( '{$conn->real_escape_string($_POST['name'])}', '{$conn->real_escape_string($_POST['email'])}' )";
$status = $conn->query($sql);
if ($status === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

PHP Redirect stopped working?

I have wrote a script to update a MySql DB from a form.
After the DB has been updated I want the page to auto redirect to another page.
This has been working fine however since switching hosting provider non of my sites re-directs work.
Here is the code:
<?php
$servername = "localhost";
$username = "XXX";
$password = "XXX";
$dbname = "XXX";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id= $_POST[id];
$dob=$_POST[dob];
$sql=("update users set dob='$dob' where id='$id'")or die('Error 23 ' . mysql_error());
if ($conn->query($sql) === TRUE) {
echo "Updated successfully<br /><br />";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
<?php
header("location:index.php?action=updated"); ?>
When I run the code the DB updates but the page just displays Updated successfully?
try using javascript to redirect like below:
if ($conn->query($sql) === TRUE) {
echo "<script>
alert('Updated successfully');
window.location.href = 'index.php?action=updated';
</script>";
}
Don't echo anything and try to redirect afterwards. Instead simply redirect without any echoing.
if ($conn->query($sql) === TRUE) {
header("location:index.php?action=updated");
exit;
} else
echo "Error: " . $sql . "<br>" . $conn->error;
try this :
<?php
ob_start();
header('Location: http://www.example.com/index.php?action=updated', true);
?>

Php to MySQL database

I have problem with MySQL database, I can't insert the information into the table. My php code seems to work, but when I run it nothing happens.
<?php
$servername = "localhost";
$fname = "fname";
$lname = "lname";
$klas = "klas";
$nomer = "nomer";
$file = "dom";
$dbname = "homeworks";
$conn = new mysqli($servername, $fname, $lname,$klas,$file,$dbname);
$sql = "INSERT INTO student (fname, lname,klas,file)
VALUES ($servername, $fname, $lname,$klas,$file,)";
?>
You have three main problems in your code:
You're still not connected to the database
Only constructing and not executing
Having not matched parameters in the insert values
Solution :
1. Make a connection first
$conn = new mysqli($servername, $username, $password, $dbname);
The Parameter $servername, $username, $password, $dbname is obviously your hostname, Database Username, Password and the Database name
You should not have your table name or column names in the connection parameters
2. Construct the parameters which matches the coloumn name and variables correctly
$sql = "INSERT INTO student (fname, lname,klas,file)
VALUES ($fname, $lname,$klas,$file)";
3. Execute Your Query :
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Note :
Also it's good practice to close your connection once you are done
$conn->close();
So, you should be having something like this
<?php
$servername = "localhost";
$username = "YourDBUsername";
$password = "YourDBPassword";
$fname = "fname";
$lname = "lname";
$klas = "klas";
$nomer = "nomer";
$file = "dom";
$dbname = "homeworks"; //Hope you will have your db name here
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "
INSERT INTO student (fname, lname,klas,file) VALUES
('$fname'
,'$lname'
,'$klas'
,'$file');
";
if ($conn->query($sql) === TRUE) {
echo "New record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Advice :
Always use prepared statements else clean your inputs before you insert.
Your connection should look something like this. link
<?php
//change the data into your connection data
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
You made your query but didn't execute it.
if (mysqli_query($conn, $sql)) {
echo 'records created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($conn);
}

Categories