IS NOT NULL giving null values - php

I have the following PHP code using PDO. I want rows with empty values to not appear in the results. How do I achieve this, and what am I doing wrong below?
<?php
require_once 'dbconfig.php';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
echo "Connected to $dbname at $host successfully.";
$sql = 'SELECT *
FROM as_questions
WHERE Answer IS NOT NULL';
$q = $conn->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}

As above suggested by two persons (Fred -ii and Alex Anderi) please change your query like below:-
$sql = "SELECT * FROM as_questions WHERE Answer !=''";

Related

PHP SQL request returning null value

I'm just starting PHP and keep returning null for my SQL query. I am successfully connected to the database and have copied and pasted the query even straight from the database.
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "customerbasics";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `orders`";
$result = $conn->query($sql);
if ($result == NULL){
echo 'No results';
};
if ($result->num_rows > 0) {
echo 'Rows returned';
}
} else {
echo "0 results";
}
$conn->close();
?>
This is what the browswer prints:
Update: Error checking added:
Fatal error: Uncaught mysqli_sql_exception: No database selected
Add the fourth parameter to your connection function
$conn = new mysqli($servername, $username, $password, $dbname);
You have forgotten the database name in your connection. For more information, you can go here. Plus I recommend you to learn PDO or prepared statements
First, you have to select database before executing a query:
mysqli_select_db($conn, $dbname);
Then execute your query:
$sql = "SELECT * FROM `orders`";
Other way, you can also specify database name directly every executing a query:
$sql = "SELECT * FROM $dbname.`orders`";

Inserting ID from primary col to another table

I want to insert 2 tables columns ids to another table
I got the query but there is the annoying error.
I tried to solve this problem for hours none worked :(
This code:
$query = "INSERT INTO
groups(
group_school_id,
group_teacher_id,
group_name,
group_note,
group_system,
group_students_count
)
VALUES(
$group_shcool_id,
$group_teacher_id,
'$group_name',
'$group_note',
'$group_system',
'$group_students_count'
)";
this old:
<?php
$db['db_host'] = "localhost";
$db['db_user'] = "admin";
$db['db_pass'] = "1998";
$db['db_name'] = "ahlquran";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
mysqli_query($con, "SET NAMES 'utf8'");
}
?>
this new:
<?php
// if you are using php just don't forget to add php tags though
$db['db_host'] = "localhost";
$db['db_user'] = "admin";
$db['db_pass'] = "1998";
$db['db_name'] = "ahlquran";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
//using try catch statements
try{
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully Connected";
}
catch(PDOException $e){
echo "Connection Failed" .$e->getMessage();
}
?>
its connects successfully but all my code use the old one, how to change to convert it? I dont know what pdo I like to learn it, it seems more pro type, but is there solution for this site only using mysqli?
sorry for the long post this is my 1st one, dont know how to explain enough
Thanks
give this error :
QUERY FAILED .You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , 'test', '', 'test' at line 11
I thought it will work fine like this but I think the problem with the query syntax.
Just an advice try to use PDO prepared statements example below:
$query = "INSERT INTO groups(group_school_id,
group_teacher_id,
group_name,
group_note,
group_system,
group_students_count)
VALUES (:gsid,:gtid,:gname,:gnote,:gsystem,:gstudcount)";
//assuming $conn is your object variable name for database connection
$stmnt = $conn->prepare($query);
$stmnt->execute(array(':gsid'=>$group_school_id,
':gtid'=>$group_teacher_id,
':gname'=>$group_name,
':gnote'=>$group_note,
':gsystem'=>$group_system,
':gstudcount'=>$group_students_count));
//to check if you have inserted data into your table
$rows = $stmnt->rowCount();
echo "Inserted ".$rows." row";
the :gsid are placeholders for your variables, also make sure that each variable passed are inline with column datatypes in your database
//if you are using php just don't forget to add php tags though
$dbhost = "localhost";
$dbname = "whatevername";
$dbuser = "root";
$dbpass = "";
//using try catch statements
try{
$conn = new PDO('mysql:host='.$dbhost.';dbname='.$dbname, $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully Connected";
}
catch(PDOException $e){
echo "Connection Failed" .$e->getMessage();
}

How do I reconnect my web pages on my website after updating to PHP 7 with a MySQL database 5.0.0?<?

I added the i updates to communicate with the database & now the page links don't work.
<?php
// Connect to database
$link=mysqli_connect('localhost', 'xxxxx', 'xxxxx');
mysqli_select_db($link, 'waddellc_PHRDB');
$sql = "SELECT * FROM quotes ORDER BY id";
$result = mysqli_query($link, $sql) or die(mysql_error());
$tenant_quotes = array();
$owner_quotes = array();
while($row = mysqli_fetch_array($result)) {
This should do the work, using PDO :
$servername = "localhost";
$username = "username";
$password = "password123";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=databaseName", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(!is_null($conn)){
$stmt = $conn->prepare("SELECT * FROM quotes ORDER BY id");
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
}
I also think you need to update your database, it's quite old now.

MySQL and PHP gives me null var

I make a random quote app, in which by pressing a button, i can load one random phrase. I created for this a MySQL database, and two php code.
I upload my two code in a web hosting, and the app is running!
But sometime it gives me "null" instead of the phrase. I don't know why.
I'm not very good with this.
What is probably the problem?
This is my index.php
require_once 'db.php';
$query = "SELECT * FROM quotes ORDER BY rand() LIMIT 1";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result)) {
print(json_encode($row['quote']));
}
And this is my db.php
// Create connection
$con=mysqli_connect("host","user","pass","a6361246_phrases");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
You can use the first three lines in your db.php file like this...
<?php
$host = 'localhost'; $db = 'database-name'; $user = 'database-user'; $pw = 'database-password';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
Don't forget to change database-name, database-user & database-password to your specific credentials.
Then using PDO get your phrase like this...
<?php
require_once 'db.php';
try {
$sql = "SELECT * FROM Quotes ORDER BY rand() LIMIT 1";
$query = $conn->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Could not get the data: " . $e->getMessage());
}
?>

PHP insert query not working

<html>
<body>
<?php
$host = 'localhost';
$user = 'users';
$pw = '';
$db = '#######';
$connect = mysql_connect($host,$user,$pw)
or die ("Could not connect.");
mysql_select_db($db);
$sql = mysql_query("INSERT INTO users VALUES ('','l','l','l','l','l','l')");
if(mysql_query($sql)){
print "Item added successfully.<br/>";
}
else{
print "Item addition failed.<br/>";
}
?>
</body>
</html>
I am trying to insert these values into my database into the table users but when I run the code it keeps on saying "item addition failed" but I am not sure why, there is no problem with the database connection as I have already tested that, and I am not sure what's wrong with my insert query?
There are some problems in your code. Firstly you do query twice. Secondly are you sure your db name is $db = '#######'; change it to proper name.
To check if query was ok and if rows were added use mysql_affected_rows() to check errors use mysql_error()
Also change your sql engine to PDO or mysqli which are better.
Please mind that Mysql_* functions are depracated. That is why I've given you example how to use db connection in PDO.
<?php
$host = 'localhost';
$user = 'users';
$pw = '';
$db = '#######'; //CHANGE IT TO PROPER NAME WHERE TABLE users IS!
$connect = mysql_connect($host,$user,$pw)
or die ("Could not connect.");
mysql_select_db($db);
$sql = mysql_query( "INSERT INTO users VALUES('' ,'l','l','l','l', 'l','l')") or die(mysql_error());
if(mysql_affected_rows()>0)
echo "Item added successfully.<br/>";
else
echo "Item addition failed.<br/>";
?>
I'll give you proper example how to do it with PDO cause if you still learn it'll help you :)
PDO example
<?php
$dsn = 'mysql:dbname=YOUR_DB_NAME;host=localhost';
$user = 'users';
$password = '';
try {
$dbh = new PDO($dsn, $user, $password);
$count = $dbh->exec("INSERT INTO users VALUES('' ,'l','l','l','l', 'l','l');");
echo $cout ? "Item added successfully" : "Item addition failed";
} catch (PDOException $e) {
echo 'Failed: ' . $e->getMessage();
}
?>
The secure and good way to insert values is using prepared statements.
To create prepared statement you use
$stmt = $dbh->prepare("INSERT INTO users (name, email) VALUES(?,?)");
$stmt->execute( array('user', 'user#example.com'));
You can learn more here
You are using mysql_query twice. Change your code to:
$sql = "INSERT INTO users VALUES ('' ,'l','l','l','l', 'l','l')";
try this.your called function mysql_query() twice.
on second time you passed it the result_set instead of query.
<html>
<body>
<?php
$host = 'localhost';
$user = 'users';
$pw = '';
$db = '#######';
$connect = mysql_connect($host,$user,$pw)
or die ("Could not connect.");
mysql_select_db($db);
$sql = mysql_query( "INSERT INTO users
VALUES('' ,'l','l','l','l', 'l','l')");
if($sql){
print "Item added successfully.<br/>";
}
else { print "Item addition failed.<br/>"; }
?>
</body>
</html>
This should help you debug, you should look into PDO instead though... And of course remember to use the correct credentials, i presume you have removed them for safety :-)
mysql_select_db($db);
$sql = mysql_query("INSERT INTO users VALUES ('','l','l','l','l','l','l')", $connect) OR die(mysql_error());
if($sql)
{
print "Item added successfully.<br/>";
}
else{
print "Item addition failed.<br/>";
}
?>

Categories