Using a variable as the column name in a mysql query - php

I'm trying to turn this:
"SELECT username FROM $table WHERE username='$newName'"
Into this:
"SELECT $column FROM $table WHERE $column='$newName'"
But when I use or die() on it, I get an error saying that there is incorrect syntax near WHERE username='someNameHere'. What is the correct way to substitute the column name, assuming that's what's wrong?
Edit: Code is just this. The values should be correct as I don't see any mispellings in the error.
$sql = "SELECT $column FROM $table WHERE $column='$newName'";
$result = mysql_query($sql) or die( mysql_error());

Make your query like this
$sql = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$newName."'"
BTW this is SQLinjection vulnerable code. You should check the variables before using them in query. Also you should start using mysqli and prepared statements

"SELECT ".$column." FROM ".$table." WHERE ".$column."=".$newName;
Check to see if that works for you.

Related

PHP syntax error - SELECT WHERE

I am making an error with PHP SELECT WHERE code - which should be simple, but I have made no progress.
The code works with SELECT FROM line, but not with the SELECT FROM WHERE `line.
I have spent a few hours with no luck.
I have tried different syntax combinations with no progress.
$sql = "SELECT * FROM `customer_crm` WHERE `sales_agent` = '$username'";
//$sql = "SELECT * FROM `customer_crm`"; /* this works*/
Assuming that you set a default character encoding, you can use mysqli_real_escape_string to avoid SQL Injections. However, the comment to use a prepared statement is really the best advice here.
However, with mysqli_real_escape_string your SQL should work like that:
$sql = 'SELECT * FROM `customer_crm` WHERE `sales_agent` = "'.mysqli_real_escape_string($link,$username).'"';
You can even try this query
$sql = "SELECT * FROM customer_crm WHERE sales_agent = '".$username."'";

PHP error get value from database

I have php script like this
$query = "select * where userid = 'agusza' ";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)) {
echo $result;
}
when I execute, the result like this
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 'where userid = 'agusza'' at line 1
But when I run that sql in sqlserver, it running well
Anybody has solution ?
$query = "select * from table_name where userid = 'agusza' ";
See the corrections I have made. You haven't used the right syntax for SELECT query
You didn't select a table using FROM. Without that, it does not know which table you are selecting data from.
You should also stop using mysql as it is deprecated. Use mysqli or PDO as they are safer.
You are also echoing the wrong variable in your while loop, try this:
while ($row = mysql_fetch_array($result) {
echo $row['column_name'];
}
$query = "select * from table where userid = 'agusza'";
Right now, you're not telling which table SQL should look in.
You should format your query like so:
select * from `TableName` where userid='agusza'
In your query below you doesnt state the database table where you should get that data using FROM
$query = "select * where userid = 'agusza' "; // instead of this
$query = "select * FROM declaredtable where userid = 'agusza' "; used this

Php update function

I wrote this code
if(isset($_POST['update'])) {
$webname = $_POST['webname'];
$webmeta = $_POST['webmeta'];
$webdesc = $_POST['webdesc'];
$sql=("UPDATE settings (name, meta, description) VALUES ('$webname', '$webmeta', '$webdesc')");
}
but the problem is that it doesn't update my database, and I cannot find anything wrong in the code ...
I have name "update" on submit button, and all my fields are the same as in code
That's insert! Not update!
$sql=("UPDATE `settings` SET `name` = '$webname',
`meta` = '$webmeta',
`description` = '$webdesc')
WHERE [some condition]");
And replace the [some condition] with a valid condition.
Your code is heavily vulnerable to SQL Injection.
Consider escaping the input by replacing these:
$webname = $_POST['webname'];
$webmeta = $_POST['webmeta'];
$webdesc = $_POST['webdesc'];
With:
$webname = mysql_real_escape_string($_POST['webname']);
$webmeta = mysql_real_escape_string($_POST['webmeta']);
$webdesc = mysql_real_escape_string($_POST['webdesc']);
Or something equivalent like PDO or MySQLi.
mysql_select_db("my_db", $con);
mysql_query("UPDATE Persons SET Age=36
WHERE FirstName='Peter' AND LastName='Griffin'");
u need to first formulate query ans then run/ execute that
$query = "UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value";
// Perform Query
$result = mysql_query($query);
You need to run
$connection = mysql_connect($server, $serv_Username, $serv_Password);
mysql_select_db($dbase_name, $connection);
mysql_query($update_query, $connection));
I don't know if this is your problem (don't know how much you know about PHP so just saying).
Also your syntax is wrong. Should be:
UPDATE tablename SET column_name='some_value' WHERE column_name ='some_value'
note that this is diffrent from mentioned above without the thingys covering the column_name parameters.
better is to use PDO as mentioned above, mysql_ can be used "safely" on < PHP 5.5.
Try The code shown below
Just replace the field names and values with your information on your database
$editid=$_POST['editid'];
$username=callback($_POST['username']);
$password=callback($_POST['password']);
$name=callback($_POST['name']);
$age=callback($_POST['age']);
$phone=callback($_POST['phone']);
$emailaddress=callback($_POST['emailaddress']);
$gender=callback($_POST['gender']);
$description=callback($_POST['description']);
$update=update("users","username='".$username."',password='".$password."',name='".$name."',age='".$age."',phone='".$phone."',emailaddress='".$emailaddress."',gender='".$gender."',description='".$description."' ","ID='".$editid."' " );

php query to insert string into database

<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password)
{
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database");
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
$result = mysql_query($query) or die("Error occurred.");
}
else die("Please enter a username and password.");
?>
For this part of the code:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The VALUES seem to not be working properly, I need whatever the string value of $username is to be inserted into my CiniUsers database. What do I need to do to make the code above work? I'm very new to php and sql syntax and the guides I'm finding online are all completely different from each other as if they keep updating php.
Try reviewing this part:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The syntax is:
$query = "INSERT INTO table (column) VALUES ('$strvar')";
What is the column name you wanted to insert into?
If it is username.CINIDAT then try removing the qoutes.
Like this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
or maybe your column is named username so:
$query = "INSERT INTO CiniUsers (username) VALUES ('$username')";
UPDATE
The query from your comment, change it to this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
The format for the SQL statement is as so:
INSERT INTO nameOfTable (column1, column2, column3, etc) VALUES ('column1', 'column2', 'column3', 'etc')
You MUST make sure that you are using the field names exactly as they are stored in MySQL.
Your SQL could appear like so:
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
OR
$query = "INSERT INTO CiniUsers (username) VALUES('{$username}')";
Another thing that may help is that your die() statement is not very helpful. Yes, it is a bummer when your php program quits early, but it will save you a lot of time and frustration if you know why it quit. Although you may still be learning PHP and MySQL and may not know what the errors mean, they will start to make sense the more you see them and can tell you whether your query was bad, the connection failed or many more things. Change to something like this:
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect: mysql_error()");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database: mysql_error()");
...
$result = mysql_query($query) or die("Some kind of error occurred...Query failed: mysql_error()");
You find that seeing the mysql_error() will help you solve problems like this much faster.
USE phpMyAdmin to test your query out, your query may be working perfectly. It is really the only way to know for sure. Use the suggested SQL and replace the PHP variable with some dummy data like "testUsername_1". If the query works, you will have manually added the username to the db, if not, the problem lies in SQL statement.
Here is some documentation on SQL INSERT INTO statements if you need more details:
http://www.w3schools.com/sql/sql_insert.asp
I think you should use mysqli or pdo. This liberary you are using is deprecated.
That said, what is username.CINIDAT? I think this is where your problem is. It should be something like this
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
I am assuming that CiniUsers is the table name and username is the column name.
The simplest way is to build the query by concatenating the statement with the value.
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('".$username."')";
Without validation, this is not a very good idea, or something like this is very easy.

What is the proper syntax for inserting variables into a SELECT statement?

I believe I have a simple syntax problem in my SQL statement. If I run this code, I get an error in the database query.
$user = $_GET['linevar'];
echo $user; // testing - url variable echos correctly
$sql = "SELECT * FROM `userAccounts` WHERE `name` = $user";
$result = mysql_query($sql) or die("Error in db query");
If I replace $user in the $sql string with 'actualName' or a known record in my table, the code works fine. Am I using the $ variable incorrectly in the SQL string?
You need to surround the value that you're getting from $user with quotes, since it's probably not a number:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
Just as a note, you should also read up on SQL injection, since this code is susceptible to it. A fix would be to pass it through mysql_real_escape_string():
$user = mysql_real_escape_string( $_GET['linevar']);
You can also replace your or die(); logic with something a bit more informative to get an error message when something bad happens, like:
or die("Error in db query" . mysql_error());
You need escape the get input, then quote it.
// this is important to prevent sql injection.
$user = mysql_real_escape_string($_GET['linevar']);
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
This should work:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '" . $user . "'";

Categories