PHP to MySQL beginner question: - php

Just to get started, and thinking I needed a "database," I did this:
$db = new PDO("java:comp/env/jdbc/mysql");
$stmt = $db->query("CREATE DATABASE kitty_db");
To see if it worked I commented out the above and then wrote:
$link = mysql_connect('localhost:3306', 'me', 'blah');
$db_list = mysql_list_dbs($link);
while($row = mysql_fetch_object($db_list)) {
echo $row->Database ."<BR>";
And I saw that my new database was there:
information_schema
mysql
kitty_db
performance_schema
test
And so my first question is, did I even need to make a new database next to mysql just to get started on something? I don't recall ever having to do that a couple of years ago (7 actually) when I was setting up MySQL before (sans via PHP).
Anyway, I'm wondering why I can't create a table now. If kitty_db isn't a good idea, let's take it out. But I may be having trouble putting a TABLE 'milk_bowl' (with an index or key or whatever 'bowl_name' field).
Thanks for any help. Things have gotten more complex since I just opened up a command line in MySQL almost a decade ago and just issued simplistic queries.

And so my first question is, did I
even need to make a new database next
to mysql just to get started on
something? I don't recall ever having
to do that a couple of years ago (7
actually) when I was setting up MySQL
before (sans via PHP).
This question is kind of vague. You are asking about needing to make a database to start on something? Without know more about your something, I don't really think that question is answerable. Creating the database is usually the first step when setting up a database. You might find this helpful when getting started.
Anyway, I'm wondering why I can't
create a table now. If kitty_db isn't
a good idea, let's take it out. But I
may be having trouble putting a TABLE
'milk_bowl' (with an index or key or
whatever 'bowl_name' field).
From the above link (adapted to your example):
<?php
$con = mysql_connect("localhost:3306","me","blah");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE kitty_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table
mysql_select_db("kitty_db", $con);
$sql = "CREATE TABLE milk_bowl
(
bowl_name varchar(15),
)";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
Thanks for any help. Things have
gotten more complex since I just
opened up a command line in MySQL
almost a decade ago and just issued
simplistic queries.
I don't think that's changed all that much. You can still use the command line to connect to your mysql db and issue queries directly. PHP just lets you do it through a browser/scripts.

This is not a direct answer to your question, but it might solve your problem... have you tried using an application such as MySQL Administrator or MySQL Query Browser? I came back to MySQL recently after a very long hiatus as well and found them both very helpful.

Related

PHP mySQL Update doesn't work

I currently have a very big problem with PHP and mySQL. I moved a System I coded to a new Server. And while everything worked fine on the old Server, I had some problems on the new Server. Especially with mySQL. While I solved nearly all of them, I have one which I can't seem to get a hold on. And after 2 hours of trying i searched on the Internet for another two hours and updated my Syntax several times. But nothing seems to work. So now I'm here. I get a Connection to the database without a problem, but I can't update the values. I hope you can help me.
//Connect to mySQL Database
$verbindung = mysql_connect($server, $username, $passwort);
if (!$verbindung) {
echo "Couldn't connect: " . mysql_error();
}
$name=$_POST['fuehrer'];
$ident=$_POST['id'];
//Debugging
echo $name;
echo $ident;
$sql_befehl_0="UPDATE 'olgatermine' SET fuehrer = '".$name."' WHERE ID = '".$ident."';";
if (!mysql_query($verbindung, $sql_befehl_0)){
echo "Couldn't write to database";
}
//Close connection
mysql_close ( $verbindung );
What version of php use? Because in the newest versions of php the mysql functions are deprecated/removed, use instead mysqli.
Try to echo a mysqli_error at the end of the code, also mysql_error if your version of php accepts mysql functions.
If not version of php is the problem check this:
Wrong things what i see in your code..:
$sql_befehl_0="UPDATE 'olgatermine' SET fuehrer = '".$name."' WHERE ID = '".$ident."';"; // wrong
should be:
$sql_befehl_0="UPDATE `olgatermine` SET `fuehrer` = '".$name."' WHERE ID = '".$ident."';";
You need to run mysql_select_db('dbname') below line you do the mysql connection.
You can set at the first line of file:
ini_set('display_errors',1);
error_reporting(E_ALL);
to show all errors.

PHP and MySQL INSERT INTO does not work -- No error and no new lines in DB

This my first post on this site. I will do my best to include all the needed information. I have read many of the answers regarding this same problem. I have tried many combinations and none of them work. The following is the one that gets me the closest to my very simple goal --> Write a line to my database. This code is in a password protected portion of my site.
<?php
//Connect to database
include("../ConfigFiles/ConnectDB_live.php");
echo "<br> I am still alive? <br>";
//Can I read from DB --- This worked on live
$strSQL = "SELECT * FROM invoicelist_table";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs))
{
echo $row['FileName'] . "<br>";
}
//Can I write to the DB --- Live
//Lets mix a few ideas together
mysql_query($bdd,"INSERT INTO `invoicelist_table` (`InvoiceNo`, `FileName`, `FilePath`) VALUES ('9999', 'MyName', 'MyPath')") ;
echo mysql_error();
//or die(mysql_error());
echo "I wrote something to the DB successfully <br>";
// Close the database connection
mysql_close();
echo "The connection to DB is closed";
?>
Note that I can read the database just fine but I can't seem to write to it. I have also tried the recommended mysqli version but that does not work either. I have tried various ways of trapping an error and I get nothing... literally nothing! I have tried at least a dozen syntax variations. I am ready to throw up!
I am new to web programming and find most of my answers online. I think I am doing pretty good for my limited knowledge. This one is blowing my mind. None of the recommendations I read about work or make sense to me. So please answer me like I am a 5-yr old!
Thanks in advance.
Move your connection as the second parameter or remove it if you didnt close the connection
mysql_query("INSERT INTO `invoicelist_table` (`InvoiceNo`, `FileName`, `FilePath`) VALUES ('9999', 'MyName', 'MyPath')") ;
Docs

Having Problems With PHP Connection

This is the code that connects to my SQL database. I'm new with this stuff and it seems to be semi-working but certain features on my website still don't work.
<?php
$con = mysql_connect("localhost","username","password");
$select_db = mysql_select_db('database1',$con);
/*$con = mysql_connect("localhost","username2","password2");
$select_db = mysql_select_db('database2',$con);*/
?>
This is the site in question: http://tmatube.com keep in mind the credentials above are filled in with what the programmer used for testing on his own server... ;) unfortunately I don't have access to him for support anymore.
Anyway, here's my thoughts on how this code needs to be edited maybe someone can chime in and let me know if I'm correct in my assumptions:
<?php
$con = mysql_connect("localhost","username1","password1"); -------------<<< leave this line
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con);
/*$con = mysql_connect("localhost","DB_USERNAME_HERE","DB_PASSWORD_HERE");
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con);*/
?>
Ok - now on to a few problems I noticed...
What does this do? /* code here */? It doesn't work at all if I leave that bit in.
Why is it connecting to database twice? and is it two separate databases?
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con); <<<---- single '
When I tried to see if that line was correct the examples I saw had quotes like this
$select_db = mysql_select_db("DATABASE_NAME_HERE",$con); <<<---- double "
Which one is right?
He didn't leave it out. What he did was leave the database to be connected using the root, which has no password. The other connection (which is commented out) is using another user, rajvivya_video, with a password defined.
In testing it MIGHT be okay to connect to root and leave it without password, but even that is not recommended, since its so easy to work with a user and password defined (besides root).
Here is php mysql connect with mysqli:
<?php
$link = mysqli_connect("myhost","myuser","mypassw","mybd");
?>
No difference here with ' or ". (Anyway use mysqli and you can the wanted db as 4th parameter.) php quotes
/* comment */ is a commented out so the php does not care what is inside so only 2 first rows of are affecting (they are same mysql database on the local machine and 2 different user + password combinations). Comment in general are used to explain the code or removing part of the code with out erasing it. php commenting

Mysql fails in php but works in phpmyadmin

I've made this a lot of times but now I can't :(
The insert allways return false but if I execute the same SQL script (taked from the output) it inserts in the database without any problem. I'm connected to the database because some values are fetched from another table.
This is my code:
$query = "INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx,equipo_compania,paciente,sexo,edad,id_compania,otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('$fecha','$macropera','$pozo','$equipo_pmx','$equipo_compania','$paciente','$sexo',$edad,$id_compania,'$otra_compania','$puesto','$ta','$tum','$ove','$coordinador')";
if (mysql_query($query,$connection)){
//OK
} else {
$errno = mysql_errno();
$error = mysql_error();
mysql_close($connection);
die("<br />$errno - $error<br /><br />$query");
exit;
}
The output is:
0 -
INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx, equipo_compania,paciente,sexo,edad,id_compania, otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('20111001','P. ALEMAN 1739','P. ALEMAN 1715','726', 'WDI 838','SERGIO AYALA','M',33,21, '','','110/70','ROBERTO ELIEL CAMARILLO','VICTOR HUGO RAMIREZ','LIC. PABLO GARCES')
Looks like there are no error, but allways execute the code in the else part of the if instruction. Any idea? Thanks in advance.
I think the issue might be you are missing the mysql_select_db line after the connection.
After the connection with the database is established you need to select a DB. Please make sure you have selected the Database that your desired table resides in.
And you can even use the following snippets to get some useful informated through mysql_errors.
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection) {
die('<br>Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name')) {
die('Could not select database: ' . mysql_error());
}
And try you insert query after these lines of code. All the best.
I agree with the others concerning the column types. INT is one of the only data types that do not require single quotes.
There are two blank strings. There is a possibility that the variables are not defined, and therefore giving you a PHP exception (not even in the MySql yet) but that requires stricter-than-normal exception settings. I would personally look into the $connection variable. Before the SQL query statement, put this and send us the cleaned results:
echo '<pre>'.var_dump($connection, true).'</pre>';
Additionally, on your mysql_connect function call, put
OR die('No connection')
afterwords. Do the same thing with the mysql_select_db function, changing it to 'No DB Select' obviously.
Ultimately, we will need more information. But changing to mysqli is very desirable.
Oh! And make sure the permissions for the user you are connecting as are not changed. Sometimes I find people who connect to PhpMyAdmin using one user account but a different account in their PHP code. This is problematic, and will lead to problems eventually, as you forget the different accounts, at times.

Can't access the SQLite database with MAMP and PHP

I have been learning how to program websites lately and the time has come for me to add a database. I have in fact already successfully created a MySQL database and interacted with it with PHP.
My problem is I can't seem to access a SQLite database file with it. I am using MAMP to host locally for now. Here is a snippet of the code I am using to access the db and find and print out a value stored on it.
<?php
$dbhandle = sqlite_open('/Applications/MAMP/db/sqlite/Users');
if ($dbhandle == false) die ('Unable to open database');
$dbquery = "SELECT * FROM usernames WHERE username=trevor";
$dbresult = sqlite_query($dbhandle, $dbquery);
echo sqlite_fetch_single($dbresult);
sqlite_close($dbhandle);
?>
As you have access to the database (your code doesn't die), I'd say there's got to be an error later ;-)
Looking at your SQL query, I see this :
SELECT * FROM usernames WHERE username=trevor
Are you sure you don't need to put quotes arround that string ?
Like this :
SELECT * FROM usernames WHERE username='trevor'
Also, notice that sqlite_fetch_single will only fetch the first row of your data -- which means you might need to use sqlite_fetch_array or sqlite_fetch_object if you want to access all the fields of your resulset.

Categories