MAMP - All MySQL Queries Return Null - php

I recently installed MAMP. But my I can't successfully execute MySQL queries from php. I can connect to MySQL from php, but all my queries come back as NULL. I don't get any error message or other message that would help me diagnose the problem.
Oddly, I can successfully query MySQL with phpMyAdmin and MySQLWorkbench.
Here is my code:
<?php
$link = mysqli_init();
$con = mysqli_real_connect($link, 'localhost', 'root', 'root', 'mrmk', 8889);
$db = 'mrmk';
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
$sql = "SHOW TABLES FROM `$db`";
$result = mysqli_query($con, $sql);
echo "</br>" . "1. MySQL Error: " . mysqli_error();
echo "</br>" . "result: ";
var_dump($result);
$sql = "SHOW TABLES FROM $db";
$result = mysqli_query($con, $sql);
echo "</br></br>2. MySQL Error: " . mysqli_error();
echo "</br>" . "result: ";
var_dump($result);
$sql = "SELECT * FROM `transactionTable` WHERE `attorneyName` LIKE \'%howard%\'";
$result = mysqli_query($con, $sql);
echo "</br></br>3. MySQL Error: " . mysqli_error();
echo "</br>" . "result: ";
var_dump($result);
if (!$result) {
echo "</br></br>" . "4. MySQL Error: " . mysqli_error();
exit;
} else {
echo "we should have results.";
}
while ($row = mysqli_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysqli_free_result($result);
?>
When I access the page through localhost I get this:
Host information: Localhost via UNIX socket
1. MySQL Error:
result: NULL
2. MySQL Error:
result: NULL
3. MySQL Error:
result: NULL
4. MySQL Error:
When I execute the same queries from phpMyAdmin, they execute successfully and return non-NULL results.
I have two questions:
What code can I add to help diagnose this problem?
Do I have a error in my code that is causing me to get NULL results.

Have you enabled mysqli extension in PHP? Check apache error log. Look at this question for example. mysqli is disabled by default, you need to uncomment line
extension=php_mysqli
in php.ini file.

To answer question #1, you might find it helpful to echo your $sql variables, to make sure your queries are valid and what you intended them to be.

Related

I got mysqli error 1064 but i don't know why

I want to post this data from android client and i tested it with postman and status code was 200. But i have a mysqli error and it's:
Error:
((1064) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE id=' at line 1)
i don't know what is my codes problem and SELECT part works correctly
<?php
$id = $_POST['id'];
$isLiked = $_POST['isLiked'];
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$connection = mysqli_connect($host, $username, $password, $database);
$query = "SELECT likes FROM posts WHERE id=$id";
$result = mysqli_query($connection, $query);
$array = mysqli_fetch_assoc($result);
$likes = $array['likes'];
if ($isLiked == true) {
$updateQuery = "UPDATE posts SET likes=" . $likes++ . " WHERE id=$id";
} else {
$updateQuery = "UPDATE posts SET likes=" . $likes-- . " WHERE id=$id";
}
if (!$connection->query($updateQuery)) {
echo "query failed: (" . $connection->errno . ") " . $connection->error;
}
mysqli_query($connection, $updateQuery);
if (!$connection->query($updateQuery)) {
echo "query failed: (" . $connection->errno . ") " . $connection->error; // It returns that 1064 error
}
mysqli_query($connection, $updateQuery);
I see 3 possible mistakes.
First mistake, the $id can be empty.
And 2nd mistake can be $likes++ need be ++$likes, because you doesn't sum it with ++ after of the variable, im referring too to --$likes.
The 3rd mistake is your code is vulnerable to MySQL injection, i recommend make a prepared statement.
Link to prepared statement example and explanation: https://www.w3schools.com/php/php_mysql_prepared_statements.asp

SQL echo table row error?

I'm VERY new to SQL, I have a table called "accounts". I want to echo all account info on an HTML table, I've tried this but it didn't work? (There are the proper tags around the php code)
<?php
$query="SELECT * FROM acccounts";
$results = mysql_query($query);
while ($row = mysql_fetch_array($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
?>
I think the problem is pretty obvious; you either didn't connect to your database, or your system doesn't allow the use of the mysql_ API.
Or, you tried connecting with the mysqli_ or other API (which is unknown). If this is the case; those different MySQL APIs do not intermix.
Using the mysqli_ API on my own machine produced results:
Replace the following with your own credentials:
<?php
ini_set("display_startup_errors", 1);
ini_set("display_errors", 1);
$connect = mysqli_connect("your_host", "user", "pass", "db");
if (!$connect) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$query="SELECT * FROM acccounts";
$results = mysqli_query($connect, $query);
if($results){
while ($row = mysqli_fetch_array($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
}
else{
echo "Your query failed: " . mysqli_error($connect);
}
Check for errors on the query and via PHP.
References:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
Note: Even without the <table></table> tags, it will still produce results, on a successful query.
Plus, this requires the file to be executed using a webserver with php/mysql installed and used as http://localhost as opposed to file:///, should this be the case.
Other reference:
http://php.net/manual/en/function.mysqli-connect.php
Few things, First off, you need to connect to the database with the sql instance name, uid and passwd strings,
secondly
your query should be mysqli_query($connection, $query)
ie
$servername = 'yourinstance\sqlexpress';
$conndetails = ["Database" => "databasename", "UID" => 'loginid', "PWD" =>'passwd'];
$sqlconn = mysqli_connect($servername, $conndetails);
$query = "Select blah blah";
$query2 = mysqli_query($sqlconn, $query);
double check the syntax because i often get it backwards off the mark but without this setup you can't connect to the database,
PHP has to authenticate / login before it can make queries (otherwise anyone would be able to query your database)
Additional to this, you need to ensure sql is listening on the right ports (normally 1433) this is done through the sql manager (not the sql explorer).
the results are still in array format, so you need to call the specific field name.
in this case.
echo '<td>' . $field['id'] . '</td>';
should work, (this is the format i use)
while ($row = mysqli_fetch_array($query)) {
foreach ($row as $field) {
echo '<td>' .$field['id']. '</td>';
}
}

php mysqli prepared statement: can't echo, print or get anything from var_dump AFTER execute command

I am starting to use mysqli and I got it working on my virtual server but can't get it working on my real server. The databases are the same. I have tried both store and get_result. Any idea what am I doing wrong?
Everything I try to echo, print or var_dump does not show up IF Place after execute but the command will be executed. It worked well on UPDATE and INSERT.
<?php
$mysqli = new mysqli("127.0.0.1", "user", "pass", "db", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$sam = 1;
$stmt = $mysqli->prepare("SELECT released FROM svers");
$stmt->execute();
echo "#";
var_dump($sam);
$res = $stmt->get_result();
var_dump($res);
$row = $res->fetch_assoc();
var_dump($row);
$mysqli->close();
The host_info is displayed as "127.0.0.1 via TCP/IP" followed By the # I echoed inside the if() but can't get anything from my database. Even the other # between the $row[ ] info are not showing. Here is my code:
<?php
$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$stmt = $mysqli->prepare("SELECT * FROM svers ORDER BY released DESC LIMIT 1");
if ($result = $stmt->execute()){
echo "#";
$result = $stmt->get_result();
$row = $result->fetch_array(MYSQLI_BOTH);
echo $row['version'] . "#" . $row['released'] . "#" . $row['note'];
$stmt->free_result();
}else {
echo "error";
}
$mysqli->close();
?>
Ok problem solved. My real server didn't support mysqlnd so can't use get_result(). Thanks for the help guys!
You are saying got it working on my virtual server but can't get it working on my real server.
Then check svers table on real server contains any data.

Error while creation of tables in the selected database in Mysql

I am getting an error as A link to the server could not be established in /var/www/Test.php on line 25 and mysql_select_db(): Access denied for user 'pass'#'localhost' (using password: NO) in /var/www/Test.php on line 25 when i trying to create a tables in a created Data base.
My code:
<?php
$con = mysqli_connect("localhost","root","pass");
connection to mysql server
//checking the connection
if(mysqli_connect_errno($con))
{
echo "Sorry!Failed to connect Mysql" . mysqli_connect_error();
}
$sql = "CREATE DATABASE viral_coff";
if(mysqli_query($con,$sql))
echo "database Created Successfully!";
else
echo "error in creating the database" . mysqli_error($con);
mysql_select_db('viral_coff') or die(mysql_error());;
$tab = ' CREATE TABLE retention( '.
' playing-date DATE ,' .
' that-day INT ,' .
' 1_day INT ,' .
' 3_days INT ,' .
' 7_days INT ,' .
' 31_days INT ,)' ;
if(mysqli_query($con,$tab))
echo "Created Tables";
else
echo "Error creating table" . mysqli_error($con);
mysqli_close($con)
?>
What am i doing wrong?
mysql_ and mysqli_ functions dont work well together. Choose one of it and work with them, not both.
You're mixing mysql_* functions with mysqli_* functions. Which you of course can't!
You need to use mysqli_select_db() instead of mysql_select_db()
Also learn to put some brackets on your if statements, thereby you can be 100% sure of what is inside and outside of the statement.
You are remove password.
<?php
define('Hostname','localhost');
define('Username','root');
define('Password','');
define('DB_Name','viral_coff');
$con=mysqli_connect(Hostname,Username,Password);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create database
$sql="CREATE DATABASE ".DB_Name;
if (mysqli_query($con,$sql))
{
echo "Database ".DB_Name." created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($con);
}
$con = mysqli_connect(Hostname,Username,Password,DB_Name);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create table
$sql = "CREATE TABLE retention(playing_date DATE, that_day INT, 1_day INT , 3_days INT ,7_days INT , 31_days INT)";
// Execute query
if (mysqli_query($con,$sql))
{
echo "Table retention created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
?>

how to run mysqli server on appserv 2.5.10?

I am trying use mysqli functions but I get this error:
Fatal error: Call to undefined method mysqli::num_rows() in C:\AppServ\www\edu\files\header.php on line 19
I tried to go to php.ini and remove ; from extension=php_mysqli.dll
I found it already removed
I tried to restart appachi;
the connection file:
// db username
define("USERNAME","root");
// db password
define("PASSWORD","root");
// db servername
define("SERVERNAME","localhost");
// db name
define("NAME","edu");
//connect to db
$mysqli = new mysqli(SERVERNAME,USERNAME,PASSWORD,NAME);
if ($mysqli->connect_errno) {
echo $cannot_connect;
}
//select db encoding
$mysqli->set_charset('utf8');
calling function in a file:
$sql = $mysqli->query("SELECT VALUE FROM SITE_CONFIG WHERE CONF='KEYWORDS'");
if (!$sql) {
echo "Failed to run query: (" . $mysqli->errno . ") " . $mysqli->error;
}
if($mysqli->num_rows($sql) > 0){
while($rs = $sql->fetch_assoc()){
$keyw = $rs['VALUE'];
}
}else{
$keyw = $no_data;
}
note : I included connection.php
Try:
$sql = $mysqli->query("SELECT VALUE FROM SITE_CONFIG WHERE CONF='KEYWORDS'");
if (!$sql) {
echo "Failed to run query: (" . $mysqli->errno . ") " . $mysqli->error;
} else {
if($sql->num_rows > 0){// here must be $sql , not $mysqli
while($rs = $sql->fetch_assoc()){
echo $rs['VALUE'];
}
} else{
echo "No data";
}
}

Categories