mysqli_query not working as expected - php

I have the php:
$con=mysqli_connect("127.0.0.1","foo","bar","quaz");
if($con){
$sql = "INSERT INTO `virtual_users` (`domain_id`, `password` , `email`)
VALUES ('2', ENCRYPT('".$password."', CONCAT('\$6\$', SUBSTRING(SHA(RAND()), -16))), '".$user."#".$domain."');";
$query = mysqli_query($con, $sql);
if(!$query){
echo $sql;
}else{
echo "Success adding new email user!";
}
}
For some reason when I run this query it always returns $sql. This means that the connection is fine but the query is not.
When I then run the the echo of $sql directly on the mysql database it works perfectly!! I have no idea what is going wrong! Any ideas?

That's because you should be outputting the reason for the failure, not the query that caused the failure:
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
^^^^^^^^^^^^^^^^^^^^^^^^^^^
There's exactly ONE way for a query to succeed, and a near infinite number of ways for it to fail. Just having "valid" sql means nothing.

Related

PHP Doesn't execute MySqli Query

The majority of this code works just fine, the database get updated when I click on the button, but the last query (the UPDATE one) doesn't execute for some reason.
I tried turning on mysql log on phpmyadmin, but even there it's not executed.
It doesn't show me any error, and I really don't know what could be wrong.
$query = "SELECT username, coins FROM users WHERE userid='$userid' LIMIT 1";
$result = mysqli_query($db, $query);
$user = mysqli_fetch_assoc($result);
$_SESSION['username'] = $user['username'];
$_SESSION['coins'] = $user['coins'];
$op = $user['username'];
$op = mysqli_real_escape_string($forumdb, $op);
$postcontent = $_POST['postcontent'];
$postcontent = mysqli_real_escape_string($forumdb, $postcontent);
$posttitle = $_POST['posttitle'];
$posttitle = mysqli_real_escape_string($forumdb, $posttitle);
$sectionid = $_GET['sectionid'];
$sectionid = mysqli_real_escape_string($forumdb, $sectionid);
$query = "INSERT INTO topic (section_id, name, replies, op, lastpost, lastuserid, views, sticked) values('$sectionid', '$posttitle', '0','$op', CURRENT_TIMESTAMP(),'$userid', '0', '0')";
$result = mysqli_query($forumdb, $query) or trigger_error("Query Failed! SQL: $query - Error: ".mysqli_error($forumdb), E_USER_ERROR);
$last_id = mysqli_insert_id($forumdb);
$query = "INSERT INTO posts (topic_id, content, user_id) values('$last_id', '$postcontent', '$userid')";
mysqli_query($forumdb, $query);
$query = "UPDATE section SET lastpost='$username', threads=threads+1, posts=posts+1 WHERE id='$sectionid'";
mysqli_query($forumdb, $query) or trigger_error("Query Failed! SQL: $query - Error: ".mysqli_error($forumdb), E_USER_ERROR);
You can use the following to solve your problem:
"UPDATE `section` SET `lastpost`='$username', `threads`=threads+1, `posts`=posts+1 WHERE `id`='$sectioni
It would have been helpful if you explained what "doesn't execute for some reason" means.
Either you get an error indicating that the SQL was invalid at runtime or the execution continued and no data was changed.
Without knowing what the error was, we can't advise what would have caused an error. If execution continued, but the record was not (obviously) updated, then it must be because the WHERE clause of the update statement did not match any rows. You could verify this by checking mysqli_affected_rows().
The queries you have run previously wil be in the mysql general log. You might want to
echo the SQL statement to the output and check that it is populated as you expect

INSERT INTO Statement not working PHP/MySQLI

I've combed through this site non-stop looking for the solution to my problems but have come up empty handed still.
Here's the problem, whenever I use the following INSERT INTO statement nothing is inserted into my database, the code runs without a hitch but at the end of the day my database is still empty(excluding values I manually inserted myself).
I would also like to point out that I ran a SELECT FROM statement that returned manually inserted values from the database nicely.
Anyway here's the code:
Connecting to database
$link = mysqli_connect("localhost", "root", "", "prototype");
Insert code
if ($error) echo "There were error(s) in your signup details:".$error;
else
{
$query = "SELECT * FROM `users` WHERE email = '".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
echo $results;
if ($results) echo " This email address is already taken. Would you like to log in?";
else
{
$query = "INSERT INTO `users`(`email`, `password`) VALUES ('".mysqli_real_escape_string($link, $_POST['email']).', '.md5(md5($_POST['email']).$_POST['password'])."')";
mysqli_query($link, $query);
echo "You've been registered!";
$_SESSION['id'] = mysqli_insert_id($link);
print_r($_SESSION);
// Redirect to logged in page
}
Try to change your insert query as below
$query = "INSERT INTO `users`(`email`, `password`) VALUES ('".mysqli_real_escape_string($link, $_POST['email'])."', '".md5(md5($_POST['email']).$_POST['password'])."')";

How do I echo name, price and id from a form just submitted?

I have an issue with MySQLi and PHP.
I created a form, and once I type the desired values in and hit submit, the values are right away sent to the database. Nothing wrong with this.
What I want to happen is that: after hitting the submit button, PHP shall echo the result of the just-submitted entry. That is to say:
`INSERT INTO table VALUES (x, x, y) -> SELECT x, x, y FROM table ORDER BY id DESC LIMIT 1`
I have tried many methods to do this, but all of them either echo the previous entry (the one before the one just submitted) or plainly don't work.
I have tried mysqli_insert_id($conn) but this returns nothing.
This is where my code rests at at the moment:
$conn = mysqli_connect($server, $user, $pw, $BD);
if (!$conn) {
die ('<span style="color: #FF0000;">"connection failed: "</span>' . mysqli_connect_error());
}
$nome = $_POST['nome'];
$preco = $_POST['preco'];
$query = "INSERT INTO produtos(nome, preco) VALUES ('$nome', '$preco')";
$result = mysqli_insert_id($conn);
var_dump ($result);
if (mysqli_query($conn, $query)){
echo '<br>'."Succeeded!";
} else {
echo '<br>'."ERROR!" .'<br>'. $query ."<br>". mysqli_error($conn) .'<br><br>'. '<span style="color: #FF0000;">You have to fill all the fields.</span>';
}
mysqli_close($conn);
to note, if of any help, var_dump outputs int(0) at the moment.
Thanks in advance. I've been struggling like mad with this.
You can't get mysqli_insert_id without executing the query. Better use prepare statement to prevent from sql injection
$stmt = $conn->prepare("INSERT INTO produtos(nome, preco) VALUES (?,?)");
$stmt->bind_param('ss', $nome, $preco);
$stmt->execute();// execute query
$conn->insert_id;// get last insert id
Please see that you haven't even executed your query. On a side note, you should be aware of SQL injections and follow the below pattern:
$nome = mysqli_real_escape_string($conn, $_POST['nome']);
$preco = mysqli_real_escape_string($conn, $_POST['preco']);
$sql = "INSERT INTO produtos (nome, preco) VALUES ('".$nome."', '".$preco."')";
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$result = mysqli_insert_id($conn);
echo $result; // Check your result.
Use this:
$query = "INSERT INTO produtos(nome, preco) VALUES ('$nome', '$preco')";
$res=mysqli_query($conn,$query);
$result = mysqli_insert_id($conn);
var_dump ($result);`

I want to insert the data of second query if first query have inserted its data

i am trying to insert a data. But i am getting an error and i can't solve it any help will be really appreciated
Error: Warning: mysqli_num_rows() expects parameter 1 to be
mysqli_result, boolean given
$insert_qryy = mysqli_query($con,"Insert into user_register(name,email,phone,cphone,address,city,country,dob)
values('".$name."','".$email."','".$phone."','".$cphone."','".$address."','".$cityr."','".$country."','".$dob."')")or die(mysqli_error());
if ($insert_qryy->num_rows==0)
{
echo "Error";
}
else
{
$handler = mysqli_query($con,"INSERT INTO `addproperty`(`purpose`, `property_type`, `city`, `title`, `description`,
`property_price`, `land_area`, `expires_after`, `property_img`) VALUES('".$purpose."','".$type."','".$city."','".$title."','".$desc."','".$price."',
'".$landarea."','".$expiry."','".$im."')") or die (mysqli_error());
}
it is entering the $insert_qryy data but the second statement is not working If statement is getting false i hope I'll get my solution here
As you said - No i want to insert the data of second query if first query have inserted its data.check this once:-
$insert_qryy = mysqli_query($con,"Insert into user_register(name,email,phone,cphone,address,city,country,dob) values('".$name."','".$email."','".$phone."','".$cphone."','".$address."','".$cityr."','".$country."','".$dob."')")or die(mysqli_error($con));
if ($insert_qryy)
{
$handler = mysqli_query($con,"INSERT INTO `addproperty`( `purpose`, `property_type`, `city`, `title`, `description`,`property_price`, `land_area`, `expires_after`, `property_img`) VALUES ('".$purpose."','".$type."','".$city."','".$title."','".$desc."','".$price."','".$landarea."','".$expiry."','".$im."')") or die (mysqli_error($con));
} else{
echo "First Insert not executed properly";
}
Note:- Problem is Insert query return a boolen value true or false, based on query executed or not. So you can not use it directly in mysqli_num_rows(), because it ask for a result-set object as parameter not a boolean value.
For checking INSERT query status you can use mysqli_affected_rows or mysqli_insert_id().
$lastid = mysqli_insert_id($link);
Modified example:
$insert_qryy = mysqli_query($con,"Insert into user_register(name,email,phone,cphone,address,city,country,dob)
values ('".$name."','".$email."','".$phone."','".$cphone."','".$address."','".$cityr. "','".$country."','".$dob."')")
or die(mysqli_error());
$lastid = mysqli_insert_id($con);
if (intval($lastid) <= 0)
{
echo "Error";
}
else{
// your second query or success.
}
Use mysqli_affected_rows () function to check if data is inserted successfully into table
$insert_qryy = mysqli_query($con,"Insert into user_register(name,email,phone,cphone,address,city,country,dob) values('".$name."','".$email."','".$phone."','".$cphone."','".$address."','".$cityr."','".$country."','".$dob."')")or die(mysqli_error($con));
if (mysqli_affected_rows() > 0) //use this to check if data is inserted successfully into table
{
$handler = mysqli_query($con,"INSERT INTO `addproperty`( `purpose`, `property_type`, `city`, `title`, `description`,`property_price`, `land_area`, `expires_after`, `property_img`) VALUES ('".$purpose."','".$type."','".$city."','".$title."','".$desc."','".$price."','".$landarea."','".$expiry."','".$im."')") or die (mysqli_error($con));
}
else
{
echo "something went wrong!!! at first query insertion";
}

Test for duplicates in a Mysql database?

so I have a simple newsletter signup form. I can add users into the database, but I want to account for duplicate emails. This is what I have right now.
$result = mysql_query("SELECT * FROM Users WHERE Email='$email'");
$num_rows = mysql_num_rows($result);
if($num_rows){
echo "You've already registered! Thanks anyway";
}
else{
mysqli_query($db_connection, "INSERT INTO Users (Name, Email) VALUES('$name' , '$email')");
echo "Thanks for signing up, $name.";
}
When I click submit, it will add it to the database, regardless if the email is the same.
The mysql_query that gets $result is fine. However, for some reason the if statement doesn't get called. Any idea why?
"The mysql_query that gets $result is fine"
Your DB connection sounds to be mysql_ - and you're using mysqli_ functions below that.
Use mysqli_ exclusively and do not mix them, they don't.
Sidenote: Your question is confusing.
You state: When I click submit, it will add it to the database, regardless if the email is the same. - then you say The mysql_query that gets $result is fine.
This: if($num_rows) should be if($num_rows >0)
Use this for your DB connection:
$db_connection = mysqli_connect("your_host","user","password","your_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
then do:
$result = mysqli_query($db_connection, "SELECT * FROM Users WHERE Email='$email'");
$num_rows = mysqli_num_rows($result);
if($num_rows >0){
echo "You've already registered! Thanks anyway";
exit;
}
else{
mysqli_query($db_connection, "INSERT INTO Users (Name, Email) VALUES('$name' , '$email')");
echo "Thanks for signing up, $name.";
}
Use http://php.net/manual/en/mysqli.error.php on your query.
I.e.: or die(mysqli_error($db_connection))
Warning
Your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements.
Footnotes:
If you want to avoid duplicates, set your column(s) as UNIQUE.

Categories