Why can't I INSERT INTO? - php

So this might be dumb, but I can't get anything to insert into a MySQL on a certain account, and I've been staring at this for two hours. I'm a newbie to PHP, so I could very well be doing something dumb. I attached a screen shot of the DB I am trying to INSERT INTO.
Here is what I'm talking about:
(imgur seems to be down for me)
Here's the code I have, and PhpMyAdmin told me GRANT ALL PRIVILEGES ON . TO ...
$fbFirstName = $me['first_name'];
$fbLastName = $me['last_name'];
$fbEmail = $me['email'];
mysql_real_escape_string($fbFirstName,$fbLastName,$fbEmail);
$getuserresult = mysql_query("SELECT * FROM newusers WHERE fbUID=$uid");
$userrowsreturned=mysql_num_rows($getuserresult);
if ($userrowsreturned=0)
{
echo '<br />user already exists, will update something here eventually<br />';
}
else {
$sql = mysql_query("INSERT INTO newusers (fbUID,callsAttempted,callsMade,fbEmail,fbFirstName,fbLastName) VALUES ($uid,'1','0',$fbEmail,$fbFirstName,$fbLastName)");
if(!$sql) {
die("Nope");
} else {
echo "1 record added";
}
echo '<br />created user<br />';
}

Two things go wrong here. Escaping goes like:
$fbFirstName = mysql_real_escape_string($fbFirstName);
// for all variables
// or, just in one go:
$fbFirstName = mysql_real_escape_string($me['first_name']);
// and for integers, make sure they are actually integers (and prevent mayhem)
$some_id = (int)$me['some_id'];
$uid = (int)$uid;
And when inserting you must quote non-integer values:
$sql = mysql_query("INSERT INTO `newusers`
(`fbUID`,`callsAttempted`,`callsMade`,`fbEmail`,`fbFirstName`,`fbLastName`)
VALUES
('$uid',1,0,'$fbEmail','$fbFirstName',$fbLastName')");
(but you may quote integers as well - you never know if some external id is, or may become, alphanumeric.)

You have an error
if ($userrowsreturned=0)
should be (use double equals to test equivalence, single equals for assignment)
if ($userrowsreturned==0)
I also think you actually mean the following since you're checking if a user already exists
if ($userrowsreturned==1)

first of all you must change
$getuserresult = mysql_query("SELECT * FROM newusers WHERE fbUID=$uid");
to
$getuserresult = mysql_query("SELECT * FROM newusers WHERE fbUID='$uid'");
after that change your insert to:
$sql = mysql_query("INSERT INTO newusers (fbUID,callsAttempted,callsMade,fbEmail,fbFirstName,fbLastName) VALUES
('$uid','1','0','$fbEmail','$fbFirstName',$fbLastName')");

Related

INSERT INTO statement won't insert a specific value correctly?

I am trying to use the INSERT INTO SQL statement in php. It will input everything correctly up until the last value ($bands_bio). Instead of putting in the correct information, it leaves the value blank. I have looked over everything and can't seem to find any sort of syntax errors.
$page_title = "Create a new band";
require ('includes/database.php');
require_once 'includes/bandsHeader.php';
$band_name = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_name', FILTER_SANITIZE_STRING)));
$band_photo = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_photo', FILTER_SANITIZE_STRING)));
$genre = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'genre', FILTER_SANITIZE_STRING)));
$band_bio = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_bio', FILTER_SANITIZE_STRING)));
echo $band_bio;
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = "")) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/searchFooter.php';
exit;
}
$albums = 0;
$sql = "INSERT INTO bands VALUES (NULL, '$band_name', '$genre', '$albums', '$band_bio')";
$query = #$conn->query($sql);
if (!$query) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/footer.php';
exit;
}
As you can see, I echoed out $band_bio in order to see if it was getting the right value from my form that uses the GET method, which it is so that's not the issue. It has no problem inserting everything correctly up until the last value, which is supposed to be the last column called band_bio in my bands table in my database. It will not output any errors or anything, either. It's almost as if it's taking the string data from the variable and removing all of the text before it inserts the information.
I have been working on this website for a few weeks now and have used the INSERT INTO statement the exact same way on other pages and it works just fine. This is the first thing that has really stumped me and I can't figure it out. Any help is appreciated.
When inserting, ensure that your pk (id) field is set to auto-increment.
This way, you can exert more control over your queries. You should be more successful with:
$sql = "INSERT INTO bands "
. "(`band_name`,`genre`,`numof_albums`,`band_bio`) "
. "VALUES ('$band_name', '$genre', '$albums', '$band_bio')";
By not specifying the pk field, INNODB will automatically increment and insert it for you.
The idea is that you want to specify which columns are being inserted into. Relying on column ordering by mysql is fine, but there may be something at play in your case.
There should be no reason why band_bio would be "left off". You would get a column-mismatch error.
Totally found the answer myself! It, in fact, was a syntax error.
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = ""))
The variable $band_bio was being assigned to a blank string in the if statement since I accidentally used an assignment operator rather than a comparison operator. So the correct code would need to be $band_bio === "" rather than $band_bio = "".
I swear, the problem is always something so much simpler than you think it's going to be.

SQL/PHP "WHERE" not returning correct value?

The code will display the returned values and and if it is greater than one it will return "Yes". But I am having trouble with the WHERE clause in $check. When I take it out the code works just fine but when I add it, the page returns incorrect values. Any ideas what's wrong?
<?php
$con = mysqli_connect("127.0.0.1","root","","lian");
$u= $_GET['username'];
$pw = $_GET['password'];
$check = "SELECT username,password FROM users WHERE username='$u' AND password='$pw'";
$login = mysqli_query($con,$check) or die(mysqli_error($con));
$num_rows = mysqli_num_rows($login);
echo "$num_rows \n";
if (mysqli_num_rows($login) == 1) {
$row = mysqli_fetch_assoc($login);
echo 'Yes';
exit;
}
else {
echo 'No';
exit;
}
Leaving aside the injection vulnerabilities, it may be because of special characters or whitespace. Try trim'ing your GET values.
$u = trim($_GET['username']);
$pwd = trim($_GET['password']);
Are you getting the number of results as 0? Also try echoing the statement in a development environment to check exactly what the statement is.
Try like this
$u= trim(mysqli_real_escape_string($_GET['username']));
$pw = trim(mysqli_real_escape_string($_GET['password']));
$check = "SELECT username,password FROM users WHERE username='$u' AND password='$pw'";
Also I hope you are ensuring unique combination of username and password.
Because suppose there are two entries in your users table
username="abc" password ="12345"
Then mysqli_num_rows() function will return two rows and the
if (mysqli_num_rows($login) == 1)
condition will return false meaning the user desn't exist.
The above comments are valid to improve the security of your code and protect vs sql injection.
Regarding your actual problem if the code executes correctly when you don't have the where clause in place but fails when you do there are a couple of possibilities:
The username or password are wrong - where wrong can mean they have extra whitespace, case insensitivities or that the column names are incorrect(case sensitive database?)
The string you are passing to the server is not displaying correctly.
Check both options by doing an echo of $u, $pw and $check right after you form your SQL string. If it's still not clear then copy whatever is echoed for $check and past it directly into the parser(management studio I guess?) and see what it returns.
Good Luck.

PHP If Statements With mySQL Results

The code below is supposed to check if there is a person in the database with a row in the database with the username it gets from the cookie login.And if there is it is supposed to include a page and if there isn't a person in the database with this user_id it is supposed to echo.Here is my code so far please tell me how I would do this.I also already know before someone tells me that mySQL statements like I have it are becoming depreciated.Here is My code:
<?php
include("dbconnect.php");
mysql_select_db("maxgee_close2");
$username = $_COOKIE['maxgee_me_user'];
$result = mysql_query("select user_id from users where username = '$username'");
$row = mysql_fetch_array($result);
mysql_free_result($result);
$check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row['user_id']'") or die(mysql_error());
if(1==1){
if (mysql_num_rows($check)>0)
{
include("example.php");
}
else
{
echo "example";
}
}
?>
In the double-quoted string, your array variable $row['user_id'] is being incorrectly parsed due to the fact that you have quoted the array key without surrounding the whole thing in {}. It is permissible to omit the {} in a double-quoted string if you don't quote the array key, but the {} adds readability.
check = mysql_query("SELECT * FROM events_main WHERE user_id ='{$row['user_id']}'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
// Also acceptable, but not as tidy, and troublesome with multidimensional
// or variable keys - unquoted array key
check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row[user_id]'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
As mentioned above, $_COOKIE is never considered a safe value. You must escape its values against SQL injection if you continue to use the old mysql_*() API:
$username = mysql_real_escape_string($_COOKIE['maxgee_me_user']);
2 Things right off the bat, like Waleed said you're open to SQL injection, not very nice thing to have happen to you. I would look into reading tutorials about MySQLi and PDOs, from there try and dive into a better way or running queries.
Also you are choosing to use cookies instead of sessions to store the username? Cookies can be modified client-side to say anything a smart user with firebug would want them to be. Sessions are stored server-side and the client (end-user) is only given an id of the session. They cannot modify the username if you send it as a session. (They could try and change the session id to another random bunch of numbers but thats like pissing into the wind, pardon my french.
Heres some pseduo code that will get you on your way I think
<?php
include("dbconnect.php");
$database = "maxgee_close2"; //Set the database you want to connect to
mysql_select_db($database); //Select database
$username = $_SESSION['maxgee_me_user']; //Grab the username from a server-side stored session, not a cookie!
$query = "SELECT user_id FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "' LIMIT 1"; //Note the user of mysql_real_escape_string on the $username, we want to clean the variable of anything that could harm the database.
$result = mysql_query($query);
if ($row = mysql_fetch_array($result)) {
//Query was ran and returned a result, grab the ID
$userId = $row["user_id"];
mysql_free_result($result); //We can free the result now after we have grabbed everything we need
$query_check = "SELECT * FROM `events_main` WHERE `user_id` = '" . mysql_real_escape_string($userId) . "'";
$check = mysql_query($query_check);
if (mysql_num_rows($check)>0) {
include("example.php");
}
else {
echo "example";
}
}
?>
That code may/may not work but the real key change is that fact that you were running
mysql_free_result($result);
before your script had a chance to grab the user id from the database.
All in all, I would really go back and read some more tutorials.

Can you use $_POST in a WHERE clause

There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.

setting the result of a sql query as a variable inside an if statement in php

Kind of an unclear question but I'm trying to check if a username has been taken or not. The code I have now isn't erroring but it's also not working, when echoing the $username variable I get nothing.
$sql="SELECT people_username FROM people WHERE people_username='{$_POST['username']}'";
//Set the result of the query as $username and if the select fails echo an error message
if ($username = !mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
else if ($_POST['username'] == $username){
$errors[ ] = 'This username is already in use, please try again...sorry';
}
Is it a syntax error or is my logic wrong?
i would just do
$resource = mysql_query("SELECT people_username FROM people WHERE people_username='".mysql_escape_string($_POST['username'])."'");
if(!$resource) {
die('Error: ' . mysql_error());
} else if(mysql_num_rows($resource) > 0) {
$errors[ ] = 'This username is already in use, please try again...sorry';
} else {
//username is not in use... do whatever else you need to do.
}
If some cheeky user happens to try: '; DROP people; -- as a username, you'd be in big trouble.
You may want to check the following Stack Overflow post for further reading on this topic:
What is SQL injection?
As for the other problem, the other answers already addressed valid solutions. However, make sure to fix the SQL injection vulnerability first. It is never too early for this.
Your code is wrong.
It should be something like this:
$sql="SELECT people_username FROM people WHERE people_username='".mysql_escape_string($_POST['username'])."'";
//If the select fails echo an error message
if (!($result = mysql_query($sql,$con))) {
die('Error: ' . mysql_error());
}
$data = mysql_fetch_assoc($result);
if ($data == null){
$errors[ ] = 'This username is already in use, please try again...sorry';
}
Notice that for security reasons you need to escape the strings you use in SQL queries.
mysql_query($sql,$con) returns a resultset (which may be empty)
you are not testing any condition with if($var = !'value'), you are just assigning a negated resultset to the variable $username (what beast that is, I am not sure)
My suggestion: Simplify the code, do not overload lines of code with multiple tasks.
3. List item

Categories