Using PHP in XAMPP: can create db but cannot create tables - php

I'm a beginner programmer, and I've installed XAMPP with the intention of learning a bit of PHP. I have a working knowledge of SQL.
I've been following the PHP tutorial at w3schools. The problem I am currently having is this: I'm using the script here to create a database and a table within it. What I'm using is almost verbatim, except I've replaced the user with "root" and I've deleted the password.
After running the script through the browser, the database my_db appears in the datafile for mysql in XAMPP.
However, there is no sign of a table, and when I try to select the table, I get
Table 'my_db.persons' doesn't exist
What is going on? Is there something wrong with the code I took verbatim, or is it something with permissions?
It's weird that the database is created but not a table...

What has happenned is that your "CREATE TABLE" will have failed.
Get into the habit of checking for errors after EVERY mySQL query (in your code): there are some times you can ignore errors, but it's rare. So program alonghte lines of:
Create query: $sql =
Set parameters: $aParams = (or bind paramters)
Execute query
If errors
If debug: Show error and query
If live: Log error and query
I'm not giving the solution is code, as one problem with the tutorial you follow is that it uses mysql_() functions that are going to be depreciated shortly. You should use PDO (PHP Database Objects) or mysqli() functions otherwise your code will not work in a few releases time.
With PDO, you can set error handling to use exceptions, and you wrap every call in try {} catch {} and this makes the habit of catching and reporting errors very easy.
$sql = 'CREATE TABLE....';
$aParams = array(
':param_name' => $param_value,
':param_name2' => $param_value2
);
try {
$stmnt = $db->prepare($sql);
$stmnt->execute($aParams);
$stmnt = null;
} catch (Exception $e) {
// Error log here; $e contins line of error and the actual error, you have $sql and $aParams
LogDBError($e, $sql, $aParams);
}

Related

How can I bring data from MariaDB hosted in a server using a php file?

We have a remote server containing a SQL MariaDB. I have to write a piece of code to be placed in that same server whose mission is to execute querys asking for data, modify that data and send it to an external api hosted in another server. When I was shown the DB, it was through ssh commands and entering sql mode inside the server rather than trough code like PHP as I have always done it before.
So, my code is to placed in the same server as the DB, brings the data, modifys some info and calls the api to upload it.
As I said, I am completely lost so my question is simple: can this be achieved? if so, how?
I've read about ssh_connect and exec, but since the code will be placed in the same server I don't think this is necessary, correct me if I am wrong. I can't place any code since I don't know how to start.
Thank you guys for all the help, I am closing the question now:
All I had to do was to use PDO as a secure way to establish a connection and to prepare and execute the querys. Remember I placed my php file in the same server that hosts the DB and note that I had to create a user and grant permissions to the DB you can find how in one of the comments above or here. Here is the code:
try {
$conn = new PDO('mysql:host=yourhostserver;dbname=dbname','user','password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
echo "ERROR: " . $e->getMessage();
}
//Example of query
$stmt = $conn->prepare('SELECT GROUP_CONCAT(DISTINCT source_external_subscriber_id) AS ids FROM cdr');
$stmt->execute();
foreach ($stmt as $row) {
$string = $row['ids'];
}

MySQL Returns different number of rows on localhost vs live server for the same code

I have a simple form that needs a list of stops in the textarea and returns an id for each on the right hand side. This is my screenshot on localhost...I have the same table names, column names, number of records on both localhost and live server.
Here's the screenshot of the same page with same query on live server...
Here's the code I am using on both pages
$conn = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
if(isset($_POST["busnumber"], $_POST["busroute"])){
$stops = explode(PHP_EOL, $_POST["busroute"]);
$sql = 'SELECT * FROM stops WHERE stop_name LIKE :stop';
$statement = $conn->prepare($sql);
$statement->setFetchMode(PDO::FETCH_ASSOC);
foreach($stops as $stop){
$statement->bindValue(':stop', $stop);
$statement->execute();
$results = $statement->fetchAll();
foreach($results as $result){
echo $result['stop_id'].' '.$result['stop_name']."</br>";
}
}
}
As you can see, it returns the ID of the last row only on the live server. Can someone please tell me how this is possible and what I am missing?
EDIT 1
Notice what happens when I reverse the data entered in the text area
The localhost shows both the ids now
Guess what the server shows after reversing? Only the LAST ROW!
You don't need setFetchMode(). In the time I've used PDO I always had the best results with just using bindParam() and fetch() with the most default setup of PDO, which means just setting the errormode to exception and charset to utf8 like this:
try
{
$con = new PDO("mysql:host=".$host.";dbname=".$db_name, $user, $password);
}
catch(PDOException $e){
die("ERROR ". $e->getMessage());
}
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->exec("SET NAMES utf8");
Fetching any results like this
while($r = $statement->fetch())
{
echo $r['id'];
}
Any time when someone has used a different set up, I've noticed they've faced problems.
Try this, perhaps.
This is very simple. Please check your live db via phpmyadmin if you have access and from phpmyadmin run your queries like you are running it from php code. May be you have some restrictions of mysql or php on live. And also check your db versions on localhost and live with php versions too. Let me know the results of phpmyadmin queries thanks!
Just guessing the problem. I don't really think if this answer is correct. So please pardon me in advance.
PDOStatement::fetchAll() returns an array that consists of all the rows returned by the query. From this fact we can make two conclusions:
This function should not be used, if many rows has been selected. In
such a case conventional while loop ave to be used, fetching rows
one by one instead of getting them all into array at once. "Many"
means more than it is suitable to be shown on the average web page.
This function is mostly useful in a modern web application that
never outputs data right away during fetching, but rather passes it
to template.
Source: PDO Tutorial
I FIXED the error. I have answered it in detail on a different post and I am linking to that post from HERE Thank you all for your time and answers

Php adodb CacheExecute com_exception arguments wrong type

I'm trying to get ADODB caching to work. I have a php script where i define the DB connection.
global $conn;
$conn = new COM ("ADODB.Connection");
$connStr = "PROVIDER-SQLOLEDB;SERVER=;UID=;PWD=;DATABASE=);
$conn->open($connStr);
I left the unnecessary details out of the picture.
Then in some other script i import the connection.php, and then try to make a normal query.
$query = "SELECT * from table where some_id = 21540 and other_id = BOGUS_INFO"
$rs = $GLOBALS['conn']->CacheExecute(60,$query);
This returns Uncaught exception 'com_exception'.. ADODB.Connection Arguments are of the wrong type,are out of acceptable range, or are in conflict with another.
I'm baffled because the next line of code works flawlessly.
$rs = $GLOBALS['conn']->execute($query); //OK!
Any ideeas?
I also tried CacheGetOne but i get the same error.
Could it be from the way i defined this thing below? (it's literally like that in my code)
$GLOBALS['ADODB_CACHE_DIR']=$_SERVER['DOCUMENT_ROOT'].'/../cache/adodb';
Well after alot of hassle, i kinda found an answer by choosing another way of doing things. I downloaded the latest ADODB build. Inserted it in my project, and modified files accordingly:
The connection.php changed to:
require('PATH/adodb.inc.php');
require('PATH/adodb-csvlib.inc.php');//read somewhere that i need this for the caching executes
$GLOBALS['ADODB_CACHE_DIR'] = $_SERVER['DOCUMENT_ROOT'].'/cache/adodb';
global $ADODB_CACHE_DIR; //don't know which one adodb usese really to identify cache directory so for safety - both
$ADODB_CACHE_DIR = $_SERVER['DOCUMENT_ROOT'].'/cache/adodb';
$conn = NewADOConnection('mssqlnative');//i tried first with mssql simple but script terminated execution on execute() attempt.. no error.. no nothing.. no output .. strange
$conn->Connect($myServer, $myUser, $myPass, $myDb);
After that i had to fiddle a bit with the code because,
$rs = $conn->CacheExecute(time,query)
returns Adodbrecordset_array_mssqlnative Object, and not an array, and, in my code i used to display and manipulate values as
while (!$rs->EOF) {
$rs['row']->value;
$rs->MoveNext();
}
and now they should be
$rs->fields['row'];
Another tricky thing was getting the fields array to be associated to the names of the columns in my query, but after a short search i discovered
$GLOBALS['conn']->SetFetchMode(ADODB_FETCH_ASSOC);
and voila! Everything works, even the caching.
It took script execution times with this bare optimisation from 1 sec to 0.1 or even 0.005 sometimes.

MySQL call SHOW ERRORS after executing a stored procedure

I have several stored procedures that I am calling via PDO in PHP. I was hoping to be able to handle errors by performing a ROLLBACK, but I still want to be able to use PHP to retrieve and handle the last error in the procedure. I have tryed using PDO::errorCode() and PDO::errorInfo(), but that does seem to be a legitimate solution, I think because I am already handling the errors in my stored procedures.
When I call one of the stored procedures via command line and then call SHOW ERRORS I get a nice result set with the error status, code and message, but if I call SHOW ERRORS in PDO after executing the stored procedure, I get no results. I also get no result from SHOW ERRORS in command line if I call show errors inside the stored procedure.
I would use GET DIAGNOSTICS, but the MySQL server I am developing for is on a hosted cPanel that I don't have control over updating and it is version 5.5.
Is there some other option I could use or another route I should be taking?
Like I said, I have several stored procedures I want to handle errors, but I can't even get this to work on a simple stored procedure:
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
END;
SELECT *
FROM bunnies;
END
Update: My PHP code was in an object, so I copied and simplified the code to post per Barmar's request and when I tried the simplified code, I found that SHOW ERRORS does indeed work with PDO when prepared and executed after the function is prepared and executed.
My object was a little complicated (I wrote it a while back before I knew much about PHP OOP), so I simplified it as well and now it works! I think the connection was being closed in between calls and now that the code is simpler, I am having no problems with calling SHOW ERRORS in it.
Here's the simplified PHP code I used to test, in case anyone has had issues getting this to work:
$host = '***';
$user = '***';
$pass = '***';
$schema = '***';
$connection = new PDO('mysql:host=' . $host . ';dbname=' . $schema . ';', $user, $pass);
$statement = $connection->prepare('CALL test()');
$statement->execute();
$statement = $connection->prepare('SHOW ERRORS');
$statement->execute();
echo var_dump($statement->fetchAll());
$statement = null;
$statement = null;
$connection = null;
Make sure you use the same PDO connection object to execute the original queries and to retrieve the errors. Each connection has its own error state.

How to skip non-object error in PHP mysqli?

When having an error in SQL syntax in classic PHP mysql, the query will not take place without any other effect. But in mysqli, it will kill the PHP script with Fatal error
mysql_query("SELECT title, misspelled_column FROM posts");
$mysqli->query("SELECT title, misspelled_column FROM posts");
In the first case, it will show the other queries and php output; but the second case kills the script by
Fatal error: Call to a member function fetch_assoc() on a non-object
The problem is related to non-object returned by false query. I can skip this error by
if($result){$row = $result->fetch_assoc();}
but my question is that why I did not need this check in classic mysql? With a more advanced system, one expects new features not missing what we had.
An error generated by MySQL should not be stopping execution. In fact, you can have your script show you any SQL errors by using $mysqli->error (assuming $mysqli is your database connection, like in your example). However, what may be happening is that your mysqli error causes a particular object not to be created, and then calling a method on that object will create a fatal PHP error. For example:
$dbconn = new mysqli("localhost", $username, $password, $dbname);
$stmt = $dbconn->prepare("bluh"); // not a valid statement. fails to create a mysqli statement object in $stmt.
echo($dbconn->error); // your script is still running, and this will show your MySQL syntax error.
$stmt->execute();
This will die not because you made an SQL error, but because $stmt was null and didn't have the expected execute() method. So like everyone else has said, check your logs and see what the actual error is.
Using # to ignore errors is going to be hit-or-miss until you figure out which specific command is creating the error.
update: If you know that the error is in the query, then you could check to see whether the query succeeded before you try to do anything with it. One way is to check the error parameter; another is to check to make sure that it actually returned the kind of object you want.
Here are examples of both:
$result = $db->query("select firstname, lastname from people where firstname = 'egbert';");
if($db->error == '') {
// the query worked, so fetch results from $result and do stuff with them.
}
else {
// the query didn't work, so don't try to do anything with $result
}
// alternately:
if(gettype($result) == "object") {
// the query worked.
}
else {
// it didn't.
}
A SQL error doesn't kill mysqli in my experience. I suspect you actually have a PHP error in the relevant statement. Check your error log.
In PHP, you can use # to suppress errors. It's a bad idea to use it here. But if that's what you really want, it's documented at http://php.net/manual/en/language.operators.errorcontrol.php.

Categories