My PHP code.
<?php
$servername = "localhost";
$username = "xxxxxxxxx";
$password = "xxxxxxxxx";
$database = "xxxxxxxxx";
$postdata = file_get_contents("php://input");
$data = json_decode($postdata, true);
$table = $data['table'];
$name = $data['name'];
$email = $data['email'];
$points = $data['points'];
$percentage = $data['percentage'];
$userAnswers = $data['userAnswers'];
function connect_DB($servername, $username, $password, $database) {
$db_conn = new mysqli($servername, $username, $password, $database);
$char = $db_conn->query("SET NAMES 'utf8'");
if ($db_conn->connect_error) {
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
die("Connection failed: " . $db_conn->connect_error);
}
else {
echo "Connected successfully \r\n";
}
return $db_conn;
}
function create_DB_table($db, $table) {
$sql = "CREATE TABLE IF NOT EXISTS $table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
reg_date TIMESTAMP
)";
if ($db->query($sql) == TRUE) {
echo "Table successfully created \r\n";
}
else {
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
die("Table creation failed: " . $db->error);
}
}
function addColumnVarchar($conn_obj, $table, $column) {
$sql = $conn_obj->prepare("SHOW COLUMNS FROM $table LIKE '%$column%'"); // add wildcard
$sql->execute();
if($sql->num_rows <= 0) {
$sql->store_result();
$sql1 = $conn_obj->prepare("ALTER TABLE $table ADD COLUMN $column VARCHAR(255)");
$sql1->execute();
}
}
function addColumnFloat($conn_obj, $table, $column) {
$sql = $conn_obj->prepare("SHOW COLUMNS FROM $table LIKE '%$column%'"); // add wildcard
$sql->execute();
if($sql->num_rows <= 0) {
$sql->store_result();
$sql1 = $conn_obj->prepare("ALTER TABLE $table ADD COLUMN $column FLOAT");
$sql1->execute();
}
}
function insert_DB($db, $table, $column, $value) {
$sql = "INSERT INTO $table ($column)
VALUES ($value)";
if( $db->query($sql) == TRUE) {
echo "Records inserted successfully!";
}
else {
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
die("Records insertion failed: " . $db->error);
}
}
//connect to the database and create table
$conn_obj = connect_DB($servername, $username, $password, $database);
create_DB_table($conn_obj, $table);
$columnArr = array();
$valueArr = array();
if (!is_null($name)){
addColumnVarchar($conn_obj, $table, 'name');
array_push($columnArr, "name");
array_push($valueArr, $name);
}
if (!is_null($email)){
addColumnVarchar($conn_obj, $table, 'email');
array_push($columnArr, "email");
array_push($valueArr, $email);
}
if (!is_null($points)){
addColumnFloat($conn_obj, $table, 'points');
array_push($columnArr, "points");
array_push($valueArr, $points);
}
if (!is_null($percentage)){
addColumnFloat($conn_obj, $table, 'percentage');
array_push($columnArr, "percentage");
array_push($valueArr, $percentage);
}
if (!is_null($userAnswers)){
foreach ($userAnswers as $ua) {
addColumnVarchar($conn_obj, $table, $ua['qID']);
array_push($columnArr, $ua['qID']);
array_push($valueArr, wordwrap($ua['answer'], 60, "\n", false));
}
}
$column = implode(",", $columnArr);
$value = "'".implode("','", $valueArr)."'";
insert_DB($conn_obj, $table, $column, $value);
$conn_obj->close();
The output is:
Connected successfully Table creation failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, reg_date TIMEST' at line 1
Is there a syntax error?
Related
Here is my code:
<?php
class Db
{
private $servername = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'emp';
function __construct()
{
$this->db = new mysqli(
$this->servername,
$this->username,
$this->password,
$this->dbname
);
if ($this->db->connect_error) {
die("Connection failed: " . $this->db->connect_error);
}
}
public function insert_record($table, $fields)
{
$sql = "";
$sql .= "INSERT INTO " . $table;
$sql .= " (" . implode(",", array_keys($fields)) . ")values";
$sql .= " ('" . implode("','", array_values($fields)) . "')";
$query = mysqli_query($this->db, $sql);
if ($query) {
return true;
}
}
}
//making object of the class
$crudobj = new Db;
//insert code for adding data in to the db
if (isset($_POST['submit'])) {
$myArray = array(
"username" => $_POST["unm"],
"email" => $_POST["eid"],
"password" => $_POST["pass"]
);
//inserting data
if($crudobj->insert_record("users", $myArray))
{
header("location: login.pho")
}
}
?>
Call it with your input email.
if($crudobj->is_email_exists($_POST["eid"]))
{
echo "Email Already Exist";
}
Add below function in your DB class:
public function is_email_exists($email)
{
if(filter_var($email, FILTER_VALIDATE_EMAIL))
{
$email = mysqli_real_escape_string($this->db, $email);;
$sql = "SELECT email FROM users WHERE email='".$email."';";
if($result = mysqli_query($this->db, $sql))
{
return mysqli_num_rows($result);
}
}
return true;
}
I am trying to select a column in mysql in php,
function PageController() {
$data = [
'categories' => _db_get_select("categories", ['name'])
];
load_view("tutu", $data);
and
function _db_get_select($table_name, $columns) {
$servername = _c("database.server_name");
$username = _c("database.username");
$password = _c("database.password");
$dbname = _c("database.db_name");
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$sql = "SELECT name=$columns FROM . $table_name.";
var_dump($sql);
the result is displaying like this
string(42) "SELECT ['name']=Array FROM . categories."
I want to be like this
SELECT name FROM . categories.
Thanks in advance.
You may use this script
function PageController() {
$data = [
'categories' => _db_get_select("categories", "name")
];
load_view("tutu", $data);
And the function will be
function _db_get_select($table_name, $columns) {
$servername = _c("database.server_name");
$username = _c("database.username");
$password = _c("database.password");
$dbname = _c("database.db_name");
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT {$columns} FROM {$table_name}";
}
Just echo your sql variable instead of var dump like below
echo $sql;
Use foreach loop to iterate through an array of columns to form a query.
function PageController() {
$data = array('categories' => _db_get_select("categories", array("name")));
load_view("tutu", $data);
}
And then:
//Start with select
$sql = 'SELECT ';
//Concat column names separated with commas
foreach ($columns as $value) {
$sql .= $value . ', ';
}
//Get rid of the last comma
$sql = rtrim($sql, ', ');
$sql .= ' FROM ' . $table_name;
Check if it's okey:
var_dump($sql);
I'm trying to make a registration script using PHP with Mysql database. The insertion cannot be done. If I register with an email-id which is already in the database, it is working fine. But, the script fails to insert new entries. It is returning 'bool(false)'.
I've tried the to do the same using PDO. The insertion can't be done. So, I tried mysqli prepared statements instead and even this yields the same result. Here is the code.
<?php
$dbh = new mysqli('localhost', 'user', 'pass', 'db');
if(isset($_POST['register'])){
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_POST['$name'];
$mail = $_POST['mail'];
$passw = $_POST['passw'];
$codeone = $_POST['codeone'];
$descs = $_POST['desc'];
$newstrings = 'specialstring';
$encrypted_pass = crypt( $passw );
$stmt = $dbh->prepare("SELECT mail FROM userrecs WHERE mail=?");
$stmt->bind_param('s',$mail);
if($stmt->execute())
{
$stmt->store_result();
$rows = $stmt->num_rows;
if($rows == 1)
{
session_start();
$_SESSION['notification_one'] = 'bla';
header('location:/someplace');
}
else {
$statement = $db->prepare("INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (?,?,?,?,?,?,?)");
$statement->bind_param('ssssiss',$ip,$name,$mail,$encrypted_pass,$codeone,$descs,$newstrings);
try {
if($statement->execute())
{
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
}
else
{
var_dump($statement->execute());
$statement->errorInfo();
}
}
catch(PDOException $pe) {
echo "S";
echo('Connection error, because: ' .$pe->getMessage());
}
}
}
}
else{
header('location:/someplace');
}
?>
EDIT:
This is the PDO-only code. I was mixing PDO and mysqli in the previous code.
<?php
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = 'user';
$password = 'pass';
$dbh = new PDO($dsn, $user, $password);
if(isset($_POST['regsubmit'])){
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_POST['$name'];
$mail = $_POST['mail'];
$pass = $_POST['passw'];
$codeone = $_POST['codeone'];
$descs = $_POST['desc'];
$newstrings = 'specialstring';
$encrypted_pass = crypt( $passw );
$sql = "SELECT mail FROM userrecs WHERE mail=:mail";
$statement = $dbh->prepare($sql);
$statement->bindValue(':mail',$mail,PDO::PARAM_STR);
if($statement->execute())
{
if($statement->rowCount() == 1)
{
session_start();
$_SESSION['noti_one'] = 'bla';
header('location:/someplace');
}
else {
$sql2 = "INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (:ip,:name,:mail,:encrypted_pass,:codeone,:descs,:newstrings)";
$stmt = $dbh->prepare($sql2);
$stmt->bindParam(':ip',$ip,PDO::PARAM_STR);
$stmt->bindParam(':name',$name,PDO::PARAM_STR);
$stmt->bindValue(':mail',$mail,PDO::PARAM_STR);
$stmt->bindParam(':encrypted_pass',$encrypted_pass,PDO::PARAM_STR);
$stmt->bindParam(':codeone',$codeone,PDO::PARAM_STR);
$stmt->bindParam(':descs',$descs,PDO::PARAM_STR);
$stmt->bindParam(':newstrings',$temstr,PDO::PARAM_STR);
try {
if($stmt->execute())
{
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
}
else
{
var_dump($stmt->execute());
$stmt->errorInfo();
}
}
catch(PDOException $pe) {
echo "S";
echo('Connection error, because: ' .$pe->getMessage());
}
}
}
}
else{
header('location:/someplace');
}
?>
Please ignore variable or table names. I edited some of the names here.
You are mixing PDO and mysqli driver in the same script, this is not possible.
Please use either one but not both.
PDO is the prefferred extension.
EDIT:
In your query:
INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (...)
NAME is a mysql reserved keyword, you escape it by using backticks:
INSERT INTO userrecs (ip,`name`,mail,pass,codeone_one,desc_one,spcstrings) VALUES (...)
EDIT:
Change
var_dump($statement->execute());
$statement->errorInfo();
to
var_dump($statement->errorInfo());
EDIT:
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = 'user';
$password = 'pass';
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['regsubmit'])) {
try {
$sql = "SELECT mail FROM userrecs WHERE mail=:mail";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':mail', $_POST['mail'], PDO::PARAM_STR);
if ($stmt->execute() && $stmt->rowCount() == 1) {
session_start();
$_SESSION['noti_one'] = 'bla';
header('location:/someplace');
} else {
$sql = "INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (:ip,:name,:mail,:encrypted_pass,:codeone,:descs,:newstrings)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
$stmt->bindValue(':name', $_POST['$name'], PDO::PARAM_STR);
$stmt->bindValue(':mail', $_POST['mail'], PDO::PARAM_STR);
$stmt->bindValue(':encrypted_pass', crypt($_POST['passw']), PDO::PARAM_STR);
$stmt->bindValue(':codeone', $_POST['codeone'], PDO::PARAM_STR);
$stmt->bindValue(':descs', $_POST['desc'], PDO::PARAM_STR);
$stmt->bindValue(':newstrings', 'specialstring', PDO::PARAM_STR);
if ($stmt->execute()) {
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
} else {
var_dump($stmt->errorInfo());
}
}
} catch (PDOException $pe) {
echo "S";
echo('Connection error, because: ' . $pe->getMessage());
}
} else {
header('location:/someplace');
}
I believe you have an error in your logic.
Try this code and see what you get ...
<?php
$dbh = new mysqli('localhost', 'user', 'pass', 'db');
if(isset($_POST['register'])) {
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_POST['$name'];
$mail = $_POST['mail'];
$passw = $_POST['passw'];
$codeone = $_POST['codeone'];
$descs = $_POST['desc'];
$newstrings = 'specialstring';
$encrypted_pass = crypt($passw);
$stmt = $dbh->prepare("SELECT mail FROM userrecs WHERE mail=?");
$stmt->bind_param('s', $mail);
$test = $stmt->execute();
if($test) {
$stmt->store_result();
$rows = $stmt->num_rows;
if($rows == 1) {
session_start();
$_SESSION['notification_one'] = 'bla';
header('location:/someplace');
} else {
$statement = $db->prepare("INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (?,?,?,?,?,?,?)");
$statement->bind_param('ssssiss', $ip, $name, $mail, $encrypted_pass, $codeone, $descs, $newstrings);
try {
if($statement->execute()) {
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
} else {
var_dump($statement->execute());
$statement->errorInfo();
}
} catch (PDOException $pe) {
echo "S";
echo('Connection error, because: ' . $pe->getMessage());
}
}
}else{
echo "test is not ok";
var_dump($test);
}
} else {
header('location:/someplace');
}
i'm getting 500 internal error in this script for some reason i looked trough the script for like an hour or two cant find the issue in the function, its not an mysql error ether..
function CreateGame($Game, $Pass, $Diff, $CharInfo, $Lad, $Desc, $Realm, $Hash, $timestamp, $Bot = 0)
{
$uno = false;
include "conf.php";
$conn = new mysqli($serverip, $username, $password, $dbname, $Port);
if ($conn->connect_error) {
die("Connection failed: " . encrypt($conn->connect_error);
}
$game = mysqli_escape_string($conn, $Game);
$pass = mysqli_escape_string($conn, $Pass);
$diff = mysqli_escape_string($conn, $Diff);
$hash = mysqli_escape_string($conn, $Hash);
$charInfo = mysqli_escape_string($conn, $CharInfo);
$desc = mysqli_escape_string($conn, $Desc);
$realm = substr($Realm, 0, 1);
$realm = mysqli_escape_string($conn, $Realm);
$bot = mysqli_escape_string($conn, $Bot);
$lad = mysqli_escape_string($conn, $Lad);
$UserResult = $conn->query("SELECT * from user where hash = '$hash'");
if (!$UserResult)
{
echo encrypt("hash not found: ". $hash);
}
while($row = $UserResult->fetch_assoc())
{
if($uno == false)
{
$uno = true;
$BanCheckQuerrt = "SELECT * from hwid where id = '".$row['HWID']."'";
$BanCheckResult = $conn->query($BanCheckQuerrt);
while($BanCheckRow = $BanCheckResult->fetch_assoc())
{
if((int)$BanCheckRow['banned'] === 0)
{
$sql = "INSERT INTO games (Game, Password, Description, Difficulty, Realm, Ladder, BotGame, created, timestamp ) VALUES ('$game', '$pass', '$desc', '$diff', '$realm', 'lad', '$bot', '$timestamp', '$timestamp')";
if ($conn->query($sql) === TRUE) {
$sqli = "INSERT INTO Players (GameID, Name, timestamp) Values ('".mysqli_insert_id($conn)."', '$charInfo', '$timestamp')";
if ($conn->query($sqli) === TRUE) {
$updateUserQuerry = "UPDATE user SET playerID = '" .mysqli_insert_id($conn). "' where hash = '$hash'";
$conn->query($updateUserQuerry);
echo encrypt(mysqli_insert_id($conn));
} else {
echo "Error: " . $sqli . "\n" . encrypt($conn->error);
}
} else {
echo "Error: " . $sql . "\n" . encrypt($conn->error);
}
}
else
echo encrypt("Banned!");
}
}
}
$conn->close();
}
any suggestion that would fix this problem would be acceptably.
I am making a game for class and I have decided to include an admin area where settings may be modified. Currently this is how I have established a database connection:
db_config.php:
<?php
defined('DB_SERVER') ? null : define('DB_SERVER', 'localhost');
defined('DB_USER') ? null : define('DB_USER', 'root');
defined('DB_PASS') ? null : define('DB_PASS', 'root');
defined('DB_NAME') ? null : define('DB_NAME', 'game');
?>
database.php:
<?php
require_once('db_config.php');
class DatabaseConnect {
public function __construct($db_server, $db_user, $db_pass, $db_name) {
if (!#$this->Connect($db_server, $db_user, $db_pass, $db_name)) {
echo 'Connection failed.';
} else if ($this->Connect($db_server, $db_user, $db_pass, $db_name)){
}
}
public function Connect($db_server, $db_user, $db_pass, $db_name) {
if (!mysqli_connect($db_server, $db_user, $db_pass, $db_name)) {
return false;
} else {
return true;
}
}
}
$connection = new DatabaseConnect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
?>
Up to this point I have used mysql_real_escape_string in my queries and I know that I shouldn't be manually escaping. I am still learning PHP so some things take me a while to grasp. I have had a look at the php.net prepared statement manual but I am not sure whether I need to change the way I have connected to the database.
So basically what I am asking is if I had this query (or any query for that matter):
if (isset($_POST['submit'])) {
// Process the form
$id = $current_page["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$content = mysql_prep($_POST["content"]);
// validations
$required_fields = array("menu_name", "position", "visible", "content");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors)) {
// Perform Update
$query = "UPDATE pages SET ";
$query .= "menu_name = '{$menu_name}', ";
$query .= "position = {$position}, ";
$query .= "visible = {$visible}, ";
$query .= "content = '{$content}' ";
$query .= "WHERE id = {$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
// Success
$_SESSION["message"] = "Page updated.";
redirect_to("manage_content.php?page={$id}");
} else {
// Failure
$_SESSION["message"] = "Page update failed.";
}
}
} else {
// This is probably a GET request
} // end: if (isset($_POST['submit']))
?>
How would it be changed into a prepared statement?
For the SQL portion, try this >>
$records_found = 0;
$record = false;
$cn = mysqli_connect($host, $user, $pass, $data);
$query = "UPDATE pages SET menu_name=?, position=?, visible=?, content=? WHERE id=? LIMIT 1"
$stmt = mysqli_prepare($cn, $query);
$stmt->bind_param("s", $menu_name);
$stmt->bind_param("s", $position);
$stmt->bind_param("s", $visible);
$stmt->bind_param("s", $content);
$stmt->bind_param("d", $id);
$result = $stmt->execute();
if($result) {
$result = $stmt->get_result();
if($result) {
while($row = $result->fetch_assoc()) {
if($records_found == 1) {
break;
}
$record = $row;
$records_found++;
}
mysqli_free_result($result);
}
}
mysqli_close($cn);
// Output the record found if any
if($record) {
var_export($record);
} else {
echo 'No records found';
}
Also, read the docs on it here >> mysqli.prepare << as there are some really good examples.
**NOTE: The above solution provides complete code from connecting to the db, to closing the connection and freeing the memory consumed, with a condition block after to allow you to work with the resulting row if any found. Basically, all trapping is complete aside from or die(mysqli_error($cn)); stuff.
This is how you create a prepared statement.
$query = "UPDATE pages SET menu_name=?, position = ?,
visible=?, content=? WHERE id=? LIMIT 1";
$stmt = mysqli_prepare($connection, $query);
$result = false;
if($stmt){
mysqli_stmt_bind_param( $stmt, "ssdsd", $menu_name,
$position, $visible, $content,$id );
$result = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
if($result){
//Successful
}
else{
//Unsuccessful
}
I made some assumptions regarding the type of the fields in the database but the notation is in mysqli_stmt_bind_param , 's' stands for string and 'd' stands for integer.