php inserting into a MySQL data field - php

I am not sure what I am doing wrong, can anybody tell me?
I have one variable - $tally5 - that I want to insert into database jdixon_WC14 table called PREDICTIONS - the field is called TOTAL_POINTS (int 11 with 0 as the default)
Here is the code I am using. I have made sure that the variable $tally5 is being calculated correctly, but the database won't update. I got the following from an online tutorial after trying one that used mysqli, but that left me a scary error I didn't understand at all :)
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
$sql = "INSERT INTO PREDICTIONS ".
"(TOTAL_POINTS) ".
"VALUES('$points', NOW())";
mysql_select_db('jdixon_WC14');
I amended it to suit my variable name, but I am sure I have really botched this up!
help! :)

I think you just need to learn more about PHP and its relation with MYSQL. I will share a simple example of insertion into a mysql database.
<?php
$con=mysqli_connect("localhost","peter","abc123","my_db");
// Check for errors in connection to database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin',35)";
mysqli_query($con, $query);
mysqli_close($con); //Close connection
?>
First, you need to connect to the database with the mysqli_connect function. Then you can do the query and close the connection

Briefly,
For every PHP function you use, look it up here first.
(You will learn that it is better to go with mysqli).
http://www.php.net/manual/en/ <---use the search feature
Try working on the SQL statement first. If you have the INSERT process down, proceed.
You need to use mysql_connect() before using mysql_select_db()
Once you have a connection and have selected a database, now you my run a query
with mysql_query()
When you get more advanced, you'll learn how to integrate error checking and response into the connection, database selection, and query routines. Convert to mysqli or other solutions that are not going to be deprecated soon (it is all in the PHP manual). Good luck!

if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
mysql_select_db('jdixon_WC14');
$sql = "INSERT INTO PREDICTIONS (TOTAL_POINTS,DATE) ". //write your date field name instead "DATE"
"VALUES('$points', NOW())";
mysql_query($sql);

Related

What is wrong with my PHP/SQL registration script?

I'm trying to make my first registration script using PHP/SQL. Part of my code isn't working:
if(!$errors){
$query = "INSERT INTO users (email, password) VALUES ($registerEmail, $registerPassword)";
if(mysqli_query($dbSelected, $query)){
$success['register'] = 'Successfully registered.';
}else{
$errors['register'] = 'Registration did not succeed.';
}
}
When I test my code I get the error 'Registration did not succeed.' For reference, $errors and $success are arrays. Is there anything wrong with this part of my script?
$dbSelected is:
$dbLink = mysqli_connect('localhost', 'root', 'PASSWORD');
if (!$dbLink) {
die('Can\'t connect to the database: ' . \mysqli_error());
}
$dbSelected = mysqli_select_db($dbLink, 'devDatabase');
if (!$dbSelected) {
die('Connected database, but cannot select
devDatabase: ' . \mysqli_error());
}
I'm sure I am connecting and selecting the database.
Any help would be greatly appreciated! I am very new to PHP/SQL so forgive me for any noob mistakes.
Quote the string like below
$query = "INSERT INTO users (email, password) VALUES ('$registerEmail', '$registerPassword')";
You can also do
echo $query;
and take the output on the browser, copy and paste into PHPMyAdmin and execute it from there. It should tell you what is wrong with the query.
I suggest you to use prepared statement as using string concatenation in SQL Statement is prone to SQL injection attack. Refer the example PHP mysqli prepare
First off, PHP is deprecating mysql_ functions, you should migrate to PDO instead.
Also, make sure since you're using the older mysql_ functions to sanitize your entries using mysql_real_escape_string
Also, your entries need to be quoted. Here's a redo of your query string:
$query = "INSERT INTO users (email, password) VALUES ('{$registerEmail}', '{$registerPassword}')";

Write to MYSQL table not working

I am trying to write to a MySQL Database / Table with the following code - but for some reason it just won't write! I've changed the "INSERT INTO" line quite a few times, trying different things each time - no luck!!!
The DBsettings.php contains variables with the MySQL connection info - which worked for creating the tables and setting the column types and stuff. For your information, it is running the main code (there are no errors with the user info entered), and echoing "Awesome! No errors!", so I'm not too sure what's not working - the MySQL checking line is saying that I'm able to connect properly... Can someone look over my code?
The PasswordHash.php file contains code for hashing and salting passwords - nothing to see here, got it from another site, no errors at all.
I know I'm not 'cleansing' the MySQL code for more security...
if($error == null){
include('DBsettings.php');
$connect = mysqli_connect($dbserver, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
echo 'Failed to connect to MySQL Database! Error: '.mysqli_connect_error();
} else {
include('PasswordHash.php');
$passinfo = explode(':', create_hash($password));
$addinfo = "INSERT INTO {$dbprefix}Users (Email, Displayname, Registered, Rank, Status, Password, Salt) VALUES ('{$email}', '{$displayname}', '{date('Y\/m\/d')}', 9999, 1, '{$passinfo[3]}', '{$passinfo[2]}')";
/* format: algorithm:iterations:salt:hash */
mysqli_query($connect, $addinfo);
mysqli_close($connect);
echo 'Salt: '.$passinfo[2];
echo '<br>Hash: '.$passinfo[3];
echo '<br>Awesome! No Errors!';
}
} else {
echo $error;
}
That's the code in question - I've tried adding;
error_reporting(E_ALL);
ini_set('display_errors', '1');
But all that reveals is undefined localhost errors in my DBsettings.php file - and the file worked when I created the MySQL DB tables, so I don't really have that as a priority.
Thanks!
If you echo your query, you will notice this issue. Following is your final query
INSERT INTO Users (Email, Displayname, Registered, Rank,Status, Password, Salt)
VALUES ('', '', '{date('Y\/m\/d')}', 9999, 1, '', '')
Notice that your date was not interpolated like you expected it to, and i'm sure if you have that field in MySQL set as a datetime field, it wont accept that value {date('Y\/m\/d')}, Move the date function call outside the string.
Plus you are not getting any error after the query execution because you are simply not checking for one. One example how to check for that can be
if (!mysqli_query($connect, $addinfo)) {
printf("Error: %s\n", mysqli_error($connect));
}
I saw your INSERT query contains this '{date('Y/m/d')}' ,maybe the single quotes has conflict,You'd better escaping the date('Y/m/d') statement's single quotes.

mysqli migration issue and security advices

I tried to migrate from mysql to mysqli but this code doesn't work. I'm new to php and mysql
$link = mysqli_connect("localhost", "user", "password", "db");
/* check connection */
if (mysqli_connect_errno()) { printf("Connect failed: %s\n",
mysqli_connect_error()); exit(); }
if ($result = mysqli_query($link, "SELECT * FROM users WHERE uid='$uid'")) {
if(mysqli_num_rows($result) != 0) {
mysqli_query($link, "UPDATE users SET array='$array' WHERE uid='$uid'");
}
else {mysqli_query($link, "INSERT INTO users (uid,array) VALUES ('$uid','$array')"); }
mysqli_free_result($result); }
/* close connection */
mysqli_close($link);
?>
So my questions are:
what should be changed to make this code work;
what security vulnerabilities does this code have and what changes in the code would you suggest to fix that?
Thanks for spending time to answer my questions.
You need to set error reporting to maximum level and make error messages available. this way you will let PHP to tell you what is going wrong and what needs to be fixed.
however, sometimes our code still doesn't work yet there are no error messages around. it's time to do some debugging
You have to change this code to make every variable to go into query via placeholder only
however, raw mysqli is extremely bad with prepared statements, so, I would recommend not to use it but rather move toward PDO or safeMysql. A latter one will let you to have safe queries with the same amount of code.
if ($db->getOne("SELECT 1 FROM users WHERE uid=?i",$uid))
{
$db->query("UPDATE users SET array=?s WHERE uid=?i",$array,$uid);
} else {
$db->query("INSERT INTO users (uid,array) VALUES (?i,?s)",$uid,$array);
}
By the way, Mysql lets you to make all these three queries in one:
$sql = "INSERT INTO users (uid, array) VALUES (?i,?s)
ON DUPLICATE KEY UPDATE array=values(array)";
$db->query($sql, $uid, $array);

Basic MySQL help? - submitting data

I've been getting better at PHP - but I have NO idea what I'm doing when it comes to MySQL.
I have a code
<IMG>
I need to grab the "for", "affi" and "reff" and input them into a database
//Start the DB Call
$mysqli = mysqli_init();
//Log in to the DB
if (!$mysqli) {
die('mysqli_init failed');
}
if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!$mysqli->real_connect('localhost', 'USERNAME', 'PASSWORD', 'DATABASE')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
That's what I'm using to create a connection. It works. I've also got a table created, call it "table", with rows for "for", "affi", and "reff".
So my question is... someone gets directed to http://www.example.com/test.php?for=abcde&affi=12345&reff=foo
Now that I've got a DB connection open - how do I SEND that data to the DB before redirecting them to their destination site? They click - pass across this page - get redirected to destination.
BONUS KARMA - I also need a separate PHP file that I can create that PULLS from that data base. If you could point me at some instructions or show me a simple "how to pull this rows values from this table" I would be greatly appreciative :)
If I understand correctly, you'll want to use $_GET to get the URL parameters.
Then you want to run an insert query on the db with the values you got, which should be something like:
INSERT INTO table VALUES(x, y, z)
Then you need to change the page using a location header.
For the bonus question you just need the code you have now with a select query like:
SELECT * FROM table WHERE 1;
and then fetch the query results.
If this does not answer your questions please provide some clarifications.
Mysqli is the deprecated function and now PDO is recommended to connect to database. You could do following.
<?php
$conn = new PDO('dblib:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
?>
Read more here.

PHP SQL Truncate

I'm having a problem trying to truncate the 'requestID' field from my requests table.
This is my code.
<?php
include 'mysql_connect.php';
USE fypmysqldb;
TRUNCATE TABLE requestID;
echo "Request ID table has been truncated";
?>
I'm using server side scripting so no idea what error is coming back.
Anyone got an idea?
You aren't executing queries, you're just putting SQL code inside PHP which is invalid. This assumes you are using the mysql_*() api (which I kind of suspect after viewing one of your earlier questions), but can be adjusted if you are using MySQLi or PDO.
// Assuming a successful connection was made in this inclusion:
include 'mysql_connect.php';
// Select the database
mysql_select_db('fypmysqldb');
// Execute the query.
$result = mysql_query('TRUNCATE TABLE requestID');
if ($result) {
echo "Request ID table has been truncated";
}
else echo "Something went wrong: " . mysql_error();
Take a look at the function mysql_query which performs the query execution. The code to execute a query should look something like this.
$link = mysql_connect('host', 'username', 'password') or die(mysql_error());
mysql_select_db("fypmysqldb", $link) or die(mysql_error());
mysql_query("TRUNCATE TABLE requestID", $link) or die(mysql_error());
mysql_close($link);

Categories