Updating data in DataBase with PHP - php

I have a simple script that should Update variable in a column where user login equals some login.
<?PHP
$login = $_POST['login'];
$column= $_POST['column'];
$number = $_POST['number'];
$link = mysqli_connect("localhost", "id3008526_root", "12345", "id3008526_test");
$ins = mysqli_query($link, "UPDATE test_table SET '$column' = '$number' WHERE log = '$login'");
if ($ins)
die ("TRUE");
else
die ("FALSE");
?>
but it doesn't work. It gives me - FALSE. One of my columns name is w1 and if I replace '$column' in the code with w1 it works fine. Any suggestions?

Simply remove quotes: '$column' = should be $column =
Your code is open for SQL Injection, use prepared statements.

change this "UPDATE test_table SET '$column' = '$number' WHERE log = '$login'"
to this "UPDATE test_table SET '".$column."' = ".$number." WHERE log = '".$login."'"

It's possible that your error is to do with the $column being set as a string with single quotation marks? Because it returns false, it suggests that you have a MySQL error of some sort.
To find out what the error message is, on your else block, rather than dying with a "FALSE" message, try use mysqli_error($link) - this should give you your error message

If removing the quotes surrounding the $column doesn't work, you could try the PDO method. Here's the snippet:
function insertUser($column, $number, $login) {
try
{
$connect = getConnection(); //db connection
$sql = "UPDATE test_table SET $column = '$number' WHERE log = '$login'";
$connect->exec($sql);
$connect = null;
} catch (Exception $ex) {
echo "EXCEPTION : Insert failed : " . $ex->getMessage();
}
}
function getConnection() {
$servername = "localhost";
$dbname = "my_db";
$username = "root";
$password = "12345";
try {
$connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo "EXCEPTION: Connection failed : " . $ex->getMessage();
}
return $connection;
}
Regarding $number, I'm not sure the datatype for the $number whether quotes or not is needed so experiment with or without quotes to see which one works.
And the getConnection() function is in separate PHP file where it will be included in any PHP files that calls for database connection.

Related

Inserting ID from primary col to another table

I want to insert 2 tables columns ids to another table
I got the query but there is the annoying error.
I tried to solve this problem for hours none worked :(
This code:
$query = "INSERT INTO
groups(
group_school_id,
group_teacher_id,
group_name,
group_note,
group_system,
group_students_count
)
VALUES(
$group_shcool_id,
$group_teacher_id,
'$group_name',
'$group_note',
'$group_system',
'$group_students_count'
)";
this old:
<?php
$db['db_host'] = "localhost";
$db['db_user'] = "admin";
$db['db_pass'] = "1998";
$db['db_name'] = "ahlquran";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
mysqli_query($con, "SET NAMES 'utf8'");
}
?>
this new:
<?php
// if you are using php just don't forget to add php tags though
$db['db_host'] = "localhost";
$db['db_user'] = "admin";
$db['db_pass'] = "1998";
$db['db_name'] = "ahlquran";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
//using try catch statements
try{
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully Connected";
}
catch(PDOException $e){
echo "Connection Failed" .$e->getMessage();
}
?>
its connects successfully but all my code use the old one, how to change to convert it? I dont know what pdo I like to learn it, it seems more pro type, but is there solution for this site only using mysqli?
sorry for the long post this is my 1st one, dont know how to explain enough
Thanks
give this error :
QUERY 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 ' , 'test', '', 'test' at line 11
I thought it will work fine like this but I think the problem with the query syntax.
Just an advice try to use PDO prepared statements example below:
$query = "INSERT INTO groups(group_school_id,
group_teacher_id,
group_name,
group_note,
group_system,
group_students_count)
VALUES (:gsid,:gtid,:gname,:gnote,:gsystem,:gstudcount)";
//assuming $conn is your object variable name for database connection
$stmnt = $conn->prepare($query);
$stmnt->execute(array(':gsid'=>$group_school_id,
':gtid'=>$group_teacher_id,
':gname'=>$group_name,
':gnote'=>$group_note,
':gsystem'=>$group_system,
':gstudcount'=>$group_students_count));
//to check if you have inserted data into your table
$rows = $stmnt->rowCount();
echo "Inserted ".$rows." row";
the :gsid are placeholders for your variables, also make sure that each variable passed are inline with column datatypes in your database
//if you are using php just don't forget to add php tags though
$dbhost = "localhost";
$dbname = "whatevername";
$dbuser = "root";
$dbpass = "";
//using try catch statements
try{
$conn = new PDO('mysql:host='.$dbhost.';dbname='.$dbname, $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully Connected";
}
catch(PDOException $e){
echo "Connection Failed" .$e->getMessage();
}

Handling MySql 'Too many connections' error on shared hosting

I have a website that uses a MySql database for storing user info for signing in, and also my data. This site is hosted on a shared hosting server. The problem I'm running into is that I'm occasionally getting a SQL too many connections error. My max connections is set at the default 151.
I am using php for all my server side scripts, and using mysqli pdo connections.
Here is some sample code to show how I handle sql connections from my php scripts. I removed anything that wasn't relevant to the issue, such as input filtering, and character escaping.
<?php
require("common.php");
//get POST data
//My database query
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
//set params for prepared statements
$query_params = array(
':username' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
$miscErr = "Something failed, please try again.";
}
$row = $stmt->fetch();
//do my password hashing, and checking, and sign in user using data in $row
}
?>
Here is my common.php where the error is thrown. I'm not sure what the correct way is to handle it, as i would like the code to try several times before failing.
<?php
$username = "username";
$password = "**************";
$host = "localhost";
$dbname = "mydbname";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$miscErr = "";
try {
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex) {
$miscErr = "Something failed, please try again";
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
I know this has been a while, but here is the solution that I came up with. Since there is no way for me to prevent the errors, i simply handle them with the following code in my common.php file.
$db = ""; // db object
$er = ""; // error object
/*setdb() is the function that actually gets and starts the db connection.
It returns either the db object, or false. The loop will try up to 5 times
to connect with .1 second breaks in between. if that fails then it logs an
error, and the page fails to load. This has not happened in over 5 months on
a live site.*/
for ($i = 0; $i = 5; $i++) { // short loop
if (setdb() !== false) {
$db = setdb(); // if successful breaks
break;
} else {
if ($i = 5) { // after 5 trys, logs error.
file_put_contents('sqlerror.er', $er . "\r\n", FILE_APPEND);
}
}
usleep(100000); // .1second sleep
}
function setdb(){
$username = "my-username";
$password = "***************";
$host = "localhost";
$dbname = "my_database";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$miscErr = "[1040] Too many connections";
try { // try to make connection
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex) {
$er = $ex;
$pos = strpos($ex, $miscErr);
if ($pos !== false) {
return false; //return false on error
}
file_put_contents('sqlerror.er', $ex . "\r\n", FILE_APPEND);
}
return $db; // return true
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
session_start();

PHP warning complains that MYSQL_STORE_RESULT will not be supported in newer versions and the code also doesn't execute properly/at all

I'm struggling to ascertain the proper way to use sql injection to perform an add query the code in question is as follows:
$affectedRows = 0;
foreach($twoDArray as $oneDArray){
$columns = implode(", ",array_keys($oneDArray));
$escaped_values = array_map('serialize', array_keys($oneDArray));
$values = implode(',',$escaped_values);
$sql = "INSERT INTO `entry_tab`($columns) VALUES ($values)";
mysqli_query($database, $sql,[$resultmode = MYSQL_STORE_RESULT]);
echo "\n done one \n";
$affectedRows += 1;
}
The error I'm getting is as follows:
Warning: Use of undefined constant MYSQL_STORE_RESULT - assumed 'MYSQL_STORE_RESULT' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\main.php on line 60, in other words (mysqli_query($database, $sql,[$resultmode = MYSQL_STORE_RESULT]);)
Use MYSQLI_STORE_RESULT
actually this is default option so you can remove this just use
mysqli_query($database, $sql);
OR
mysqli_query($database, $sql, MYSQLI_STORE_RESULT);
Its probably best to use a pdo database connection.
Similar to this
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$sql = "INSERT INTO `entry_tab ($columns) VALUES ($values)";
$conn->exec($sql);
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

MySQL and PHP gives me null var

I make a random quote app, in which by pressing a button, i can load one random phrase. I created for this a MySQL database, and two php code.
I upload my two code in a web hosting, and the app is running!
But sometime it gives me "null" instead of the phrase. I don't know why.
I'm not very good with this.
What is probably the problem?
This is my index.php
require_once 'db.php';
$query = "SELECT * FROM quotes ORDER BY rand() LIMIT 1";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result)) {
print(json_encode($row['quote']));
}
And this is my db.php
// Create connection
$con=mysqli_connect("host","user","pass","a6361246_phrases");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
You can use the first three lines in your db.php file like this...
<?php
$host = 'localhost'; $db = 'database-name'; $user = 'database-user'; $pw = 'database-password';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
Don't forget to change database-name, database-user & database-password to your specific credentials.
Then using PDO get your phrase like this...
<?php
require_once 'db.php';
try {
$sql = "SELECT * FROM Quotes ORDER BY rand() LIMIT 1";
$query = $conn->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Could not get the data: " . $e->getMessage());
}
?>

Categories