I am trying to get the reputation of a union (everyone who is in the unions reputation added)
$the_member = mysql_query("SELECT `reputation` FROM `stats` WHERE `id` in (SELECT `id` FROM `user` WHERE `union`='".$id."')") or die(mysql_error());
Thats what I have So far and if you echo it its just blank, no errors and no text.
If you read the PHP doc for mysql_query, you'll see an example that shows you how to use it. Basically you need to use mysql_fetch_assoc (or some similar function) to get the actual data, like this:
while ($row = mysql_fetch_assoc($the_member)) {
echo $row['reputation'];
}
Warning: try not to use mysql_query, it's deprecated. Use mysqli_query, or better yet, PDO. It's all in the link above. Also, you need to make sure the $id value doesn't contain anything that would break your query. This is called "SQL injection", and in certain cases it lets anyone run an arbitrary query. Consider the case when $id == "'); drop table user; --"
Related
I am trying to use PHP to run consecutive MYSQL statements as shown in the code snippet below (which just copies one row to another and renames the id via a tmp table).
I am getting a repeated syntax error message. I've tried numerous iterations. And the code looks like code I've researched in the PHP Manual and other myql questions on SO (which do not include the php dimension).
Can anyone shine a light on why my php syntax is incorrect?
include("databaseconnect.php");// This obviously works. Used a zillion time
$sql ="CREATE TEMPORARY TABLE tmp SELECT * FROM event_categoriesBU WHERE id
= 1;";
$sql.="UPDATE tmp SET id=100 WHERE id = 1;";
$sql.="INSERT INTO event_categoriesBU SELECT * FROM tmp WHERE id = 100;";
if ($conn->query($sql) === TRUE)
{
echo "Table row copied successfully. Do something with it";
}
else
{
echo "Error creating table: " . $conn->error;
//close connection etc
}
PHP Message back:
Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE tmp SET id=100 WHERE id = 1INSERT INTO event_categoriesBU SELECT * FROM t' at line 1
Don't run a bunch of queries at once. Usually the success of one depends on all the other operations having been performed correctly, so you can't just bulldozer along as if nothing's gone wrong when there's a problem.
You can do it like this:
$queries = [
"CREATE TEMPORARY TABLE tmp SELECT * FROM event_categoriesBU WHERE id = 1",
"UPDATE tmp SET id=100 WHERE id = 1",
"INSERT INTO event_categoriesBU SELECT * FROM tmp WHERE id = 100"
];
foreach ($query as $query) {
$stmt = $conn->prepare($query);
$stmt->execute();
}
Don't forget to enable exceptions so that any query failures will stop your process instead of the thing running out of control.
The reason you don't use multi_query is because that function does not support placeholder values. Should you need to introduce user data of some kind in this query you need to use bind_param in order to do it safely. Without placeholder values you're exposed to SQL injection bugs, and a single one of those is enough to make your entire application vulnerable.
It's worth noting that PDO is a lot more flexible and adaptable than mysqli so if you're not too heavily invested in mysqli, it's worth considering a switch.
You can't execute more than one SQL statement with query($sql), you must use multi_query($sql). Your script will then become something like this:
if ($conn->multi_query($sql) === TRUE)
{
echo "Table row copied successfully. Do something with it";
}
See the documentation for a complete example.
However, note that, as other users have well explained in the comments, executing multiple queries at the same time with this method can be potentially dangerous and should be avoided when possible, especially when handling user inputs.
You have better control of the execution flow if you execute one query at a time and check its result, rather than grouping all of them in a single call.
I am trying to use PHP to run consecutive MYSQL statements as shown in the code snippet below (which just copies one row to another and renames the id via a tmp table).
I am getting a repeated syntax error message. I've tried numerous iterations. And the code looks like code I've researched in the PHP Manual and other myql questions on SO (which do not include the php dimension).
Can anyone shine a light on why my php syntax is incorrect?
include("databaseconnect.php");// This obviously works. Used a zillion time
$sql ="CREATE TEMPORARY TABLE tmp SELECT * FROM event_categoriesBU WHERE id
= 1;";
$sql.="UPDATE tmp SET id=100 WHERE id = 1;";
$sql.="INSERT INTO event_categoriesBU SELECT * FROM tmp WHERE id = 100;";
if ($conn->query($sql) === TRUE)
{
echo "Table row copied successfully. Do something with it";
}
else
{
echo "Error creating table: " . $conn->error;
//close connection etc
}
PHP Message back:
Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE tmp SET id=100 WHERE id = 1INSERT INTO event_categoriesBU SELECT * FROM t' at line 1
Don't run a bunch of queries at once. Usually the success of one depends on all the other operations having been performed correctly, so you can't just bulldozer along as if nothing's gone wrong when there's a problem.
You can do it like this:
$queries = [
"CREATE TEMPORARY TABLE tmp SELECT * FROM event_categoriesBU WHERE id = 1",
"UPDATE tmp SET id=100 WHERE id = 1",
"INSERT INTO event_categoriesBU SELECT * FROM tmp WHERE id = 100"
];
foreach ($query as $query) {
$stmt = $conn->prepare($query);
$stmt->execute();
}
Don't forget to enable exceptions so that any query failures will stop your process instead of the thing running out of control.
The reason you don't use multi_query is because that function does not support placeholder values. Should you need to introduce user data of some kind in this query you need to use bind_param in order to do it safely. Without placeholder values you're exposed to SQL injection bugs, and a single one of those is enough to make your entire application vulnerable.
It's worth noting that PDO is a lot more flexible and adaptable than mysqli so if you're not too heavily invested in mysqli, it's worth considering a switch.
You can't execute more than one SQL statement with query($sql), you must use multi_query($sql). Your script will then become something like this:
if ($conn->multi_query($sql) === TRUE)
{
echo "Table row copied successfully. Do something with it";
}
See the documentation for a complete example.
However, note that, as other users have well explained in the comments, executing multiple queries at the same time with this method can be potentially dangerous and should be avoided when possible, especially when handling user inputs.
You have better control of the execution flow if you execute one query at a time and check its result, rather than grouping all of them in a single call.
so I have a mysql query that looks like this.
$copy = mysql_query("SELECT `id` FROM `brain` WHERE `id` = '$user_screen_name' && '$posts['title']'");
I want the query to search for the id that is in the table where screen name and post title strings are matched and put the found id in a variable. How would I do this?
First, some warnings:
Please stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
Little Bobby says your script is at risk for SQL Injection Attacks.. Even escaping the string is not safe!
To fix your query you need a separate AND condition for each item you want to filter against:
WHERE `id` = '$user_screen_name'
AND `title` = '$posts["title"]'
Without seeing your table layout it would be hard to go much further but if you want the id in a variable you would do this after the query:
$row = mysql_fetch_array($copy);
Once done, $row['id'] will be the variable containing the id.
I'm experiencing a strange problem with save query, and I'd like to better understand how to solve it.
I have a database with 2 tables, example:
TBL_PERSON
person_id
person_name
person_telephone
TBL_ADDRESS
address_id
address_person_id
address_address
address_city
address_zip
Now, I use a query like this to store records:
$sqlQuery = "INSERT INTO TBL_PERSON (
person_name,
person_telephone
) VALUES (
'$person_name',
'$person_telephone'
)";
$result = MYSQL_QUERY($sqlQuery);
//Get last id
$address_person_id = mysql_insert_id();
$sqlQuery = "INSERT INTO TBL_ADDRESS (
address_person_id,
address_address,
address_city,
address_zip
) VALUES (
'$address_person_id',
'$address_address',
'$address_city',
'$address_zip'
)";
$result = MYSQL_QUERY($sqlQuery);
Sometimes, no record is added on TBL_ADDRESS.
After the user presses Insert, Action Button, Name and Telephone are stored on TBL_PERSON, but not address on TBL_ADDRESS.
Barring the discussion on the use of deprecated an insecure mysql_* functions, I think this is a good opportunity to explain methods of debugging issues like this.
In the replacements for the mysql_* query functions, exceptions are thrown on errors allowing you to wrap the query in a try/catch block and handle it accordingly. In the case of mysql_query(), you will simply get false returned from the function. So to be able to debug and consequently see what is wrong, you need to do something like this (from the PHP manual):
$result = mysql_query('SELECT * FROM myTable');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
If your query fails, you will see why, which is important in debugging.
As mentioned in the comments, you do not escape any of your values. Aside from the fact that you shouldn't be using these functions at all (see mysqli or PDO), you should at minimum be escaping your values using the mysql_real_escape_string() method:
$value = mysql_real_escape_string($value);
If you follow the above logic, you will see what is causing the issue, and I suspect fix it successfully using proper escaping of values. If it's not the value, you may have an issue with your database schema design such as a column that is not nullable and has no default value, yet you may be passing a null value.
Why does this PHP code (mysql_query to delete a row where user name is $phpVar) do nothing?
mysql_query("DELETE FROM xraydeath WHERE user = $user");
Probably because you forgot to quote the $user parameter also, please escape variables goes into sql query strings. If that parameter is connected directly to user input someone might submit ' or 1=1 -- and your whole table gone. This idea know as sql injection.
note: the old mysql_* functions are now deprecated, you should avoid using them, see the alternatives.
You need to put quotes around strings like this:
mysql_query("DELETE FROM xraydeath WHERE user = '$user'");
you forgot the quotes around the user:
mysql_query("DELETE FROM xraydeath WHERE user = '$user'");
What are you expecting? How it fails? Mysql_query is not suppose to do anything in the form that you are using it, except sending the query to the server.
$result = mysql_query (...);
// use the result if any.
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// check the error that you might have
you need to put $user into quotes
mysql_query("DELETE FROM xraydeath WHERE user = '".$user."';");
also DELETE will succeed if even no rows where deleted, so to get how many rows where actually deleted use mysql_affected_rows()
$x = mysql_query("..");
echo "There were ".mysql_affected_rows()." rows affected";
**Try not to use mysql_* switch to PDO instead.
Assuming xraydeath.user is a character type, the value needs to be enclosed in quotes. If $user does not already contain the quotes, try:
mysql_query("DELETE FROM xraydeath WHERE user = '$user'");
And for kicks, try setting $user = "' OR '1'='1";! (Read up on SQL injection attacks and you should really switch to mysqli!)
It's also possible the table does not have a matching row, and therefore nothing will be deleted. Without knowing what you have assigned to $user and your data there is no way to know.
try this one:
mysql_query("DELETE FROM xraydeath WHERE user = '".$user."'");
or
mysql_query("DELETE FROM xraydeath WHERE user = '".$user."';");
every php variables that used in mysql, put them into '".$variable."'
First : mysql is deprecated. you should use mysqli.
Second : What kind of type is user?
if is int :
(object oriented style)
mysqli::query("DELETE (what you want) FROM xraydeath WHERE `user` = '".$user."'");
if is varchar (string) :
mysqli::query("DELETE (what you want) FROM xraydeath WHERE `user` LIKE '".$user."'");
or
(procedurel syle)
mysqli_query((your mysqli link), "DELETE (what you want) FROM xraydeath WHERE `user` LIKE/= '".$user."'");
Hope it helps