Query different MySQL tables from PHP - php

been googling for hours and I'm quite new to this.
I have two identical tables in one MySQL database:
One named "users" and one named "keys".
They are identical for testing purposes.
When I query "users" I get a response, when I query "keys" I get nothing.
Querying users I get the expected response:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT name
FROM users
WHERE can_share = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
Querying keys I get nothing:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT name
FROM keys
WHERE can_share = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
I guess there must be some basic understanding of databases that has slipped by me, but still, after hours of searching I can't figure it out. Maybe I'm becoming retarded.

I think that might be due to table name being 'keys'.
Have a look here:
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
You have to understand while designing your tables and naming the attributes that some words are reserved by MySQL itself.
So, if you name your table 'WHERE' you will have troubles in usual query. Why?
'SELECT * FROM WHERE'
Such a query obviously doesn't work, as it will ask you to provide table name.
Now, when you change format situation also changes:
'SELECT * FROM `WHERE`'
As you can see I added some backwards commas. In MySQL they are used to denote names of tables or fields. If you use them - the server processes and reads your query correctly.
So, that's why your edited query worked fine in the end.

Thanks to enabeling debugging, I got this message:
mysql_result() expects parameter 1 to be resource, boolean given in
...
And figured out that I had to query "keys" like this:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT `name`
FROM `keys`
WHERE `can_share` = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
Now it works, but I still don't understand why only one of the tables needed that formatting. And I have learned that I should rewrite the whole thing to not be vulnerable to SQL injection attacks. ...
EDIT: It seems like the words "key" and "keys" and some more are reserved by MySQL, so to use them, they have to be formatted like that.

Related

Basic php - echo mysql, how?

I want it to echo how many posts there are in bestallt where its ID is 1 from the table order and display it as how many posts there are in numbers. I am connected to the database in the PHP file, that's not an issue. I'm just not sure how to put it all down in PHP, quite new to this. I just can't get it to echo what I want, nothing comes out/I get an error.
Any help is appreciated!
Your present code does not fetch the data from the database, it simply echoes the SQL query you have written.
Quite a lot more code goes in to fetching results from a mysql database, and I am not sure reproducing a full explanation here will serve anyone's interests. However, you may wish to view the examples of how to use PDO (a method of using mysql databases from php) here, and then either edit or re-ask your question if you find you have specific difficulties following those examples.
Try this code:
<td>
<?php
$sql = "SELECT count(*) FROM order WHERE bestallt='1'"; // Your SQL query
$response = mysql_query($sql);
if (mysql_num_rows($response) == 0) {
// Your query returned 0 rows!
}
while($row = mysql_fetch_array($response)){
// For each row returned from your query
// $row is an array
// For example, You can use it:
echo $row['data1'];
echo $row['data2'];
echo $row['data3'];
// data1, data2, data3 are the name of the fiels in your database
}
?>
</td>
Have a nice day!
Try this,
$sql = "SELECT count(*) FROM order WHERE bestallt='1'"
$res=mysql_query($sql);
$arr=mysql_fetch_array($res);
echo "<pre>";print_r($arr); //you will get whole array for matching record of your order table if found anything
To learn more, you can check my earlier Answer: how generate report between the two dates using datepicker,ajax,php,mysql.?
In that answer I have described whole working demo.

foreach loop returns nothing

I am trying to pull user data from a Cart66 table I have and put it into a shortcode in wordpress. $account is an integer pulled from session data. The code below returns nothing.
$account =Cart66Session::get(Cart66AccountId);
global $wpdb;
$fname=$wpdb->get_results("SELECT * FROM 'vfp_cart66_accounts' WHERE id = '$account', ARRAY_N");
foreach ($fname AS $row)
{
echo $row;
}
This returns "Array"
return $fname;
Ok firstly, maybe I am the only one who saw this, and it could be the source of your entire problem, but you have a misplaced double quote, at the end of your SQL line, which should live at the end of the actual SQL string, not after the requested return type:
// at the end of this line you have: '$account', ARRAY_N");
// this should be changed to: '$account'", ARRAY_N);
$fname=$wpdb->get_results("SELECT * FROM 'vfp_cart66_accounts' WHERE id = '$account', ARRAY_N");
Even the first person who answered the question did not correct you, so I am assuming he didn't see it either. Secondly, using single quotes (') to escape a table name is invalid. If it is quoted at all, use backticks (`). Single quotes indicate a string, not an database, table, or field, all three of which should only be quoted with backticks (except on utility queries like SHOW). Use this instead:
select * from `vfp_cart66_accounts` where id = '$account'
Thirdly, as your commenters point out, you could be vulnerable to SQL Injection. Make sure to use the tools that WP gives you, and do this, or similar, instead:
$fname = $wpdb->get_results(
$wpdb->prepare(
'select * from `vfp_cart66_accounts` where id = %d',
$account
),
ARRAY_N
);
Lastly, you are requesting an array from the DB, but you are trying to echo it as if it were a scalar value. This explains why printing the value of $row yields "Array". When you convert an array() to a string, by default, you get "Array", since arrays can be complex data that may not be beautifully converted to a string. As a correction of this, you can do one of two things.
First, if you need the entire resulting array that represents the entire row of the table, then you can simply change your echo code to this:
foreach ($fname as $row) {
// print the fname of the row
echo $row['fname'];
// do the other stuff you need to do with $row
...
}
OR, if you simply need the fname field out of that table, for the given id, you could use a different $wpdb function, called $wpdb->get_var(), which gets one specific field from the first entry of the resulting data from the database, coupled with some minor SQL changes:
// use the get_var() function instead
$fname = $wpdb->get_var(
$wpdb->prepare(
// 1) change the 'fields' of your sql to only get the `fname` field
// 2) also add limit 1, to reduce load by only asking for one row
// NOTE: #2 is optional really, because WP does this for you when using get_var,
// but is good practice to only ask for what you need. so do it
'select fname from `vfp_cart66_accounts` where id = %d limit 1',
$account
),
ARRAY_N
);
echo $fname; // print the value of field fname from vfp_cart66_accounts for id $account
Now. I don't have specific knowledge of Cart66. That being said, if the above changes to PHP, WordPress, and SQL syntax do not yield results, then you are probably having one of the following other problems instead:
there is a different PHP error somewhere in the code, causing this to never run
this code is never called, and thus it is never executed
you misspelled the table name, which is causing an SQL error
the table exists, but does not have a field named id
both table and field exist, but there are no entries in the table
some other random thing that is not coming to mind
DEBUG #1
For #1, you could try turning on error_reporting() and display_errors early in the code execution. In a normal, run of the mill PHP script you could add the following two lines somewhere early in the code:
error_reporting(E_ALL);
ini_set('display_errors', 1);
However, you are using WordPress, so you will need to do something like this in your wp-config.php file:
// find the line that looks like this and comment it out
// define('WP_DEBUG', false);
// add these two lines directly below it
define('WP_DEBUG', true);
ini_set('display_errors', 1);
DEBUG #2
Make sure your code is running. Don't be afraid to throw a die() statement directly above it, to make sure it is running. Something like this:
// add a die() before everything
die('I am running. Awesome!');
// revised code
$account = Cart66Session::get(Cart66AccountId);
global $wpdb;
$fname = $wpdb->get_var(
$wpdb->prepare(
'select fname from `vfp_cart66_accounts` where id = %d limit 1',
$account
),
ARRAY_N
);
echo $fname;
DEBUG #3
To debug #3, you need either access to a commandline tool for MySQL or some type of GUI interface like phpMyAdmin, so that you can run a query directly from the database. Here is the query you should run:
show tables like 'vfp_cart66_%';
This is an example of one of the only places in SQL that you should ever quote a table name in single quotes. Running this will yield a list of all the tables that start with vfp_cart66_. If you get no results, then your table name is wrong. If your results do not include vfp_cart66_accounts, then your table name is wrong. If you see vfp_cart66_accounts, you are good to go.
DEBUG #4
This one will need to be run directly from the DB or through something like phpMyAdmin also. You are trying to make sure you have the correct field name. The way you do that is:
show create table `vfp_cart66_accounts`;
Assumedly, the field you are calling id would be the auto_incremented field in the table. Thus you are looking for a line, similar to this one:
`id` bigint(20) NOT NULL AUTO_INCREMENT,
Make sure that the line that has AUTO_INCREMENT on it, begins with:
`id`
If it does not, and the name is something else other than id, then you probably have the wrong field name.
DEBUG #5
Make sure you actually have data to display. From your mysql console or phpMyAdmin, run:
select * from `vfp_cart66_accounts` limit 1;
If you bet any results, then you have data, and you are good.
DEBUG #3 - #5 (alternate methods)
Another option you have is to dump the $wpdb object, directly after you run the query, because it contains the last error you received from MySQL. You can do this like so:
$fname = $wpdb->get_var(
$wpdb->prepare(
'select fname from `vfp_cart66_accounts` where id = %d limit 1',
$account
),
ARRAY_N
);
// dump a readable version of the $wpdb object
echo '<pre>';
print_r($wpdb);
die('</pre>');
Often times, reading the MySQL error message helps narrow down the problem in your SQL syntax.
DEBUG #6
If none of this has helped at all, then you will need to use your experience to trackdown a random bug in either your plugins or theme, what could literally be anything. You may as well not even dig in core WP code because, while it does have a couple minor bugs unrelated to your problem, which are getting repaired as we speak, it is one of the most stable CMS platforms out there. It is used by more of the top 10 million sites on the internet than any other CMS, for a good reason. It works, it is up-to-date, and most of all, it is stable.
I really hope you found this helpful or at least learned something from it. Hopefully others find it useful as well.
$fname=$wpdb->get_results(
"SELECT * FROM `vfp_cart66_accounts` WHERE id = '$account'",
ARRAY_N"
);

PHP MySQL While loop for SELECT from two tables?

Hi there i am working on PHP code that is selecting columns from two tables.
Here is my code:
$result2 = mysql_query("SELECT *
FROM `videos`, `m_subedvids`
WHERE `videos.approved`='yes' AND
`videos.user_id`='$subedFOR'
ORDER BY `videos.indexer`
DESC LIMIT $newVID");
while($row2 = mysql_fetch_array($result2))
{
$indexer = addslashes($row2['videos.indexer']);
$title_seo = addslashes($row2['videos.title_seo']);
$video_id = addslashes($row2['videos.video_id']);
$title = addslashes($row2['videos.title']);
$number_of_views = addslashes($row2['videos.number_of_views']);
$video_length = addslashes($row2['videos.video_length']);
}
When i try to print $indexer with echo $indexer; it's not giving me any results.
Where is my mistake in this code?
It seems to me like the key 'indexer' isn't in your results. It's hard to tell, since you haven't listed a definition for your table and you're using SELECT * so we can't see the names.
It makes the program easier to read later, if instead of SELECT *..., you use SELECT col1, col2, .... Yes, SELECT * will save you some typing right now, but you'll lose that time later when you or anyone else who works on your code has to check the table definition every time they work with that line of code.
So, try changing your query to explicitly select the columns you use. If it's an invalid column you'll get an error right away rather than this silent failure you're getting now, and you'll thank yourself later as well.
So long as videos.indexer is a unique field name among all tables used in the query you can change
$indexer = addslashes($row2['videos.indexer']);
to
$indexer = addslashes($row2['indexer']);
You don't need to (or can not) use the table name when referring to the result.

only retrieving 1 row of data from MYSQL database

I am trying to input multiple pieces of data through a form and all the data will be separated by (,). I plan to use this data to find the corresponding id for further processing through an sql query.
Below is the code I use.
$key_code = explode(",", $keyword);
//$key_count = count($key_code);
$list = "'". implode("','", $key_code) ."'";
//$row_count = '';
$sql4= "SELECT key_id FROM keyword WHERE key_code IN (".$list.")";
if(!$result4 = mysql_query($sql4, $connect)) {
mysql_close($connect);
$error = true;
}else{
//$i = 0;
while($row = mysql_fetch_array($result4)) {
$keyword_id[] = $row['key_id'];
//$i++;
}
//return $keyword_id;
}
The problem i see is that keyword_id[0] is the only element that contains any data (the data is accurate). Even if I input multiple values through the aforementioned form.
I thought it might be an error in the sql but I echo'ed it and it looks like:
SELECT key_id FROM keyword WHERE key_code IN ('WED','WATER','WASTE')
The values in the brackets are exactly what I inputted.
I even tried to figure out how many rows are being returned by the query and it shows only 1. I assume something is wrong with my query but I cannot figure where.
Any help will be greatly appreciated.
Edit: Alright Solved the problem. Thanks to suggestions made I copied and pasted the $sql_query I had echo'ed on the website into mysql console; which resulted in only 1 row being retrieved. After taking a closer look I realized that there was a whitespace between ' and the second word. I believe the problem starts when I input the key_code as:
WED, WATER, WASTE
Instead inputting it as
WED,WATER,WASTE
fixes the problem. I think I should make it so that it works both ways though.
Anyway, thank you for the help.
I am pretty sure that the query is ok. How many rows do you get with just
SELECT key_id FROM keyword
I think that there is just one line that matches your WHERE.
Check the query directly in the database(with phpmyadmin, or in the mysql console), however this query seems to be working as you may assumed. If it returns only 1 row when you use it directly in the db, then maybe there is only one row in your table wich matches this query.

Cannot simply use PostgreSQL table name ("relation does not exist")

I'm trying to run the following PHP script to do a simple database query:
$db_host = "localhost";
$db_name = "showfinder";
$username = "user";
$password = "password";
$dbconn = pg_connect("host=$db_host dbname=$db_name user=$username password=$password")
or die('Could not connect: ' . pg_last_error());
$query = 'SELECT * FROM sf_bands LIMIT 10';
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
This produces the following error:
Query failed: ERROR: relation "sf_bands" does not exist
In all the examples I can find where someone gets an error stating the relation does not exist, it's because they use uppercase letters in their table name. My table name does not have uppercase letters. Is there a way to query my table without including the database name, i.e. showfinder.sf_bands?
From what I've read, this error means that you're not referencing the table name correctly. One common reason is that the table is defined with a mixed-case spelling, and you're trying to query it with all lower-case.
In other words, the following fails:
CREATE TABLE "SF_Bands" ( ... );
SELECT * FROM sf_bands; -- ERROR!
Use double-quotes to delimit identifiers so you can use the specific mixed-case spelling as the table is defined.
SELECT * FROM "SF_Bands";
Re your comment, you can add a schema to the "search_path" so that when you reference a table name without qualifying its schema, the query will match that table name by checked each schema in order. Just like PATH in the shell or include_path in PHP, etc. You can check your current schema search path:
SHOW search_path
"$user",public
You can change your schema search path:
SET search_path TO showfinder,public;
See also http://www.postgresql.org/docs/8.3/static/ddl-schemas.html
I had problems with this and this is the story (sad but true) :
If your table name is all lower case like : accounts
you can use: select * from AcCounTs and it will work fine
If your table name is all lower case like : accounts
The following will fail:
select * from "AcCounTs"
If your table name is mixed case like : Accounts
The following will fail:
select * from accounts
If your table name is mixed case like : Accounts
The following will work OK:
select * from "Accounts"
I dont like remembering useless stuff like this but you have to ;)
Postgres process query different from other RDMS. Put schema name in double quote before your table name like this, "SCHEMA_NAME"."SF_Bands"
Put the dbname parameter in your connection string. It works for me while everything else failed.
Also when doing the select, specify the your_schema.your_table like this:
select * from my_schema.your_table
If a table name contains underscores or upper case, you need to surround it in double-quotes.
SELECT * from "Table_Name";
I had a similar problem on OSX but tried to play around with double and single quotes. For your case, you could try something like this
$query = 'SELECT * FROM "sf_bands"'; // NOTE: double quotes on "sf_Bands"
This is realy helpfull
SET search_path TO schema,public;
I digged this issues more, and found out about how to set this "search_path" by defoult for a new user in current database.
Open DataBase Properties then open Sheet "Variables"
and simply add this variable for your user with actual value.
So now your user will get this schema_name by defoult and you could use tableName without schemaName.
You must write schema name and table name in qutotation mark. As below:
select * from "schemaName"."tableName";
I had the same issue as above and I am using PostgreSQL 10.5.
I tried everything as above but nothing seems to be working.
Then I closed the pgadmin and opened a session for the PSQL terminal.
Logged into the PSQL and connected to the database and schema respectively :
\c <DATABASE_NAME>;
set search_path to <SCHEMA_NAME>;
Then, restarted the pgadmin console and then I was able to work without issue in the query-tool of the pagadmin.
For me the problem was, that I had used a query to that particular table while Django was initialized. Of course it will then throw an error, because those tables did not exist. In my case, it was a get_or_create method within a admin.py file, that was executed whenever the software ran any kind of operation (in this case the migration). Hope that helps someone.
In addition to Bill Karwin's answer =>
Yes, you should surround the table name with double quotes. However, be aware that most probably php will not allow you to just write simply:
$query = "SELECT * FROM "SF_Bands"";
Instead, you should use single quotes while surrounding the query as sav said.
$query = 'SELECT * FROM "SF_Bands"';
You have to add the schema first e.g.
SELECT * FROM place.user_place;
If you don't want to add that in all queries then try this:
SET search_path TO place;
Now it will works:
SELECT * FROM user_place;
Easiest workaround is Just change the table name and all column names to lowercase and your issue will be resolved.
For example:
Change Table_Name to table_name and
Change ColumnName to columnname
It might be silly for a few, but in my case - once I created the table I could able to query the table on the same session, but if I relogin with new session table does not exits.
Then I used commit just after creating the table and now I could able to find and query the table in the new session as well. Like this:
select * from my_schema.my_tbl;
Hope this would help a few.
Make sure that Table name doesn't contain any trailing whitespaces
Try this: SCHEMA_NAME.TABLE_NAME
I'd suggest checking if you run the migrations or if the table exists in the database.
I tried every good answer ( upvote > 10) but not works.
I met this problem in pgAdmin4.
so my solution is quite simple:
find the target table / scheme.
mouse right click, and click: query-tool
in this new query tool window, you can run your SQL without specifying set search_path to <SCHEMA_NAME>;
you can see the result:

Categories