MySQL Database Specific Top (Amount) - php

I recently began learning PHP, and I set up a MySQL Server. However, I'm not very familiar with SQL, and I would like to know, how would I get the top amount of results (amount as defined by _GET["Amount"] that all have the same EventType as defined by _GET["EventType"]?
<?php
$con=mysqli_connect(Info removed);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Amount=$_GET["Amount"];
$GetType=$_GET["Type"];
$sql= ""; //How would I do the action outlined above?
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Done";
mysqli_close($con);
?>
I've looked over this site and others, to no avail. All help is greatly appreciated.

Sorry misunderstood your question...
Try this instead: $sql = "SELECT * FROM table WHERE EventType='$GetType' ORDER BY amount_column DESC";
Run the query: $sql_run = mysql_query($sql);
The amount column in your table do have to be INT i think.
To echo out all the amounts you could then say something like:
while($sql_row = mysql_fetch_assoc($sql_run)){
echo $sql_row['amount_column'].'<br>';
}
btw in your code you don't use the mysql_select_db() method, there might be a way around it, but as far as I know you do have to specify a database.

Before writing query you need to prepare the mysql table. If you have one, try to post here your table structure.

Related

what is the correct syntax for this SQL SELECT statement

im making a website and have done a lot of INSERT statements but i also need a SELECTstatements for this, pretty much the customers will be able to type in their custID in order to display their purchases.
So far my sql looks like this:
<?php
$con = mysqli_connect('localhost', 'root', '');
if (!$con) {
echo'Not connected to Server';
}
if (!mysqli_select_db($con, 'horizonphotography')) {
echo'DataBase Not Selected';
}
$custID = $_GET['custID'];
$sql = "SELECT custID FROM `paymentPersonal`, `paymentsPayment`, `paymentsProduct`, `paymentsShipping` WHERE = $custID";
if (!mysqli_query($con, $sql)) {
echo 'Not Inserted';
} else {
echo 'Finding...';
}
header("refresh:1; url=admin.php");
?>
and i know the syntax isnt correct but i dont know what to write so it finds what the customers custID has ordered as it will be different. thankyou
select query will be something like below for selecting particular field
$sql = "SELECT `coloumname1`,`coloumname2` from `tablename` where `someid`='matchingvalue'";
for selecting all the field sql query will be like below
$sql = "SELECT * from `tablename` where `someid`='matchingvalue'";
hope you understand this, so from next time please google first and than come here if not find the answer in google

PHP script to update mySQL database

another day another question...
I need to write PHP script to update mySQL database.
For example: updating profile page when user want to change their first name, last name or etc.
Here is my php script so far, it doesn't work. Please help!
<?php
# $db = new MySQLi('localhost','root','','myDB');
if(mysqli_connect_errno()) {
echo 'Connection to database failed:'.mysqli_connect_error();
exit();
}
if (isset($_GET['id'])) {
$id = $db->real_escape_string($_GET['id']);
$First_Name2 = $_POST['First_Name2'];
$query = "UPDATE people SET $First_Name2 = First_Name WHERE `Id` = '$id'";
$result = $db->query($query);
if(! $result)
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
$db->close();
}
?>
THank you.
Your sql is wrong. Apart from the gaping wide open SQL injection attack vulnerability, you're generating bad sql.
e.g. consider submitting "Fred" as the first name:
$First_Name2 = "Fred";
$query = "UPDATE people SET Fred = First_name WHERE ....";
now you're telling the db to update a field name "Fred" to the value in the "First_Name" field. Your values must be quoted, and reversed:
$query = "UPDATE people SET First_name = '$First_Name2' ...";
You are also mixing the mysqli and mysql DB libraries like a drunk staggering down the street. PHP's db libraries and function/method calls are NOT interchangeable like that.
In short, this code is pure cargo-cult programming.

Cannot find error in my php script. Can someone point it out to me

I have written a php script on my web server to insert values into the table table3. The variables used to get values are username and image. username contains varchar type data and image contains text type data in it. I need to insert it into my table table3 . The table3 is having two columns username and imagename which is of varchar type and text type respectively.
When I try to run the above script by entering values, an error shows as given below:
Error: 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 '1' at line 1.
I don't understand what the error is and I'm stuck here with knowing the error. Can someone please clear the errors for me. I'm a newbie in php and doesnot know much about php. So a little help from anyone is needed... Please help me out. My php script is shown below:
<?php
$con=mysqli_connect("localhost","username","password","db_name");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$image = $_POST['image'];
$result = mysqli_query($con,"INSERT INTO table3 (username,imagename) VALUES ('$username','$image')");
if (!mysqli_query($con,$result))
{
die('Error: ' . mysqli_error($con));
}
else
echo "1 record added";
mysqli_close($con);
?>
1) **You have an error in your SQL syntax; ** means that You have error in your query. It seems that your query is okay but that error may come from your post data. you need to mysqli_real_escape_string for post data.
2) you have executed twice the query.
try like this :
$username = mysqli_real_escape_string($con, $_POST['username']);
$image = mysqli_real_escape_string($con,$_POST['image']);
$result = mysqli_query($con,"INSERT INTO table3 (username,imagename) VALUES ('$username','$image')");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
else
echo "1 record added";
mysqli_close($con);
You should have written something like
$result = mysqli_query($con,"INSERT INTO table3 (username,imagename) VALUES ('$username','$image')");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
the condition should be something like
if (!$result)
{
die('Error: ' . mysqli_error());
}
Your SQL request (INSERT) is sent at the 9th line and the result is caught in $result.
$result contains the number of lines affected by the previous request (1).
Then you call the mysqli_query method again with the value of $result as a SQL request : "1" is not a valid SQL request.

mysql_insert_id() not returning a value -

I need to retrieve the auto increment field from my database table. I tried the following but $id is always just empty.
The insert works too.
My table is as follows:
idint(9) NOT NULL auto_increment,
and id is set as primary
What am I doing wrong?
$conn = mysql_connect($host,$username,$password);
mysql_select_db($database, $conn) or die( "Unable to select database");
include "update_activity.php";
updateActivity("logged in", "On Break");
$date = date("m/d/y"); $starttime = time();
$sesh = $_SESSION['fname']." ".$_SESSION['lname'];
$q = "INSERT INTO `breaks` (date, starttime, user) VALUES ('".$date."', '".$starttime."', '".$sesh."')";
$query = mysql_query($q, $conn);
$id = mysql_insert_id($conn);
echo var_dump($id); exit;
edited to show my more recent attempts
Have read all comments given and your replies to each.
Only one of these is possible:
Either the query works properly OR
You are not getting the generated primary key.
Both of these can never be true.
Define, how you know query is working? Do you know the max PK before and after the running query? Is the insert happening from some other place or thread or even other user? the query is working properly from code or from your mysql client?
To diagnose the problem, we have to go though the normal way.
Dump your generated query before calling mysql_query.
Wrap a error checking system around your query call so php can tell you if the query worked or not. I am sure just by these two steps you will realize the root cause of the problem.
error_reporting(E_ALL);
ini_set('display_errors','on');
echo "before calling: $q\n";
$query = mysql_query($q, $conn);
if(!$query)
{
echo "Error:" . mysql_error($conn);
return;
}
echo " generated id:" . mysql_insert_id($conn);
#adelphia as far as i get the idea there is a problem in the query that is executed.
plz check the query properly
Borrow a lead from this code extracted from here:
http://php.net/manual/en/function.mysql-insert-id.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
The problem with your insert query
$q = "INSERT INTO `breaks` (date, starttime, user)
VALUES ('".$date."',
'".$starttime."',
'".$_SESSION['fname'] $_SESSION['lname']."')";
try with this
and main thing you are using most of the deprecated "mysql" things like "mysql_insert_id()"
store the values that u want to pass into an array or variable and pass it in the insert query.
its should work fine then...

SELECT and UPDATE not working -- MySQL

After I upload a photo to a server, I want to save it in the user's database in MySQL, but for some reason, it is not working. Below is the code for uploader.php:
session_start();
if(!$_SESSION['userid']) {
header("Location: index.php");
exit;
}
$con = mysql_connect("host","db","pw");
if (!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("db", $con);
$sess_userid = mysql_real_escape_string($_SESSION['userid']);
$query = "SELECT * FROM Members WHERE fldID='$sess_userid' UPDATE Members SET PortraitPath = 'profileportraits/' . '$_FILES[file][name]'");
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_assoc($result);
I'm sure there is something very wrong with my query, but I can't figure out what it is. The photo is definitely being saved into the folder. But I simply want to update its path in the user database for later use. Thank you!
as it was mentioned already, you cannot use these two queries at once.
but there is also weird syntax: you're trying to use PHP's concatenation operator inside of mysql query.
And you did not escape a string parameter - very bad!
So, looks like you need something like
$sess_userid = mysql_real_escape_string($_SESSION['userid']);
$PortraitPath = mysql_real_escape_string('profileportraits/' . $_FILES['file']['name']);
$query = "UPDATE Members SET PortraitPath = '$PortraitPath' WHERE fldID='$sess_userid'";
You can do two separate queries:
UPDATE Members SET PortraitPath = 'profileportraits/' . '$_FILES[file][name]'
WHERE fldID='$sess_userid';
And:
SELECT * FROM Members WHERE fldID='$sess_userid'
It seems you tried to put two queries(SELECT and UPDATE) into one query which will result in invalid query error.
Just wondering why you need two queries since you already know the userid and all you want is to update. All you need is to update the file path
UPDATE Members SET PortraitPath = 'profileportraits/' . '$_FILES[file][name]' WHERE fldID='$sess_userid';

Categories