php # mysql help [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Extremely basic PHP and Mysql
i am new to web scripting languages. i want to know what are the function's and theories i need to know if i want to submit & retrieve data using php # mysql...\
ex;- user submits a phone of a picture with details,user can search them ...likewise

You may take a look at many tutorials freely available on the net. For example:
http://www.freewebmasterhelp.com/tutorials/phpmysql - describes it in fine details.

first of all to work with mysql in php you need to have a basic understanding of SQL commands like SELECT,INSERT,DELETE... which can be found all over the web.
then you must use the mysql related functions in php to actually execute those commands.
you can find the manual in http://php.net/manual/en/book.mysql.php.

Before you can make any queries, you have to connect to the correct database!
$link = mysql_connect('localhost', 'db_user', 'db_pass');
mysql_select_db('db_database',$link));
Please replace DB_USER and DB_PASS with your login info and the DB_DATABASE witht he corresponding database.
Here's some basic queries:
database table (table):
name text
Here's some code:
mysql_query("INSERT INTO table (name, text) VALUES ('Yo', 'hello')");
This will put a new entry of "yo" and "hello" into the database table (table).
And if you want to display a table, you can do something like this:
$result = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($result)) {
echo $row['name'] . " - " . $row['text'];
echo "<br />";
}
Now this is by far a very simple explanation. There are tons of resources on the internet you can look at.
Have fun! (but not too much)
w3school.com has some great examples and easy to understand MYSQL explanations.

Related

How can I get results of this MYSQL query? [duplicate]

This question already has answers here:
mysql query result in php variable
(5 answers)
Closed 10 years ago.
How can I get the results?:
$check = mysql_query("select username, email, case
when max(username = '$username') > 0 and max(email = '$email') > 0 then 'both'
when max(username = '$username') > 0 then 'username'
when max(email = '$email') > 0 then 'email'
end
from school_users
WHERE username = '$username' or email = '$email'") or die(mysql_error());
I need "username" or "email" or "both" when it exists. How do I receive these variables?
You should use fetch functions.
mysql_query() returns resource of data, for getting this data, you need to use either mysql-fetch_assoc or mysql_fetch_array.
As already mentioned, mysql_* functions are deprecated as of >PHP 5.5, and they are bad practice of using. You should learn about mysqli or PDO.
Resources:
http://php.net/mysql_query
http://php.net/mysql_fetch_assoc
http://php.net/mysql_fetch_array
http://php.net/mysqli
http://php.net/pdo
Ok I think I understand what you are trying to do. You have alot more work than you think you do. What you need is template to work with so you can make it your own. The link below will allow you to create your own php API to communicate with a MySQL database in the manner you are talking about. It is step by step and he gives you the code to work with, all of it!
android login and registration with php mysql and sqlite
I used it and it it awesome, if you have any questions feel free to message me.
put the green check if this helps

Using content called from MySQL

I am trying to create a simple link. The issue is the file name is going to come from the database.
example: Download
I have not worked much with MYSQL and have pieced together something that is working so far
<?php
$products_id = $_GET['id'];
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$sql = "select * from znc_product_extra_fields where products_id = '" . $products_id . "'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo $row['file_1'];
}
?>
When I run it it does just what I want, it echos the file name that is assigned to that specific row (item number)
But I am lost how to turn this into the link. The only thing I can think is somehow assigning this result to a variable and calling it while creating the link but I do not know how to take this result which is correct and actually use it! How would I take this filename and place in the link
Download
PHP outputs whatever you want it to - text, HTML, XML, etc. So just output the HTML. I think what you want is:
echo "Download";
Although you shouldn't be using the outdated mysql_* functions. Please see PDO (the best option) or mysqli.
To prevent SQL injection, use PDO::quote (if you are using PDO), or mysqli_real_escape_string (if you are using mysqli).
echo 'file;
Your code is vulnerable to MySQL injection. Use real_escape_string
on your GET, POST parameters.
You should use PDO (see tereško comment for reason)

Displaying all table names in php from MySQL database

Alright, so I'm fairly new to PHP and SQL/MySQL so any help is appreciated.
I feel like I took the right approach. I searched php.net for "MySQL show all table names", it returned a deprecated method and suggested using a MySQL query on SHOW TABLES [FROM db_name] [LIKE 'pattern'] I'm not sure what "pattern" means but, I searched for "SQL Wildcard" and got the "%" symbol. According to everything I found, this should work and output the table names at the end, but it does not. Any suggestions? Thanks in advance.
<?php
if ($_REQUEST["username"]=="coke"&&$_REQUEST["password"]=="pepsi"){
echo 'You have successfully logged in.';
echo '<br />';
echo 'These are your tables:';
echo '<br />';
$link = mysql_connect("sql2.njit.edu", "username", "password");
mysql_select_db("db_name") or die(mysql_error());
$result = mysql_query('SHOW TABLES [FROM db_name] [LIKE '%']');
echo $result;
}
else
echo 'You did not provide the proper authentication';
?>
I get no errors. The output is exactly what's echoed, but no table names.
The square brackets in your code are used in the mysql documentation to indicate groups of optional parameters. They should not be in the actual query.
The only command you actually need is:
show tables;
If you want tables from a specific database, let's say the database "books", then it would be
show tables from books;
You only need the LIKE part if you want to find tables whose names match a certain pattern. e.g.,
show tables from books like '%book%';
would show you the names of tables that have "book" somewhere in the name.
Furthermore, just running the "show tables" query will not produce any output that you can see. SQL answers the query and then passes it to PHP, but you need to tell PHP to echo it to the page.
Since it sounds like you're very new to SQL, I'd recommend running the mysql client from the command line (or using phpmyadmin, if it's installed on your system). That way you can see the results of various queries without having to go through PHP's functions for sending queries and receiving results.
If you have to use PHP, here's a very simple demonstration. Try this code after connecting to your database:
$result = mysql_query("show tables"); // run the query and assign the result to $result
while($table = mysql_fetch_array($result)) { // go through each row that was returned in $result
echo($table[0] . "<BR>"); // print the table that was returned on that row.
}
For people that are using PDO statements
$query = $db->prepare('show tables');
$query->execute();
while($rows = $query->fetch(PDO::FETCH_ASSOC)){
var_dump($rows);
}
SHOW TABLES
will show all the tables in your db. If you want to filter the names you use LIKE and wildcard %
SHOW TABLES FROM my_database LIKE '%user%'
will give you all tables that's name include 'user', for example
users
user_pictures
mac_users
etc.
The brackets that are commonly used in the mysql documentation for examples should be ommitted in a 'real' query.
It also doesn't appear that you're echoing the result of the mysql query anywhere. mysql_query returns a mysql resource on success. The php manual page also includes instructions on how to load the mysql result resource into an array for echoing and other manipulation.
Queries should look like :
SHOW TABLES
SHOW TABLES FROM mydatabase
SHOW TABLES FROM mydatabase LIKE "tab%"
Things from the MySQL documentation in square brackets [] are optional.
you need to assign the mysql_query to a variable (eg $result), then display this variable as you would a normal result from the database.
Sure you can query your Database with SHOW TABLES and then loop through all the records but that is extra code lines and work.
PHP has a built in function to list all tables into an array for you :
mysql_list_tables - you can find more information about it at The PHP API page
//list_tables means database all table
$tables = $this->db->list_tables();
foreach ($tables as $table)
{
echo $table;
}

PHP MySql Select statement not working... Any advice?

[UPDATED] with new code "sql_real_escape_string()"
[UPDATED] if anyone wants to look at the site its at Test site
[UPDATED] with the while code showing any results via echo
Hello All,
I have looked at many posts on this matter, but simply cannot understand why the following code doesn't work:
$username = $_POST['username'];
// get the record of the user, by looking up username in the database.
$query = sprintf("SELECT UserName, Password FROM userlogin WHERE UserName='%s'", mysql_real_escape_string($username));
$result = mysqli_query($dbc, $query) or
die ("Error Querying Database for: " . $query .
"<br />Error Details: " . mysql_error() . "<br/>" . $result);
while ($row = mysqli_fetch_assoc($result))
{
Echo($row['UserName']);
}
The Code seems to be correct... the database is working perfectly (for input purposes) and the connection is a shared connection applied with require_once('databaseconnection.php'); that is working for the registration side of things.
like normal I'm sure this is something simple that I have overlooked but cannot for the life of me see it!
I do not get any error messages from the myssql_error() its simply blank.
any help would be much appreciated.
Regards
Check the username you try to query as it might be empty. Do you really use a post-request to run that script? How do you verify that it does not work? What do you do with $data after the query?
If just nothing seems to happen it is likely your query did not match any record. Check for whitespace and case of the username you are looking for.
Mind those warnings:
Use a prepared statement or at least sql-escape any user-input before using it in sql.
Don't use die in serious code only for debugging.
The $data will contain a result object. You need to iterate over it using something like mysqli_fetch_assoc($data).
Also, you can interpolate variables directly into double quoted strings - i.e. UserName='".$username."'" could be written more cleanly as UserName='$username' rather than breaking out of the string.
Also, please sanitize your input - all input is evil - using mysqli_real_escape_string() function. You've got a SQL injection exploit waiting to happen here.
Bear in mind that it's a very good idea to validate all data to be inserted into a database.
Very often you have problems with query itself, not implementation. Try it in phpMyAdmin first and see if there are any problems.
Check server logs.
BY THE WAY: Never put variables from POST to query! That's definitely a SQL injection'
You might have some issue with the query.
Have you Tried to echo the $query and run that directly with mysql client or workbench?
This piece of code seems ok. That is, if $dbc contains an actual database connection. But the choice of naming that variable $data while the function actually returns a result object or a boolean, indicates that you may process the data wrong.
If that is not the problem, we'll definately have to see more code.
Try printing $data variable instead of printing only query. Check, whether you are able to get any error messages. If you could see any data then you should use mysql fetch function to iterate things. Try it.

run sql query from a string using php [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
execute sql query from sql file
i have a file named file.sql which is exported from a database 'desktop'. i want import this old database to my new database 'laptop' using php scripts. i opened the file.sql using fopen and read all contents using fread and stored whole content to a string named $sqldata. how can i execute whole query from that variable??
In this kind of situation, I would rather use the mysql command-line utility to import the dump as a whole.
For instance, something like this should do :
mysql --user=YOUR_LOGIN --password=YOUR_PASSWORD --host=localhost YOUR_NEW_DATABASE_NAME < your_dump.sql
If you do not have command-line access to your server, maybe you can run this with exec / shell_exec / ...
If you really cannot use the mysql command from the command-line (nor using exec or any equivalent), maybe you can try using mysqli_multi_query ; as stated in the manual :
Executes one or multiple queries which
are concatenated by a semicolon.
Considering your dump prbably only contains several queries, separated by semi-colons, this might actually work...
Edit : as other people pointed out, what about reading the answers that have been given to your other questions ? For instance, there is some interesting stuff here : execute sql query from sql file
If there is something you don't understand in those answers, you can post comments to them, to, hoppefully, get more precisions.
You have to split the string which effectively contains multiple queries into a list of single queries (which is not as simple as splitting by ';') and execute them separately or you can simple use the MySQL Improved Extension which is, as far as I know, the only MySQL PHP extension that natively supports multiple queries which are concatenated by a semicolon by its mysqli::multi_query() / mysqli_multi_query() method/function.
By the way - using the MySQL command line client will be the best solution to this problem as Pascal MARTIN suggested.
I might be missing something, but there is no single function for such a batch-query in PHP. So, other than using the mysql command line utility, you will have to split file.sql into seperate statements and execute them one after the oter. The easiest way to do this might be to use preg_split, altough I'd like to point out that this might fail under certain cercumstances.
Update: Ok, as I just learned from S. Gehrig's answer, there is such a function in PHP.
MySQL GUI Tools sounds like what you need. Using the Administrator you can backup and restore databases. I suggested this since your moving your DB to your laptop.
Someone just asked a similar question
And my answer is the same:
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = file_get_contents("file.sql");
/* execute multi query */
if (mysqli_multi_query($link, $query))
echo "Success";
else ehco "Fail";
?>
This because mysqli can accept multiple query strings using the function 'mysqli_multi_query'.
Hope this helps.

Categories