Unable to INSERT any records in MYSQL from PHP - php

So I am trying to develop an app and I need an API, so I am trying now PHP in order to pass my variables from the app to the MYSQL. I am trying with $_GET first in order to see if everything works fine. I tried to pass variables to the database through MYSQL Workbench and then from the app and worked fine. But, when I emptied the table and tried again it didn't work! So I am guessing that my loop doesn't respond well to the fact that my table is empty(?)
This is the code that checks for the email and username if exists and if not insert the variables:
$result = 'notSet';
$query=mysql_query("SELECT * FROM project");
while ($row = mysql_fetch_assoc($query)) {
if(strcmp($row['email'],$email)==0){ //strcmp uses two strings and it returns an integer, if 0 then no differences if more than 0 then there are
$result = 'Email exists';
}else{
if(strcmp($row['username'],$username)==0){
$result = 'Username exists';
}else{
//encryption
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
}
}
Any ideas??

Your table is empty. $query is returning false. Because of this your loop is not executed. You should change the code like this:
if($query){
while(){
//check username and email
}
}
else{
// execute insert query
}
Can you try this code:
$result = 'notSet';
$query = mysql_query("SELECT * FROM project WHERE email = '$email' OR username = '$username' ");
if(mysql_num_rows($query) === 0 ){
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
else{
$result = 'Username or Email exists';
}

We should add single quotes ' only if field type is not integer type. For eg if userid field is integer type and rest of fields are not integer type then query will be
$insert = mysql_query("INSERT INTO project VALUES ($userid, '$fullname','$username','$password','$course','$year','$age','$email')") or die(mysql_error());
thanks

First: you should switch to PDO or mysqli, because the mysql_* functions are deprecated. Please follow the links in Shais comment.
To get the INSERT done, you've got to change your logic. With your code right now, it will never be executed for an empty resultset. You could do it so:
$query=mysql_query("SELECT * FROM project");
if (mysql_num_rows($query) > 0) {
// we've got results, let's loop through the resultset
while($row = mysql_fetch_assoc($query)) {
// do something with the result
}
}
else {
// we've got no results,
// do the insert
}
mysql_query will return a resource for SELECT type queries. A resource evaluates in PHP to true. You can use mysql_num_rows() to check, whether your resultset is not empty.
Excerpt from the linked manual:
Use mysql_num_rows() to find out how many rows were returned for a
SELECT statement
PS: Please consider the content of the red box.

<?php
$query=mysql_query("INSERT INTO project set id=$userid,
'fullname'=$fullname,
'username'=$username,
'password'=$password,
'course'=$course,
'year'=$year,
'age'=$age,
'email'=$email
");
?>

Related

Need to add count(*) to this file and an if statement

When I change SELECT * to SELECT count(*) the script stops working altogether. How to I add a count(*) to this file and a statement if row count for $user >= 20 allow to INSERT else do nothing.
// Include needed files
include 'mysql.php';
// Connect to MySQL
connectMySQL();
//****** SECURITY CHECK *********
session_start();
if(isset($_SESSION['userid'])){
$user = mysql_real_escape_string($_SESSION['userid']);
//*******************************
// Retrieves variables through AJAX
$favid = mysql_real_escape_string($_GET['favid']);
// $favid = mysql_real_escape_string($_GET['favid']);
// Firstly, check if article is favourite or not
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
$matches = mysql_num_rows($query);
// If it is not favourited, add as favourite
if($matches == '0'){
mysql_query("INSERT INTO ajaxfavourites (user, favid, exptime) VALUES ('$user', '$favid', CURRENT_TIMESTAMP)");
echo "";
}
// Instead, if it is favourited, then remove from favourites
if($matches != '0'){
mysql_query("DELETE FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
echo "";
}
} else {
// Someone tries to directly access the file!
echo "Invalid session!";
}
Thanks!
Please do necessary steps to avoid SQL injection, also try using mysqli_* functions instead of mysql_* functions
$query = mysql_query("SELECT COUNT(*) as cnt FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
$res = mysql_fetch_array($query);
// If it is not favourited, add as favourite
if($res[cnt] == 0){
mysql_query("INSERT INTO ajaxfavourites (user, favid, exptime) VALUES ('$user', '$favid', CURRENT_TIMESTAMP)");
echo "";
}
// Instead, if it is favourited, then remove from favourites
if($res[cnt] > 0){
mysql_query("DELETE FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
echo "";
}
I got it resolved. The reason it wasn't working was it took both values into consideration ($user and $favid). As a result it was always either 0 or 1.
I had to create another mysql query with just one value in it ($user) and then I was able to get the row count. Thanks everyone!
try to use below query, using below query if requested user's session will be 20+ then only insert statement will execute else insert statement will be ignore.
INSERT INTO ajaxfavourites(USER,favid ,exptime)
SELECT 1 AS USER, 1 AS favid, NOW() AS exptime
FROM ajaxfavourites WHERE USER=1 HAVING COUNT(*) >=20;

How to do checking in sql?

$sql = "SELECT *
FROM users
WHERE username = '$username' AND s_id = '$s_id'";
$result = mysql_query($sql);
if (($result) == 1) {
$errorMessage = 'Username or Student ID already taken. Choose another one';
} else {
$sql = "INSERT INTO users VALUES ('$username','$password','$f_name','$l_name','$s_id','$email')";
mysql_query($sql);
$errorMessage = 'Registration is Successful. You can Login Now.';
}
Hello, i just want to ask why the sql statement didn't read the first statement which is if there have the same username and s_id the user should change it. But it will print successful inserted into database but the data didn't have in the database because the username or s_id already have in database. Is there have any syntax error? Please help me
Use mysql_num_rows to count/compare rows. ($result) > 0 is more better then ($result) == 1
Change from
if (($result) == 1) {
To
if(mysql_num_rows($result) > 0) {
Warning: MYSQL extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
Very nice question, people always get confused by this problem. Firstly, skip the code. Question yourself, what does a SELECT statement return? It returns a table if it succeeds.
Now, tell me can u compare a table with the value 1? The answer is no, u don't. What you have to do is to first compute the number of row of the table. And as your userId is unique, you will find one row(if matches) or zero row(if doesn't match) always.
So check if that number of row is one or not. How to do it?
Change your code like that,
$sql = "SELECT *
FROM users
WHERE username = '$username' AND s_id = '$s_id'";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1) {
$errorMessage = 'Username or Student ID already taken. Choose another one';
} else {
$sql = "INSERT INTO users VALUES ('$username','$password','$f_name','$l_name','$s_id','$email')";
mysql_query($sql);
$errorMessage = 'Registration is Successful. You can Login Now.';
}
As included in previous answer,
MYSQL extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
Because mysql_query() returns TRUE on success or FALSE on error.
use mysql_num_rows instead
And you can increase performance when you use SELECT count(*) FROM ... and check if the result (with mysql_result function) is greater than 0:
$sql = "SELECT count(*)
FROM users
WHERE username = '$username'
AND s_id = '$s_id'";
$result = mysql_query($sql);
if (mysql_result($result, 0, 1) > 0) {
$errorMessage = 'Username or Student ID already taken. Choose another one';
} else {
$sql = "INSERT INTO users VALUES ('$username','$password','$f_name','$l_name','$s_id','$email')";
if (mysql_query($sql)) {
$errorMessage = 'Registration is Successful. You can Login Now.';
} else {
$errorMessage = 'An error occurred.';
}
}
Your student table ID should be primary key -- thus no need to check name
$pdo = 'mysql:host=' . $host . ';dbname=' . $db;
$dbL = new PDO($pdo, $user, $pass);
$sql = 'SELECT 1 FROM users WHERE s_id = '. ceil($s_id);
$sth = $dbL->prepare($sql);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_NUM);
if ($row[0]) {
//already exists
} else {
//new record and save it
}

PHP & MySQL Search Column for value

I am a little confused about how $query works and how I can find a value... Say I have a checkuser.php script. The purpose here is to echo "Correct" if the user already exists. I have the columns (username, password, email). What I want to know is how can I search the column username for value $username? This is what I have currently:
$query = sprintf("SELECT * FROM users WHERE CONCAT(username) LIKE '$u'");
$result = mysql_query($query);
if(mysql_num_rows($result) != 1)
echo "Username Not Found";
Thanks!
This should work. However, I didn't test it:
$query = "SELECT * FROM users WHERE username = '$u'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
echo "Username Not Found";
In your query, you do not need to use the sprintf() function at all. an SQL query is inserted as a regular string.
Furthermore you don't need to use CONCAT() SQL function either.
Then if you want to check against an exact string you can just compare with the = operator instead of using SQL LIKE statement.
I haven't tested it, but this should work:
$q=mysql_query("select ysername from user where username='$u'");
$count=mysql_num_rows($q);
If ($count>0) { echo "usename fount";};

show row data from a specific ID

I'm building a simple bug tracking tool.
You can create new projects, when you create a project you have to fill in a form, that form posts to project.class.php (which is this code)
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_real_escape_string($sql);
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php?id='.mysql_insert_id());
}
else {
echo "There is something wrong. Try again later.";
}
mysql_close();
(It's not yet sql injection prove, far from complete...)
Eventually you get redirected to the unique project page, which is linked to the id that is stored in the MySQL db. I want to show the name of that project on the page, but it always shows the name of the first project in the database.
(here I select the data from the MySQL db.)
$query = 'SELECT CONCAT(name)
AS name FROM projects';
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
(here I show the name of the project on my page, but it's always the name of the first project in the MySQL db)
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
How can I show the name of the right project? The one that is linked with the id?
Do I have the use WHERE .... ?
Yes, You have to use the WHERE to specify which project You want to get. I'm also not sure why are You using CONCAT function when You want to get only one project.
Other important thing is that You have to use mysql_real_escape_string() function on parameters before You put them in the query string. And use apropriate functions for specific type of data You receive.
So Your statement for getting the project should look like this:
SELECT name FROM projects WHERE id = ' . intval($_GET['id'])
Also when before You use the mysql_fetch_assoc() function, check if there are any records in the result with
if(mysql_num_rows($result) > 0)
{
$project = mysql_fetch_assoc($result);
/* $project['name'] */
}
try this
// first get the id, if from the url use $_GET['id']
$id = "2";
$query = "SELECT `name` FROM `projects` WHERE `id`='".intval($id). "'";
$result = mysql_query(mysql_real_escape_string($query));
use mysql_fetch_row, here you'll not have to loop through each record, just returns single row
// if you want to fetch single record from db
// then use mysql_fetch_row()
$row = mysql_fetch_row($result);
if($row) {
echo '<h5>'.$row[0].'</h5>';
}
$row[0] indicates the first field mentioned in your select query, here its name
The might be of assistance:
Your are currently assing a query string parameter projectpage.php?id=
When you access the page the sql must pick up and filter on the query string parameter like this:
$query = 'SELECT CONCAT(name) AS name FROM projects WHERE projectid ='. $_GET["id"];
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
Also maybe move mysql_insert_id() to right after assigning the result just to be safe.
$result = mysql_query($sql);
$insertId = mysql_insert_id();
Then when you assign it to the querystring just use the parameter and also the
header('Location: ../projectpage.php?id='.$insertId);

Postgresql INSERT INTO using PHP not working

What is wrong here? I get the table usertable fine. I've made sure that the column name uid is there. But when I try to get uids from a query, nothing comes back. That is fine as the table is empty. However, my INSERT INTO command is not working because after the INSERT INTO, I still don't have uids coming back. Using Postgres 9.1.5. Thanks!
$query = "SELECT * FROM information_schema.tables WHERE table_name = 'usertable';";
$result = pg_query($dbconn, $query);
if (pg_num_rows($result))
{
echo "Table exists<br>";
checkForUserRow();
}
else
{
echo "Error on query, attempting to create table<br>";
$sql = "CREATE TABLE usertable (uid integer PRIMARY KEY, sign varchar(255));";
pg_query($dbconn, $sql) or die(pg_errormessage());
$result = pg_query($dbconn,$query);
if (pg_num_rows($result)) {
echo "Table created<br>";
checkForUserRow();
}
}
pg_close($conn);
function checkForUserRow()
{
$query = "SELECT uid FROM usertable WHERE uid = '123'";
$result = pg_query($dbconn, $query);
if(pg_num_rows($result))
{
echo "User DB row exists<br>";
}
else
{
echo "User row does not exist - attempt to add user to table<br/>";
$sql = "INSERT INTO usertable (uid) VALUES('123')";
pg_query($dbconn, $sql);
$result = pg_query($dbconn, $query);
if (pg_num_rows($result))
{
echo "User successfully added!<br/>";
}
else
{
echo "User not added :(";
}
}
Inside your function, you need to get the global $dbconn:
function checkForUserRow()
{
global $dbconn;
// everything else
}
This is because when you do pg_query($dbconn, $query); inside of the function, it's using the local version of $dbconn, which doesn't exist.
You can also choose to pass in $dbconn as a parameter if you wish:
function checkForUserRow($dbconn)
{
// global $dbconn; // Don't need this anymore.
// everything else
}
If you start with an empty table, then this:
if (pg_num_rows($result))
will always evaluate as false. This means you will always try to create a new table (which will fail since table exists triggering die(pg_errormessage());.
This means checkForUserRow() will never be called.
Even if it was called, $dbconn doesn't exist in the scope of your checkForUserRow() function, meaning none of your queries will ever work in this function.
Rudimentary debugging and review of error messages on your part would show you how your execution path is not working properly.
Also this line of code:
pg_close($conn);
refers to a different variable name for the DB connection then used elsewhere.

Categories